From: Steve Sutton Date: Tue, 4 Nov 2014 18:21:27 +0000 (-0500) Subject: convert to git X-Git-Url: http://cvs2.gaslightmedia.com/gitweb/?a=commitdiff_plain;h=f45cecd35d812728e2e4970645c3edff448bdfe2;p=web%2Fwww.gaslightmedia.com.git convert to git --- f45cecd35d812728e2e4970645c3edff448bdfe2 diff --git a/.cvsignore b/.cvsignore new file mode 100644 index 0000000..027f934 --- /dev/null +++ b/.cvsignore @@ -0,0 +1,2 @@ +uploads uploads.tar + diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..d03dc14 --- /dev/null +++ b/.htaccess @@ -0,0 +1,57 @@ + +Order allow,deny +Deny from all + + +Order allow,deny +Deny from all + + +Order allow,deny +Deny from all + +#Options -MultiViews +#ErrorDocument 404 /404.html +RewriteEngine On +AddDefaultCharset utf-8 +#RewriteBase /www.gaslightmedia.com/ +##RewriteCond %{HTTP_HOST} !^(.*)\.gaslightmedia\.com$ [NC] +##RewriteRule ^(.*)$ http://www.gaslightmedia.com.com/$1 [R=301,L] +RewriteCond %{HTTP_HOST} !^(.*)\.gaslightmedia\.com$ [NC] +RewriteRule ^(.*)$ http://www.gaslightmedia.com/$1 [R=301,L] + +Redirect 301 /connectivity/dsl_wireless_service_agreement.html http://www.gaslightmedia.com/dslwireless-service-agreement-121/ +# Press +RewriteRule press-archives/$ index.php?catid=3&archive=1 [L] +RewriteRule press/([0-9]*)/$ index.php?catid=3&press_id=$1 [L] + +# isp recent connected +RewriteRule ^isp-portfolio-detail-([0-9]*)/([0-9]*)/$ index.php?catid=$1&pcatid=$1&busid=$2 [L] +RewriteRule ^isp/.*-([0-9]*)/$ index.php?catid=$1 [L] +RewriteRule ^isp/.*-([0-9]*)/([0-9]*)/$ index.php?catid=$1&pcatid=$2 [L] + +# web portfolio +RewriteRule ^portfolio-category/.*-([0-9]*)/$ index.php?catid=100&pcatid=$1 [L] +RewriteRule ^portfolio-detail-([0-9]*)/([0-9]*)/$ index.php?catid=100&pcatid=$1&busid=$2 [L] +RewriteRule ^web/.*-([0-9]*)/$ index.php?catid=$1 [L] +RewriteRule ^web/.*-([0-9]*)/([0-9]*)/$ index.php?catid=$1&pcatid=$2 [L] +RewriteRule ^web/.*-([0-9]*)/([0-9]*)/([0-9]*)/$ index.php?catid=$1&pcatid=$2&id=$3 [L] + +# rewrites for the toolbox pages +RewriteRule ^.*-([0-9]*)/index.php index\.php?%{QUERY_STRING} +RewriteRule ^.*-([0-9]*)/$ index\.php?catid=$1 [L] + +#RewriteRule site-map index.php?catid=1&sitemap=1 +AddType application/x-httpd-php .tpl + +# short urls +RewriteCond %{REQUEST_URI} !(^.*-([0-9]*)/$) +RewriteCond %{REQUEST_URI} !(^support|^mac|^pc|^join|^meeting) +RewriteRule ^([A-Za-z0-9_-]*)/$ index.php?glmPage=$1 [L] + +# Redirects +RewriteRule ^jobs http://www.gaslightmedia.com/job-openings-131/ +RewriteRule ^jobs/ http://www.gaslightmedia.com/job-openings-131/ +RewriteRule ^billpay https://ws3.gaslightmedia.com/www/index.php?catid=117 +RewriteRule ^wsa http://www.gaslightmedia.com/wireless-service-agreement-136/ +RewriteRule ^responsivedesign http://www.gaslightmedia.com/portfolio-category/Responsive-Design--82/ diff --git a/.htaccess-old b/.htaccess-old new file mode 100644 index 0000000..07c1afd --- /dev/null +++ b/.htaccess-old @@ -0,0 +1,55 @@ + +Order allow,deny +Deny from all + + +Order allow,deny +Deny from all + + +Order allow,deny +Deny from all + +#Options -MultiViews +#ErrorDocument 404 /404.html +RewriteEngine On +AddDefaultCharset utf-8 +#RewriteBase /www.gaslightmedia.com/ +RewriteCond %{HTTP_HOST} !^(.*)\.gaslightmedia\.com$ [NC] +RewriteRule ^(.*)$ http://www.gaslightmedia.com.com/$1 [R=301,L] + +Redirect 301 /connectivity/dsl_wireless_service_agreement.html http://www.gaslightmedia.com/dslwireless-service-agreement-121/ +# Press +RewriteRule press-archives/$ index.php?catid=3&archive=1 [L] +RewriteRule press/([0-9]*)/$ index.php?catid=3&press_id=$1 [L] + +# isp recent connected +RewriteRule ^isp-portfolio-detail-([0-9]*)/([0-9]*)/$ index.php?catid=$1&pcatid=$1&busid=$2 [L] +RewriteRule ^isp/.*-([0-9]*)/$ index.php?catid=$1 [L] +RewriteRule ^isp/.*-([0-9]*)/([0-9]*)/$ index.php?catid=$1&pcatid=$2 [L] + +# web portfolio +RewriteRule ^portfolio-category/.*-([0-9]*)/$ index.php?catid=100&pcatid=$1 [L] +RewriteRule ^portfolio-detail-([0-9]*)/([0-9]*)/$ index.php?catid=100&pcatid=$1&busid=$2 [L] +RewriteRule ^web/.*-([0-9]*)/$ index.php?catid=$1 [L] +RewriteRule ^web/.*-([0-9]*)/([0-9]*)/$ index.php?catid=$1&pcatid=$2 [L] +RewriteRule ^web/.*-([0-9]*)/([0-9]*)/([0-9]*)/$ index.php?catid=$1&pcatid=$2&id=$3 [L] + +# rewrites for the toolbox pages +RewriteRule ^.*-([0-9]*)/index.php index\.php?%{QUERY_STRING} +RewriteRule ^.*-([0-9]*)/$ index\.php?catid=$1 [L] + +#RewriteRule site-map index.php?catid=1&sitemap=1 +AddType application/x-httpd-php .tpl + +# short urls +RewriteCond %{REQUEST_URI} !(^.*-([0-9]*)/$) +RewriteCond %{REQUEST_URI} !(^support|^mac|^pc|^join|^meeting) +RewriteRule ^([A-Za-z0-9_-]*)/$ index.php?glmPage=$1 [L] + +# Redirects +RewriteRule ^jobs http://www.gaslightmedia.com/job-openings-131/ +RewriteRule ^jobs/ http://www.gaslightmedia.com/job-openings-131/ +RewriteRule ^billpay https://ws3.gaslightmedia.com/www/index.php?catid=117 +RewriteRule ^wsa http://www.gaslightmedia.com/wireless-service-agreement-136/ +RewriteRule ^responsivedesign http://www.gaslightmedia.com/portfolio-category/Responsive-Design--82/ diff --git a/GLM_site_check.phtml b/GLM_site_check.phtml new file mode 100644 index 0000000..91236ba --- /dev/null +++ b/GLM_site_check.phtml @@ -0,0 +1,12 @@ + diff --git a/Toolkit/.htaccess b/Toolkit/.htaccess new file mode 100644 index 0000000..532b751 --- /dev/null +++ b/Toolkit/.htaccess @@ -0,0 +1,2 @@ +#IndexIgnore */* +#Options All -Indexes diff --git a/Toolkit/Banners.php b/Toolkit/Banners.php new file mode 100644 index 0000000..6ce0bfc --- /dev/null +++ b/Toolkit/Banners.php @@ -0,0 +1,392 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Banners.php,v 1.1.1.1 2009/09/17 20:08:55 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Create, process and display banners + * + * @category Banners + * @package Toolkit_Banners + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Banners +{ + // {{{ properties + + /** + * Holds the subnav li links + * + * @var string + * @access protected + */ + protected $nav; + + /** + * Holds the sub-navigation array + * + * @var array + * @access protected + */ + protected $navConfig = array(); + + /** + * Whether bottom banners should be turned on or off + * + * @var Const + * @access Public + */ + const BOTTOM_BANNERS = true; + + /** + * Whether side banners should be turned on or off + * + * @var Const + * @access Public + */ + const SIDE_BANNERS = false; + + /** + * Whether this client has a memberdb or not + * + * This directly effects how the create/edit forms for the banner render + * as well as how the banners are displayed on the front end. When this is + * is turned on, extra select elements appear on the create/edit forms + * that allow a user to associate a banner w/ member categories. And + * on the front end, banners associated w/ categories will show up on + * the pages. + * + * FYI: A banner can be associated w/ a member category BUT NOT a + * toolbox navigational page and still show on that page IFF the member + * member category was assigned to that page. + * + * @var Const + * @access Public + */ + const HAS_MEMBER_DB = true; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB + * + * @return void + * @access public + */ + public function __construct(PDO $pdo) + { + $this->dbh = $pdo; + if (!empty($_GET['type'])) { + $this->setupDefines(); + } + } + + // }}} + + // {{{ createNav() + + /** + * Creates the subnav links for the admin + * + * @return void + * + * @author Jamie Kahgee + * @access Public + */ + public function createNav() + { + $subnav = array( + 'List Banners' => 'banners.php?action=listBanners', + ); + + if (self::BOTTOM_BANNERS) { + $subnav['Create Bottom Banner'] + = 'banners.php?type=bottom&action=editBottomBanner'; + } + if (self::SIDE_BANNERS) { + $subnav['Create Side Banner'] + = 'banners.php?type=side&action=editSideBanner'; + } + + $this->navConfig = $subnav; + if (!is_array($this->navConfig)) { + $this->navConfig = (array)$this->navConfig; + } + if (array_walk($this->navConfig, array($this, 'makeLiLinks'))) { + echo '
    '.$this->nav.'
'; + } + } + + // }}} + + // {{{ &factory() + + /** + * Provides an interface for generating Banner:: objects of various types + * + * @param String $driver The kind of Banner:: object to instantiate. + * + * @return Object Banner an instance of the driver class or if fails + * a PEAR error. + * + * @author Jamie Kahgee + * @access Public + */ + public function &factory($driver) + { + $class = "Toolkit_Banners_$driver"; + $file = BASE . str_replace('_', '/', $class) . '.php'; + // The class for the driver should reside in this file + // if it doesn't, we have an error. + if (file_exists($file)) { + // The file exists, now make sure the class exists, + // class_exists calls __autoload by default, so it should + // automatically load the file when testing for its existance + if (class_exists($class)) { + // Get all function arguments passed in. + $params = func_get_args(); + // remove the first argument, driver name, and convert + // to a string delimited by commas so we can pass off + // to class constructor call. + $args = implode(', ', (array_splice($params, 1))); + + $instantiatedClass =& new $class($$args); + return $instantiatedClass; + } else { + return PEAR::raiseError("Class $driver does not exist in $file"); + } + } else { + return PEAR::raiseError("Unable to find class for driver $driver"); + } + } + + // }}} + + // {{{ makeLiLinks() + + /** + * Assists the createNav function for creating the subnav in admin + * + * @param string $link the url to the page + * @param string $name name of the link + * + * @return void + * + * @author Jamie Kahgee + * @access Protected + * @see Toolkit_Banners::createNav() + */ + protected function makeLiLinks($link, $name) + { + $url = parse_url($link); + $action = end(explode('=', $url['query'])); + if ($_GET['action'] == $action) { + $attr = ' id="current"'; + } + $this->nav .= ''.$name.''; + } + + // }}} + + // {{{ setupDefines() + + /** + * Setup all the defines needed to make this application run correctly + * + * This function can be called statically. It will sets up the defines + * when call that will tell the create/edit forms where to put the + * banner images. And tells the front end display where to look for the + * images when displaying banners. + * + * @param string $position What kind of banner are we talking + * about? ('bottom' or 'side') + * + * @return void + * + * @author Jamie Kahgee + * @access Public + */ + static public function setupDefines($position = null) + { + $type = is_null($position) ? $_GET['type'] : $position; + + // BANNER IMAGE PATHS + + /** + * Path to original banner images + */ + define('BANNER_ORIGINAL_PATH', BASE."images/banner_{$type}_original/"); + + + /** + * Path to resized banner images + */ + define('BANNER_RESIZED_PATH', BASE."images/banner_{$type}_resized/"); + + + /** + * Path to midsized banner images + */ + define('BANNER_MIDSIZED_PATH', BASE."images/banner_{$type}_midsized/"); + + + /** + * Path to thumbnail banner images + */ + define('BANNER_THUMB_PATH', BASE."images/banner_{$type}_thumb/"); + + // Adjust the umask to ensure we set the directory permissions properly + // And get the old umask value so we can reset it later. + $oldUmask = umask(0); + if (!is_dir(BANNER_ORIGINAL_PATH)) { + mkdir(BANNER_ORIGINAL_PATH, 0770, true); + } + if (!is_dir(BANNER_RESIZED_PATH)) { + mkdir(BANNER_RESIZED_PATH, 0770, true); + } + if (!is_dir(BANNER_MIDSIZED_PATH)) { + mkdir(BANNER_MIDSIZED_PATH, 0770, true); + } + if (!is_dir(BANNER_THUMB_PATH)) { + mkdir(BANNER_THUMB_PATH, 0770, true); + } + // Reset the umask. + umask($oldUmask); + + // BANNER IMAGE SIZES + // used in convert call to resize images + if ($type == 'side') { + + /** + * Resized size of side banner images + */ + define('BANNER_ITEM_RESIZED', "'160'"); + + /** + * Midsized size of side banner images + */ + define('BANNER_ITEM_MIDSIZED', "'80'"); + + /** + * Thumbnail size of side banner images + */ + define('BANNER_ITEM_THUMB', "'40'"); + } elseif ($type == 'bottom') { + + /** + * Resized size of bottom banner images + */ + define('BANNER_ITEM_RESIZED', "'550>'"); + + /** + * Midsized size of bottom banner images + */ + define('BANNER_ITEM_MIDSIZED', "'210'"); + + /** + * Thumbnail size of bottom banner images + */ + define('BANNER_ITEM_THUMB', "'120'"); + } + + // BANNER IMAGE URLS + $BASE_URL = ($_SERVER['HTTPS'] != 'on') ? BASE_URL : BASE_SECURE_URL; + + /** + * URL to the original banner image folder + */ + define('BANNER_ORIGINAL', "{$BASE_URL}images/banner_{$type}_original/"); + + + /** + * URL to the resized banner image folder + */ + define('BANNER_RESIZED', "{$BASE_URL}images/banner_{$type}_resized/"); + + + /** + * URL to the midsized banner image folder + */ + define('BANNER_MIDSIZED', "{$BASE_URL}images/banner_{$type}_midsized/"); + + + /** + * URL to the thumbnail banner image folder + */ + define('BANNER_THUMB', "{$BASE_URL}images/banner_{$type}_thumb/"); + } + + // }}} + // {{{ show() + + /** + * Manage what should be displayed + * + * @return void + * + * @author Jamie Kahgee + * @access Public + */ + public function show() + { + switch ($_GET['action']) { + case 'editSideBanner' : + case 'editBottomBanner' : + case 'editBanner' : + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + + global $banner; + $banner = new Toolkit_Banners_EditBanner('GLM_Banner'); + $banner->show(); + break; + + case 'listBanners' : + default : + echo ''; + echo ''; + + $list =& new Toolkit_Banners_ListBanners($this->dbh, 10); + //$list->process(); + //echo $list->render(); + $list->show(); + break; + } + } + + // }}} +} +?> diff --git a/Toolkit/Banners/Display.php b/Toolkit/Banners/Display.php new file mode 100644 index 0000000..7cf2e63 --- /dev/null +++ b/Toolkit/Banners/Display.php @@ -0,0 +1,498 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Display.php,v 1.2 2009/12/15 20:18:15 jamie Exp $ + * @link <> + */ + +/** + * Banner Ad Application + * + * Controls the front end displaying of banners to the webpage. + * + * @category Banners + * @package Toolkit_Banners + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +class Toolkit_Banners_Display +{ + // {{{ properties + + /** + * The Type of banner we are working with + * [side, bottom] + * @var string + * @access protected + */ + protected $bannerType = null; + + /** + * Array containing available banners for a page / catid + * @var array + * @access protected + */ + protected $availableBanners = array(); + + /** + * Database Banner Id + * @var unknown + * @access protected + */ + protected $bid; + + /** + * Table that holds the banner data + * @var string + * @access protected + */ + protected $tableName = 'banners'; + + /** + * Array of scripts needed for the banners + * @var array + * @access public + */ + public $scripts = array(); + + /** + * The banner(s) we are going to display on the page + * @var string + * @access public + */ + public $bannerDisplay; + + // }}} + + // {{{ __construct() + + /** + * Class constructor + * + * @param string $type Type of banner we are working with + * + * @author Jamie Kahgee + * @access Public + */ + public function __construct($type = null) + { + if (!is_null($type) && is_string($type)) { + $this->bannerType = strtolower($type); + Toolkit_Banners::setupDefines($this->bannerType); + } + + $this->dbh = Toolkit_Database::getInstance(); + if (!empty($_GET['banner'])) { + $this->bid = $_GET['banner']; + $this->adjustClicks(); + $url = $this->getLocation(); + header("Location: $url"); + } + } + + // }}} + // {{{ addScriptsToPage() + + /** + * Adds scripts needed for the banners to the page + * + * Puts any scripts that the banners need to run into the page object + * scripts array. That way it won't add the same script more than once + * and puts all scripts together in the head. + * + * @param array &$existing Flexy template page object script array + * + * @return void + * @access public + */ + public function addScriptsToPage(&$existing) + { + foreach ($this->scripts as $i) { + if (!in_array($i, $existing)) { + $existing[] = $i; + } + } + } + + // }}} + + // {{{ adjustClicks() + + /** + * Updates a banners click count when it is clicked on + * + * @author Jamie Kahgee + * @return void + * @access protected + */ + protected function adjustClicks() + { + try { + $sql = " + UPDATE {$this->tableName} + SET clicks = clicks + 1 + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $this->bid, PDO::PARAM_INT); + $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ adjustImpressions() + + /** + * Updates a banners impression count when it is displayed on a page + * + * @param int $bid Banner id to update impression for + * + * @author Jamie Kahgee + * @return void + * @access protected + */ + protected function adjustImpressions($bid) + { + try { + // If the banner is set in the url, then we don't need to adjust + // the impressions since its already been accounted for. + if (empty($_GET['banner'])) { + $sql = " + UPDATE {$this->tableName} + SET impressions = impressions + 1 + WHERE id = $bid"; + $this->dbh->query($sql); + } + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ setSingleOutput() + + /** + * Gets a random banner from available banner pool + * + * Randomly selects a banner to be displayed and updates the impression + * counter for that banner + * + * @author Jamie Kahgee + * @return mixed img link to a banner + * @access public + */ + public function setSingleOutput() + { + if (empty($this->availableBanners)) { + return false; + } + + $this->scripts = array(); + + $size = count($this->availableBanners); + $random = rand(1, $size - 1); + $banner = $this->availableBanners[$random]; + $this->adjustImpressions($banner['id']); + + Toolkit_Banners::setupDefines($this->bannerType); + + $properties = getimagesize(BANNER_RESIZED_PATH . $banner['image']); + + $img = ''.$banner['image'].''; + + if ($banner['external'] == 't') { + $target = 'target="_blank"'; + } + + $this->bannerDisplay + = ''.$img.''; + } + + // }}} + // {{{ getLocation() + + /** + * Gets the url from the current banner + * + * @author Jamie Kahgee + * @return string URL + * @access protected + */ + protected function getLocation() + { + try { + $sql = " + SELECT url + FROM {$this->tableName} + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $this->bid, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + return $row['url']; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setRotatingOutput() + + /** + * Sets up banners that rotate with no transitioning effect + * + * @author Jamie Kahgee + * @return mixed false if no banners are available for the current page + * @access public + */ + public function setRotatingOutput() + { + if (empty($this->availableBanners)) { + return false; + } + + $this->scripts = array( + GLM_APP_BASE_URL . 'libjs/jquery.json-1.2.min.js', + GLM_APP_BASE_URL . 'libjs/jquery.timers-1.0.0.js', + BASE_URL . 'Toolkit/Banners/libjs/rotating-banners.js' + ); + + $size = count($this->availableBanners); + $random = rand(1, $size) - 1; + $banner = $this->availableBanners[$random]; + foreach ($this->availableBanners as $b) { + $this->adjustImpressions($b['id']); + } + + Toolkit_Banners::setupDefines($this->bannerType); + + $properties = getimagesize(BANNER_RESIZED_PATH . $banner['image']); + + $img = ''.$banner['image'].''; + + if ($banner['external'] == 't') { + $target = 'target="_blank"'; + } + + foreach ($this->availableBanners as $b) { + $jsonSet[] = array( + 'image' => $b['image'], + 'description' => $b['description'], + 'id' => $b['id'], + ); + } + $bannerList = ''; + + $this->bannerDisplay = $bannerList + . ''.$img.''; + } + + // }}} + // {{{ setFadingOutput() + + /** + * Sets up banners that rotate with a fading effect + * + * @author Jamie Kahgee + * @return mixed false if no banners are available for the current page + * @access public + */ + public function setFadingOutput() + { + if (empty($this->availableBanners)) { + return false; + } + + $this->scripts = array( + //GLM_APP_BASE_URL . 'libjs/jquery.js', + GLM_APP_BASE_URL . 'libjs/jquery.innerfade.js', + BASE_URL . 'Toolkit/Banners/libjs/fading-banners.js' + ); + + Toolkit_Banners::setupDefines($this->bannerType); + + foreach ($this->availableBanners as $b) { + $this->adjustImpressions($b['id']); + + $properties = getimagesize(BANNER_RESIZED_PATH . $b['image']); + + $img = ''.$b['image'].''; + + if ($b['external'] == 't') { + $target = 'target="_blank"'; + } + + $banners[] + = ''.$img.''; + } + + $this->bannerDisplay = implode("\n", $banners); + } + + // }}} + + // {{{ hasBannersAvailable() + + /** + * Whether we have available banners in the pool for the current page + * + * @author Jamie Kahgee + * @return boolean + * @access public + */ + public function hasBannersAvailable() + { + return !empty($this->availableBanners); + } + + // }}} + + // {{{ setAvailable() + + /** + * Sets an array of available banners that can be used on the current page + * + * @author Jamie Kahgee + * @return boolean false on error + * @access public + * @throws PDOException PDOException on DB error + * @throws Exception Exception on invalid banner type + */ + public function setAvailable() + { + if (!is_numeric($_GET['catid'])) { + $this->availableBanners = array(); + return; + } + try { + if (is_null($this->bannerType) || empty($this->bannerType)) { + // The banner type hasn't been set yet. + // you can either set it when instatiating the object + // through the constructor, Or through its own function + // setBannerType(). + throw new Exception ('Banner Type is not set!'); + } + + $bottom = ($this->bannerType == 'bottom'); + $catid = empty($_GET['catid']) ? HOME_ID : $_GET['catid']; + + if (Toolkit_Banners::HAS_MEMBER_DB) { + $sql = " + OR id IN ( + SELECT bid + FROM banners2membercategories + WHERE catid in ( + SELECT memb_type + FROM bus_cat_member + WHERE catid in ( + SELECT id + FROM bus_category + WHERE active = true + AND id = :catid + ) + ) + )"; + } + $sql = " + SELECT * + FROM banners + WHERE active = true + AND sdate <= CURRENT_DATE + AND edate > CURRENT_DATE + AND bottom = :bottom + AND (id IN ( + SELECT bid + FROM banners2navpages + WHERE catid = :catid) + $sql) + ORDER BY id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':bottom', $bottom, PDO::PARAM_BOOL); + $stmt->bindParam(':catid', $catid, PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $banners[] = $row; + } + + $this->availableBanners = $banners; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } catch (Exception $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setBannersToDisplay() + + /** + * If the method to set the banner doesn't exists set the display to nothing + * + * @param String $type Type of banner we are going to be displayed + * + * @author Jamie Kahgee + * @access public + * @return void + */ + public function setBannersToDisplay($type = 'Single') + { + $type = ucfirst($type); + $func = "set{$type}Output"; + if (method_exists($this, $func)) { + $this->$func(); + } else { + $this->bannerDisplay = null; + } + } + + // }}} + // {{{ setBannerType() + + /** + * Sets the type of banners we are going to work with + * + * @param String $type Type of banner we are going to work with + * 'bottom' and 'side' are currently available + * + * @author Jamie Kahgee + * @access public + * @return void + */ + public function setBannerType($type) + { + $this->bannerType = strtolower($type); + } + + // }}} +} +?> diff --git a/Toolkit/Banners/EditBanner.php b/Toolkit/Banners/EditBanner.php new file mode 100644 index 0000000..7537d60 --- /dev/null +++ b/Toolkit/Banners/EditBanner.php @@ -0,0 +1,910 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditBanner.php,v 1.2 2009/12/15 20:18:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Banner Ad Application + * + * Manages the creation and editing form for manipulating banners in the db. + * + * @category Banners + * @package Toolkit_Banners + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Banners_EditBanner extends Toolkit_FormBuilder +{ + // {{{ properties + + + /** + * Description for public + * @var array + * @access public + */ + public $tableMetaData; + + /** + * Description for public + * @var string + * @access public + */ + public $tableName = 'banners'; + + /** + * Description for public + * @var unknown + * @access public + */ + public $type; + + /** + * Description for public + * @var object + * @access public + */ + public $dbh; + + /** + * 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. +
'; + + /** + * The default rules to register for validating + * + * We have to register these rules, or any others we want, before + * we are able to use them in our forms. + * + * @var string + * @access protected + */ + protected $registeredRules = array('date', 'banner'); + + // }}} + + // {{{ __construct() + + /** + * Constructor + * + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target 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 + * @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 + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->template = BASE . 'Toolkit/Banners/templates/currentTables/'; + + $this->dbh = Toolkit_Database::getInstance(); + $this->type = $_GET['type']; + + $this->configureElements(); + $this->configureRules(); + $this->configureFilters(); + $this->configureDefaults(); + } + + // }}} + + // {{{ configureElements() + + /** + * Configure how the form elements should look + * + * @author Jamie Kahgee + * @return void + * @access protected + */ + protected function configureElements() + { + $e = array(); + + $pages = $this->getSitePages(); + if (Toolkit_Banners::HAS_MEMBER_DB) { + $categories = $this->getMemberCategories(); + } + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'bottom' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'instructions_rmv', + 'opts' => 'Hold down the Ctrl key to select of unselect more than one at a time. Hold down the Shift key to select a range.' + ); + $e[] = array( + 'type' => 'select2', + 'req' => false, + 'name' => 'pages', + 'display' => 'Pages', + 'opts' => $pages, + 'att' => array( + 'multiple' => 'multiple', + 'id' => 'categories', + 'size' => 10) + ); + if (Toolkit_Banners::HAS_MEMBER_DB) { + $e[] = array( + 'type' => 'select2', + 'req' => false, + 'name' => 'member_categories', + 'display' => 'Member Categories', + 'opts' => $categories, + 'att' => array( + 'multiple' => 'multiple', + 'id' => 'member_categories', + 'size' => 10) + ); + } + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'url', + 'display' => 'URL' + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'external', + 'display' => 'External Link', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'display' => 'Description', + 'opts' => array( + 'id' => 'description', + 'rows' => 5, + 'cols' => 50) + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'sdate', + 'display' => 'Start Date', + 'opts' => array('format' => 'm / d / Y', + 'minyear' => date('Y'), + 'maxYear' => date('Y') + 10, + 'addEmptyOption' => true, + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy')), + 'att' => array('id' => 'sdate') + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'edate', + 'display' => 'End Date', + 'opts' => array('format' => 'm / d / Y', + 'minyear' => date('Y'), + 'maxYear' => date('Y') + 10, + 'addEmptyOption' => true, + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy')), + 'att' => array('id' => 'edate') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'active', + 'display' => 'Active', + 'val' => array('off', 'on') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'clicks', + 'display' => 'Clicks' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'impressions', + 'display' => 'Impressions' + ); + // If we're editing a banner, show the current + // banner image in the form + if (isset($_GET['id']) || isset($_POST['uploaded_file_rmv'])) { + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'image_rmv', + 'display' => 'Current Banner' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'uploaded_file_rmv' + ); + } + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'file_rmv', + 'display' => 'Banner Image' + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit_rmv', + 'display' => 'Submit Banner', + 'opts' => array('id' => 'submit') + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureRules() + + /** + * Configure how the form elements should act + * + * @author Jamie Kahgee + * @return void + * @access protected + */ + protected function configureRules() + { + $r = array(); + + $mimeTypes = array( + 'image/jpe', + 'image/jpeg', + 'image/jpg', + 'image/jfif', + 'image/pjpeg', + 'image/pjp', + 'image/gif', + 'image/png', + ); + + $r[] = array( + 'element' => 'start', + 'message' => 'Error: Invalid Date!', + 'type' => 'date', + 'format' => '%m-%d-%Y', + 'validation' => $validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'end', + 'message' => 'Error: Invalid Date!', + 'type' => 'date', + 'format' => '%m-%d-%Y', + 'validation' => $validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'clicks', + 'message' => 'Error: Must be an integer!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'impressions', + 'message' => 'Error: Must be an integer!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $validationType, + 'reset' => false, + 'force' => false + ); + // If we're not editing a banner, (creating a new banner) + // then the banner image IS required + // Use this check to determine if we want to use the + // uploadedfile rule. This will make the field required if + // a banner has not already been uploaded. + if ($_POST && !empty($_FILES['file_rmv']['name'])) { + // Don't do anything! + } elseif (!isset($_GET['id']) && !isset($_POST['uploaded_file_rmv'])) { + $r[] = array( + 'element' => 'file_rmv', + 'message' => 'Error: Must contain a banner image!', + 'type' => 'uploadedfile', + 'format' => null, + 'validation' => $validationType, + 'reset' => false, + 'force' => false + ); + } + // If we're editing a banner and have uploaded a new banner image + // make sure the MIME is of the correct type + if (!isset($_GET['id']) && !empty($_FILES['file_rmv']['tmp_name'])) { + $r[] = array( + 'element' => 'file_rmv', + 'message' => 'Error: Incorrect File Type (.gif, .png, .jpg) only!', + 'type' => 'mimetype', + 'format' => $mimeTypes, + 'validation' => $validationType, + 'reset' => false, + 'force' => false + ); + } + $r[] = array( + 'element' => 'file_rmv', + 'message' => 'Error: Invalid Banner Image!', + 'type' => 'banner', + 'format' => 'banner', + 'validation' => $validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + // {{{ configureFilters() + + /** + * Configure how the form elements should act when being submitted + * + * @author Jamie Kahgee + * @return void + * @access protected + */ + protected function configureFilters() + { + $f = array(); + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'stripslashes' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureDefaults() + + /** + * Configure the initial default values for the form + * + * @author Jamie Kahgee + * @return void + * @access protected + */ + protected function configureDefaults() + { + $nextWeek = mktime(0, 0, 0, date('m'), date('d') + 7, date('Y')); + if (isset($_GET['id'])) { + try { + $sql = " + SELECT *, + date_part('month', sdate) AS smonth, + date_part('day', sdate) AS sday, + date_part('year', sdate) AS syear, + date_part('month', edate) AS emonth, + date_part('day', edate) AS eday, + date_part('year', edate) AS eyear, + CASE bottom + WHEN true then '1' + ELSE '0' + END as bottom + FROM banners + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $banner = $stmt->fetch(PDO::FETCH_ASSOC); + $img = ''; + $defaults = array( + 'url' => $banner['url'], + 'external' => $banner['external'], + 'bottom' => $banner['bottom'], + 'description' => $banner['description'], + 'sdate' => array( + 'm' => $banner['smonth'], + 'd' => $banner['sday'], + 'Y' => $banner['syear'] + ), + 'edate' => array( + 'm' => $banner['emonth'], + 'd' => $banner['eday'], + 'Y' => $banner['eyear'] + ), + 'active' => $banner['active'], + 'clicks' => $banner['clicks'], + 'impressions' => $banner['impressions'], + 'uploaded_file_rmv' => $banner['image'], + 'image_rmv' => $img, + ); + + // Make sure all the pages that were selected are + // pre selected. + $sql = " + SELECT * + FROM banners2navpages + WHERE bid = :bid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':bid', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $pages[] = $row['catid']; + } + $defaults['pages'] = $pages; + + // Make sure all the member categories that were selected are + // pre selected. + $sql = " + SELECT * + FROM banners2membercategories + WHERE bid = :bid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':bid', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $pages[] = $row['catid']; + } + $defaults['member_categories'] = $pages; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } else { + $bottom = (int) ($_GET['type'] == 'bottom'); + $defaults = array( + 'sdate' => array( + 'm' => date('m'), + 'd' => date('d'), + 'Y' => date('Y') + ), + 'edate' => array( + 'm' => date('m', $nextWeek), + 'd' => date('d', $nextWeek), + 'Y' => date('Y', $nextWeek) + ), + 'external' => false, + 'clicks' => 0, + 'impressions' => 0, + 'bottom' => $bottom, + ); + } + + $this->setupDefaults($defaults); + } + + // }}} + + // {{{ getMemberCategories() + + /** + * Get the array of member categories used for the select list + * + * @author Jamie Kahgee + * @return array $pages pages used to populate a select list element + * @access protected + */ + protected function getMemberCategories() + { + $categories = Toolkit_Common::getHierarchicalTreeStructure( + 'category', + 'category_id', + 'parent_id' + ); + // Get only the active categories from + // the nav structure for our select list. + $sql = " + SELECT category_id, name + FROM category + WHERE category_id = :id"; + + $stmt = $this->dbh->prepare($sql); + + foreach ($categories as $k => $v) { + unset($row, $category); + $stmt->bindParam(':id', $k, PDO::PARAM_INT); + $stmt->execute(); + + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + // If we actually retrieved a row, add it to the select list + // after we clean it up. + if (!empty($row)) { + for ($i = 1; $i < $v; ++$i) { + $category .= '     '; + } + $pages[$k] = $category . $row['name']; + } + } + + return $pages; + } + + // }}} + // {{{ getSitePages() + + /** + * Get the array of navigational pages used for the select list + * + * @author Jamie Kahgee + * @return array $pages pages used to populate a select list element + * @access protected + */ + protected function getSitePages() + { + $categories = Toolkit_Common::getHierarchicalTreeStructure(); + // Get only the active categories from + // the nav structure for our select list. + $sql = " + SELECT id, category + FROM bus_category + WHERE id = :id + AND active = true"; + + $stmt = $this->dbh->prepare($sql); + + foreach ($categories as $k => $v) { + unset($row, $category); + $stmt->bindParam(':id', $k, PDO::PARAM_INT); + $stmt->execute(); + + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + // If we actually retrieved a row, add it to the select list + // after we clean it up. + if (!empty($row)) { + for ($i = 1; $i < $v; ++$i) { + $category .= '     '; + } + $pages[$k] = $category . $row['category']; + } + } + + return $pages; + } + + // }}} + + // {{{ insertData() + + /** + * Inserts banner data in the DB from the submitted form values + * + * @param array $values Form submission values + * + * @return boolean Result of insert queries for banner + * @access protected + */ + protected function insertData($values) + { + $values['url'] = $this->parseUrl($values['url'], $values['external']); + $navPages = $values['pages']; + $memberCategories = $values['member_categories']; + $values['image'] = $values['uploaded_file_rmv']; + unset($values['pages'], $values['member_categories'], + $values['uploaded_file_rmv']); + $values['sdate'] = implode('/', $values['sdate']); + $values['edate'] = implode('/', $values['edate']); + $values['active'] = ($values['active'] == 'on') ? true : false; + + try { + $this->dbh->beginTransaction(); + $params = implode(', ', array_keys($values)); + $bindParams = ':' . implode(', :', array_keys($values)); + + $sql = " + INSERT INTO {$this->tableName} ($params) + VALUES ($bindParams)"; + + $stmt = $this->dbh->prepare($sql); + foreach ($values as $k => &$v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + // for empty values that are not actually a zero (0), we + // want to insert null's. + // This will help hold the unique values for member_logins, + // as empty values '', are not considered unique + if (empty($v) && (int)$v !== 0) { + $v = null; + $dataType = PDO::PARAM_NULL; + } + $stmt->bindParam(":$k", $v, $dataType); + } + $stmt->execute(); + $bid = $this->dbh->lastInsertId('banners_id_seq'); + + if (!empty($navPages)) { + $sql = " + INSERT INTO banners2navpages (bid, catid) + VALUES ($bid, :catid)"; + + $stmt = $this->dbh->prepare($sql); + foreach ($navPages as $v) { + $stmt->bindParam(':catid', $v, PDO::PARAM_INT); + $stmt->execute(); + } + } + if (!empty($memberCategories)) { + $sql = " + INSERT INTO banners2membercategories (bid, catid) + VALUES ($bid, :catid)"; + + $stmt = $this->dbh->prepare($sql); + foreach ($memberCategories as $v) { + $stmt->bindParam(':catid', $v, PDO::PARAM_INT); + $stmt->execute(); + } + } + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ parseUrl() + + /** + * Parse the submitted url so we can put a fully formated url into the db + * + * @param string $url URI to validate + * @param boolean $external If we are dealing with an external URI + * compared to this site + * + * @return string The fully formatted uri + * @author Jamie Kahgee + * @access Protected + */ + protected function parseUrl($url, $external) + { + if ($external) { + $pattern = '/^http:\/\/.+$/'; + preg_match($pattern, $url, $matches); + if (empty($matches)) { + $url = "http://$url"; + } + } else { + $tok = strtok(BASE_URL, '/'); + while ($tok !== false) { + $url = preg_replace("/$tok/", '', $url, 1); + $tok = strtok('/'); + } + $url = BASE_URL . ltrim($url, '/'); + } + + return $url; + } + + // }}} + // {{{ processData() + + /** + * Determine how the form should be handled (insert new data or update old) + * + * @param array $values Submitted form values + * + * @author Jamie Kahgee + * @return boolean Result of insert or update function + * @access protected + */ + protected function processData($values) + { + Toolkit_Common::getTableMetaData(); + + unset($values['MAX_FILE_SIZE']); + foreach ($values as $k => $v) { + if ($k != 'uploaded_file_rmv' && preg_match('/^.+_rmv$/', $k)) { + unset($values[$k]); + } + } + + $function = isset($_GET['id']) ? 'updateData' : 'insertData'; + return $this->$function($values); + } + + // }}} + + // {{{ toHTML() + + /** + * Call the rendering function to get the form in a string + * + * @author Jamie Kahgee + * @return string $output The Form to be rendered or success msg. + * @access protected + */ + public function toHTML() + { + $this->setupRenderers(); + if ($this->validate()) { + $this->cleanForm(); + + if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) { + $this->freeze(); + $output = $this->successMsg; + } + } else if ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHTML(); + } else { + $output = parent::toHTML(); + } + return $output; + } + + // }}} + + // {{{ updateData() + + /** + * Updates banner data in the DB from the submitted form values + * + * @param array $values Submitted form values + * + * @return object Result of update queries on DB + * @access protected + */ + protected function updateData($values) + { + $values['url'] = $this->parseUrl($values['url'], $values['external']); + $navPages = $values['pages']; + $memberCategories = $values['member_categories']; + $values['image'] = $values['uploaded_file_rmv']; + unset($values['pages'], $values['member_categories'], + $values['uploaded_file_rmv']); + $values['sdate'] = implode('/', $values['sdate']); + $values['edate'] = implode('/', $values['edate']); + $values['active'] = ($values['active'] == 'on'); + + try { + $this->dbh->beginTransaction(); + $params = array_keys($values); + $length = count($params); + for ($i = 0; $i < $length; ++$i) { + $bindParams .= "{$params[$i]} = :{$params[$i]}"; + if ($i < ($length - 1)) { + $bindParams .= ', '; + } + } + $sql = " + UPDATE {$this->tableName} + SET $bindParams + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + foreach ($values as $k => &$v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + // for empty values that are not actually a zero (0), we + // want to insert null's. + // This will help hold the unique values for member_logins, + // as empty values '', are not considered unique + if (empty($v) && (int)$v !== 0) { + $v = null; + $dataType = PDO::PARAM_NULL; + } + $stmt->bindParam(":$k", $v, $dataType); + } + $stmt->execute(); + + if (!empty($navPages)) { + $sql = " + DELETE FROM banners2navpages + WHERE bid = :bid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':bid', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + $sql = " + INSERT INTO banners2navpages (bid, catid) + VALUES (:id, :catid)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + foreach ($navPages as $v) { + $stmt->bindParam(':catid', $v, PDO::PARAM_INT); + $stmt->execute(); + } + } + if (!empty($memberCategories)) { + $sql = " + DELETE FROM banners2membercategories + WHERE bid = :bid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':bid', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + $sql = " + INSERT INTO banners2membercategories (bid, catid) + VALUES (:id, :catid)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + foreach ($memberCategories as $v) { + $stmt->bindParam(':catid', $v, PDO::PARAM_INT); + $stmt->execute(); + } + } + + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + } + + // }}} +} +?> diff --git a/Toolkit/Banners/ListBanners.php b/Toolkit/Banners/ListBanners.php new file mode 100644 index 0000000..9e2ee7b --- /dev/null +++ b/Toolkit/Banners/ListBanners.php @@ -0,0 +1,310 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ListBanners.php,v 1.1.1.1 2009/09/17 20:08:57 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * List the banners in the database in a datagrid + * + * Handles listing of the banners in the bannerDB, pagnation, and sorting. + * Also controls the resulting number of banners that are rendered + * on the page. + * + * @category Banners + * @package Toolkit_Banners + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_DataGridBuilder + */ +class Toolkit_Banners_ListBanners extends Toolkit_DataGridBuilder +{ + // {{{ properties + + /** + * Description for protected + * @var array + * @access protected + */ + protected $contactColumns = array(); + + /** + * Description for protected + * @var unknown + * @access protected + */ + protected $dataGrid; + + /** + * Description for protected + * @var string + * @access protected + */ + protected $folder; + + /** + * Description for protected + * @var string + * @access protected + */ + protected $noRecMessage = 'No Banners Created Yet.'; + + // }}} + + // {{{ __construct() + + /** + * Constructor + * + * Builds the DataGrid class + * + * @param PDO $pdo PHP Data Object to use for the DB + * @param integer $limit The number of records to display per page + * @param integer $page The current page viewed + * @param object $rendererType The type of renderer to use + * + * @return void + * @access public + */ + public function __construct( + PDO $pdo, + $limit = null, + $page = null, + $rendererType = null + ) { + parent::__construct($pdo, $limit, $page, $rendererType); + + // Where are the banner folders located at? + $this->folder = BASE_URL . 'images/'; + + if (isset($_GET['status'])) { + $sql = " + UPDATE banners + SET active = + CASE + WHEN active = 't' then false + ELSE true + END + WHERE id = :id"; + + $stmt = $pdo->prepare($sql); + $stmt->bindParam(':id', $_GET['status'], PDO::PARAM_INT); + $stmt->execute(); + // pdo & stmt are unset to release the postgres connection. + // status is unset to if the user clicks to rearrange the + // grid after changing the status of a banner, its not + // carried into the rearrange url. + unset($stmt, $_GET['status']); + } elseif (isset($_GET['del'])) { + $sql = " + DELETE from banners + WHERE id = :id"; + + $stmt = $pdo->prepare($sql); + $stmt->bindParam(':id', $_GET['del'], PDO::PARAM_INT); + $stmt->execute(); + // pdo & stmt are unset to release the postgres connection. + // status is unset to if the user clicks to rearrange the + // grid after changing the status of a banner, its not + // carried into the rearrange url. + unset($stmt, $_GET['del']); + } + + $sql = " + SELECT id, url, image, impressions, clicks, active, image, bottom, + sdate AS ssdate, + edate AS sedate, + to_char(sdate, 'MM/DD/YYYY') AS sdate, + to_char(edate, 'MM/DD/YYYY') AS edate, + CASE + WHEN impressions = 0 THEN 0 || '%' + ELSE ROUND(clicks / impressions * 100, 2) || '%' + END AS conversion + FROM banners + $where"; + + $this->setQuery($sql); + $defaultSort = array('id' => 'ASC'); + $this->setDefaultSort($defaultSort); + } + + // }}} + + // {{{ configureColumns() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function configureColumns() + { + $edit =& new Structures_DataGrid_Column('Edit', + null, + null, + array('class' => 'editLink'), + null, + array(&$this, 'renderEditLink')); + $this->addColumn($edit); + + $del =& new Structures_DataGrid_Column('Delete', + null, + null, + array('class' => 'delLink'), + null, + array(&$this, 'renderDeleteLink')); + $this->addColumn($del); + + $active =& new Structures_DataGrid_Column('Active', + null, + null, + array('class' => 'delLink'), + null, + array(&$this, 'renderStatusLink')); + $this->addColumn($active); + + $url =& new Structures_DataGrid_Column('URL', 'url', 'url'); + $this->addColumn($url); + + $sdate =& new Structures_DataGrid_Column('Start Date', + 'sdate', + 'sdate', + array('class' => 'dateLink')); + $this->addColumn($sdate); + + $edate =& new Structures_DataGrid_Column('End Date', + 'edate', + 'edate', + array('class' => 'dateLink')); + $this->addColumn($edate); + + $fname =& new Structures_DataGrid_Column('Impressions', + 'impressions', + 'impressions', + array('class' => 'dateLink')); + $this->addColumn($fname); + + $lname =& new Structures_DataGrid_Column('Clicks', + 'clicks', + 'clicks', + array('class' => 'dateLink')); + $this->addColumn($lname); + + $conversion =& new Structures_DataGrid_Column('CTR', + 'conversion', + 'conversion', + array('class' => 'dateLink')); + $this->addColumn($conversion); + + $image =& new Structures_DataGrid_Column('Banner', + null, + null, + array('class' => 'dateLink'), + null, + array(&$this, 'renderBannerImage')); + $this->addColumn($image); + } + + // }}} + + // {{{ renderBannerImage() + + /** + * Render the banner thumbnail image + * + * @param array $data DB record + * + * @return mixed thumbnail image of the banner + * @access public + */ + public function renderBannerImage($data) + { + $location = ($data['record']['bottom'] == 't') ? 'bottom' : 'side'; + + $src = $this->folder . "banner_{$location}_thumb/{$data['record']['image']}"; + + return ''.
+                    $data['record']['image'].''; + } + + // }}} + // {{{ renderDeleteLink() + + /** + * Render the delete link for a banner + * + * @param array $data DB record + * + * @return mixed Link to delete a banner + * @access public + */ + public function renderDeleteLink($data) + { + return 'Delete'; + } + + // }}} + // {{{ renderEditLink() + + /** + * Render the edit link for a banner + * + * @param array $data DB record + * + * @return mixed Link to edit a banner + * @access public + */ + public function renderEditLink($data) + { + $type = ($data['record']['bottom'] == 't') ? 'bottom' : 'side'; + return 'Edit'; + } + + // }}} + // {{{ renderStatusLink() + + /** + * Render the status link for a banner + * + * @param array $data DB record + * + * @return string clickable link to switch the status of a banner + * @access public + */ + public function renderStatusLink($data) + { + $ball = ($data['record']['active'] == 't') ? 'grnball' : 'redball'; + $alt = ($data['record']['active'] == 't') ? 'On' : 'Off'; + $src = BASE_URL . "images/{$ball}.gif"; + + $img = '' . $alt . ''; + $link = '' . $img . ''; + + return $link; + } + + // }}} +} +?> diff --git a/Toolkit/Banners/banners.sql b/Toolkit/Banners/banners.sql new file mode 100644 index 0000000..1495c5d --- /dev/null +++ b/Toolkit/Banners/banners.sql @@ -0,0 +1,43 @@ +drop table banner cascade; +drop table banner_buscat cascade; +drop table banner_category cascade; +drop table banner_city cascade; +drop table banners cascade; +drop table banners2categories; +drop table banners2navpages; +drop table banners2membercategories; + +create table banners ( +id serial primary key, +active boolean default false, +bottom boolean default true, +clicks numeric default 0, +description text, +edate date not null, +external bool default false, +image text not null, +impressions integer default 0, +sdate date not null, +url text not null +); + +grant all on banners_id_seq to nobody; +grant all on banners to nobody; + +create table banners2navpages ( +id serial primary key, +bid integer references banners (id) on delete cascade, +catid integer references bus_category (id) on delete cascade +); + +grant all on banners2navpages_id_seq to nobody; +grant all on banners2navpages to nobody; + +create table banners2membercategories ( +id serial primary key, +bid integer references banners (id) on delete cascade, +catid integer references category (category_id) on delete cascade +); + +grant all on banners2membercategories_id_seq to nobody; +grant all on banners2membercategories to nobody; diff --git a/Toolkit/Banners/libjs/edit-banner.js b/Toolkit/Banners/libjs/edit-banner.js new file mode 100644 index 0000000..3626cdd --- /dev/null +++ b/Toolkit/Banners/libjs/edit-banner.js @@ -0,0 +1,126 @@ +var Banner = +{ + baseUrl: null, + pages: null, + pagesId: 'categories', + memberCats: null, + memberCatsId: 'member_categories', + + init: function() + { + Banner.baseUrl = location.protocol + '//' + location.hostname + '/'; + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + Banner.baseUrl += urlParts[1] + '/'; + } else if (location.hostname == 'kanga.acrewoods.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + Banner.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } + + Banner.pages = $('#' + Banner.pagesId); + Banner.pages.parents('tr').before('Select All Pages'); + + Banner.memberCats= $('#' + Banner.memberCatsId); + Banner.memberCats.parents('tr').before('Select All Member Categories'); + + Banner.setupPagesCheckbox(); + Banner.setupMemberCatsCheckbox(); + + $('#select_all_pages').bind('click', Banner.pagesSelection); + $('#select_all_member_cats').bind('click', Banner.memberCatsSelection); + + if ($('#sdate1').get(0)) { + Banner.setupSDateCalendar(); + var fromCal = new Zapatec.Calendar.setup({ + weekNumbers : false, + ifFormat : '%m/%d/%Y', + button : 'startcal', + onUpdate : Banner.updateFrom, + showsTime : false + }); + } + + if ($('#edate1').get(0)) { + Banner.setupEDateCalendar(); + var toCal = new Zapatec.Calendar.setup({ + weekNumbers : false, + ifFormat : '%m/%d/%Y', + button : 'endcal', + onUpdate : Banner.updateTo, + showsTime : false + }); + } + }, + + updateFrom: function(cal) + { + var date = cal.date; + $('#sdate1').get(0).selectedIndex = date.getMonth() + 1; + $('#sdate2').get(0).selectedIndex = date.getDate(); + $('#sdate3').get(0).selectedIndex = (date.getFullYear() - 2000); + }, + + updateTo: function(cal) + { + var date = cal.date; + $('#edate1').get(0).selectedIndex = date.getMonth() + 1; + $('#edate2').get(0).selectedIndex = date.getDate(); + $('#edate3').get(0).selectedIndex = (date.getFullYear() - 2000); + }, + + setupSDateCalendar: function() + { + var img = ' '; + $('#sdate3').after(img); + }, + + setupEDateCalendar: function() + { + var img = ' '; + $('#edate3').after(img); + }, + + setupPagesCheckbox: function() + { + var totalLength = Banner.pages.children().length; + var selectedLength = $('#' + Banner.pagesId + ' option:selected').length; + + var selected = true; + if (totalLength != selectedLength) { + selected = false; + } + $('#select_all_pages').attr('checked', selected); + }, + + setupMemberCatsCheckbox: function() + { + var totalLength = Banner.memberCats.children().length; + var selectedLength = $('#' + Banner.memberCatsId+ ' option:selected').length; + + var selected = true; + if (totalLength != selectedLength) { + selected = false; + } + $('#select_all_member_cats').attr('checked', selected); + }, + + pagesSelection: function(event) + { + var selected = $(this).attr('checked') ? true : false; + Banner.pages.children().attr('selected', selected); + }, + + memberCatsSelection: function(event) + { + var selected = $(this).attr('checked') ? true : false; + Banner.memberCats.children().attr('selected', selected); + } +}; + +$(document).ready(Banner.init); diff --git a/Toolkit/Banners/libjs/fading-banners.js b/Toolkit/Banners/libjs/fading-banners.js new file mode 100644 index 0000000..1a89e8c --- /dev/null +++ b/Toolkit/Banners/libjs/fading-banners.js @@ -0,0 +1,16 @@ +var FadingBanners = +{ + // Give time in seconds + rotationTime: 'slow', + container: '#banner', + + init: function() + { + $(FadingBanners.container).innerfade({ + speed: FadingBanners.rotationTime, + containerheight: '60px' + }); + } +}; + +$(document).ready(FadingBanners.init); diff --git a/Toolkit/Banners/libjs/list-banner.js b/Toolkit/Banners/libjs/list-banner.js new file mode 100644 index 0000000..667fc91 --- /dev/null +++ b/Toolkit/Banners/libjs/list-banner.js @@ -0,0 +1,16 @@ +var Banner = +{ + init: function() + { + $('.delete').click(Banner.confirmDelete); + }, + + confirmDelete: function(event) + { + if (!confirm('Are you sure you wish to delete this banner?\n\nThis action is not reversible!')) { + event.preventDefault(); + } + } +}; + +$(document).ready(Banner.init); diff --git a/Toolkit/Banners/libjs/rotating-banners.js b/Toolkit/Banners/libjs/rotating-banners.js new file mode 100644 index 0000000..0f87966 --- /dev/null +++ b/Toolkit/Banners/libjs/rotating-banners.js @@ -0,0 +1,51 @@ +var RotatingBanners = +{ + list: null, + currentBanner: null, + baseUrl: null, + // Give time in seconds + rotationTime: '10s', + folder: null, + + init: function() + { + RotatingBanners.baseUrl = location.protocol + '//' + location.hostname + '/'; + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + RotatingBanners.baseUrl += urlParts[1] + '/'; + } + + i = 0; + RotatingBanners.list = $('#bannerList').html(); + var obj = $.evalJSON(RotatingBanners.list); + var banners = $('.currentBanner'); + $(document).everyTime(RotatingBanners.rotationTime, function(t) { + banners.each(function() { + var startingBanner = $(this).attr('alt'); + var folderRegExp = new RegExp(RotatingBanners.baseUrl + '(.+)' + startingBanner, 'g'); + var src = $(this).attr('src'); + var folder = folderRegExp.exec(src); + RotatingBanners.folder = folder[1]; + RotatingBanners.currentBanner = $(this); + + if (!obj[++i]) { + i = 0; + } + RotatingBanners.update(obj[i]); + }); + }); + }, + + update: function(obj) + { + var image = RotatingBanners.baseUrl + RotatingBanners.folder + obj.image; + RotatingBanners.currentBanner.attr('src', image); + RotatingBanners.currentBanner.attr('alt', obj.image); + RotatingBanners.currentBanner.attr('title', obj.description); + var parentNode = RotatingBanners.currentBanner.parent(); + parentNode.attr('href', RotatingBanners.baseUrl + 'index.php?banner=' + obj.id); + } +}; + +$(document).ready(RotatingBanners.init); diff --git a/Toolkit/Banners/styles.css b/Toolkit/Banners/styles.css new file mode 100644 index 0000000..454beb3 --- /dev/null +++ b/Toolkit/Banners/styles.css @@ -0,0 +1,146 @@ +#form-warning-top { + color: #FF0000; + font-size: 14px; + font-weight: bold; + margin-bottom: 0.5em; + margin-top: 1em; +} +.required, .req { + color: #FF0000; +} +.group { + display: -moz-inline-box; + width: 100%; +} +.group td { + width: 324px; +} +.requiredNote { + text-align: center; +} +#contact { + margin: 10px; +} +#contact table { + background-color: #FFFFFF; + border: 1px solid #EEEEEE; + border-collapse: collapse; +} +#contact td { + border: 1px solid #EEEEEE; + border-collapse: collapse; + color: #000000; + font-family: arial, helvetica, sans-serif; + padding: 3px; +} +.labelcell { + background-color: transparent; + padding-right: 10px; + padding-top: 3px; + text-align: right; + white-space: nowrap; + width: 140px; +} +.fieldcell { + padding-left: 4px; + width: 325px; +} +#contact table.group { + font-size: 10px; + border: none; + padding-top: 4px; +} +#contact table.group td { + border: none; +} +#contact .hdr { + background-color: #999999; + border: 1px solid #666666; + font-weight: bold; +} +.paging { + text-align: center; + background-color: #F6F6F6; + border-color: #E86a10; + border-color: #296DC0; + border-style: solid; + border-width: 1px 0; + margin: 1.0em 0; + padding: 8px 0; + text-align: center; + width: 100%; + font-size: 12px; + +} +.paging b { + border: 1px solid #b22c2c; + border: 1px solid #E86A10; + background: #FFF; + padding: 5px 7px; + margin: 0 5px; +} +.paging a { + background: #FFF; + border: 1px solid #CCC; + padding: 5px 7px; + text-decoration: none; + font-family: helvetica, times; + color: #000; + margin: 0 5px; +} +.paging a:hover { + border: 1px solid #999; + border: 1px solid #b22c2c; + border: 1px solid #E86A10; +} +#dataGrid { + margin: 10px auto; + border: 1px solid #296DC0; + width: 100%; + border-collapse: collapse; +} +#dataGrid thead th { + background: #296DC0; + border: 1px solid #1b4880; + color: #000; + font-weight: normal; +} +#dataGrid th a { + font-weight: bolder; + color: #000; + text-decoration: none; +} +#dataGrid th a:hover { + color: #E86A10; + text-decoration: underline; +} +#dataGrid tr { + border: 1px solid #296DC0; + border-collapse: collapse; +} +#dataGrid tbody tr td { + padding: 5px; +} +#dataGrid .editLink, #dataGrid .delLink, +#dataGrid .mailLink, #dataGrid .dateLink, +#dataGrid .posLink { + text-align: center; +} +img.status { + border: none; +} +.even { + background-color: #D9D9D9; +} +#gridSorter { + margin: 0 auto; + padding: 10px; + text-align: center; + border: 1px solid #296DC0; +} +#gridSorter table { + border: none; +} +#gridSorter td { + border: none; +} diff --git a/Toolkit/Banners/templates/currentTables/Element.tpl b/Toolkit/Banners/templates/currentTables/Element.tpl new file mode 100644 index 0000000..8e6cc84 --- /dev/null +++ b/Toolkit/Banners/templates/currentTables/Element.tpl @@ -0,0 +1,14 @@ + + + + * + + + + + +
{error}
+ + {element} + + diff --git a/Toolkit/Banners/templates/currentTables/Form.tpl b/Toolkit/Banners/templates/currentTables/Form.tpl new file mode 100644 index 0000000..f59286a --- /dev/null +++ b/Toolkit/Banners/templates/currentTables/Form.tpl @@ -0,0 +1,7 @@ +
+ + + {content} +
+ +
diff --git a/Toolkit/Banners/templates/currentTables/Group.tpl b/Toolkit/Banners/templates/currentTables/Group.tpl new file mode 100644 index 0000000..cdd24cf --- /dev/null +++ b/Toolkit/Banners/templates/currentTables/Group.tpl @@ -0,0 +1,5 @@ + + + {content} + +
diff --git a/Toolkit/Banners/templates/currentTables/GroupElement.tpl b/Toolkit/Banners/templates/currentTables/GroupElement.tpl new file mode 100644 index 0000000..1a4ba27 --- /dev/null +++ b/Toolkit/Banners/templates/currentTables/GroupElement.tpl @@ -0,0 +1,9 @@ + + + {element} + + * + + {label} + + diff --git a/Toolkit/Banners/templates/currentTables/Header.tpl b/Toolkit/Banners/templates/currentTables/Header.tpl new file mode 100644 index 0000000..64ac244 --- /dev/null +++ b/Toolkit/Banners/templates/currentTables/Header.tpl @@ -0,0 +1,5 @@ + + + {header} + + diff --git a/Toolkit/Banners/templates/currentTables/RequiredNote.tpl b/Toolkit/Banners/templates/currentTables/RequiredNote.tpl new file mode 100644 index 0000000..525ef33 --- /dev/null +++ b/Toolkit/Banners/templates/currentTables/RequiredNote.tpl @@ -0,0 +1 @@ +* Denotes required field diff --git a/Toolkit/CKImages/Connector.php b/Toolkit/CKImages/Connector.php new file mode 100755 index 0000000..5df5155 --- /dev/null +++ b/Toolkit/CKImages/Connector.php @@ -0,0 +1,395 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Connector.php,v 1.2 2012/02/03 19:04:26 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + + +/** + * Connects the CKImage browser to the server for image manipulation + * + * @category CKImages + * @package Toolkit_CKImages + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version Release: @package_version@ + * @link http://demo.gaslightmedia.com + */ +class Toolkit_CKImages_Connector +{ + // {{{ setDbh() + + /** + * Sets the database handler for the object to use + * + * @param PDO $pdo PHP Data Object + * + * @return void + * @access public + */ + public function setDbh(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + + // {{{ createFolder() + + /** + * Creates a new folder + * + * @return void + * @access public + */ + public function createFolder() + { + // get the folder id + $folder = filter_var( + $_GET['name'], + FILTER_SANITIZE_STRING, + FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH + ); + if ($parent = filter_var($_GET['folder'], FILTER_VALIDATE_INT)) { + // do nothing, $parent set and validated + // from the $_GET['folder'] variable + } else { + $parent = 1; + } + + // if the parentFolder variable is set and valid, then override the + // existing parent folder value + if ($newParent = filter_var($_GET['parentFolder'], FILTER_VALIDATE_INT)) { + $parent = $newParent; + } + + // unset unneeded param values + unset($_GET['command'], $_GET['name'], $_GET['parentFolder']); + + try { + $sql = " + INSERT INTO ckeditor_folders(name, parent) + VALUES (:name, :parent)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':name', $folder, PDO::PARAM_INT); + $stmt->bindParam(':parent', $parent, PDO::PARAM_INT); + $stmt->execute(); + header('Location:' . BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ deleteFile() + + /** + * Deletes a file from the image server for client + * + * @param Toolkit_FileServer_ImageAdapter $ia Image Server Object + * + * @return void + * @access public + */ + public function deleteFile(Toolkit_FileServer_ImageAdapter $ia) + { + $getImg = filter_input(INPUT_GET, 'img'); + // Get offset where target img starts at + $start = strrpos($getImg, '/') + 1; + // get the image name + $img = substr($getImg, $start); + // unset unneeded param values + unset($_GET['command'], $_GET['img']); + + $ia->delete($img); + + try { + $sql = " + DELETE FROM ckeditor_images + WHERE name_on_disk = :nod"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':nod', $img, PDO::PARAM_STR); + $stmt->execute(); + header('Location:' . BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ deleteFolder() + + /** + * Deletes a folder and any sub folders + * + * Moves all containing images to home folder so they are not + * inadvertently deleted + * + * @return void + * @access public + */ + public function deleteFolder() + { + // get the folder id + $folder = $_GET['folder']; + if ($folder == 1) { + unset($_COOKIE['glm_image_browser_open'], $_COOKIE['glm_image_browser_selected']); + header('Location:' . BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + exit(); + } + // unset unneeded param values + unset($_GET['command'], $_GET['tgt']); + $_GET['folder'] = 1; + + try { + $tree = Toolkit_Common::getHierarchicalTreeStructure( + $this->dbh, + 'ckeditor_folders', + 'id', + 'parent', + 'id', + $folder, + 0, + false + ); + + $sql = " + UPDATE ckeditor_images + SET folder = 1 + WHERE folder = :folder"; + + $imgStmt = $this->dbh->prepare($sql); + + $sql = " + DELETE FROM ckeditor_folders + WHERE id = :folder"; + $fldrStmt = $this->dbh->prepare($sql); + while (list($tgt) = each($tree)) { + $imgStmt->bindParam(':folder', $tgt, PDO::PARAM_INT); + $imgStmt->execute(); + + $fldrStmt->bindParam(':folder', $tgt, PDO::PARAM_INT); + $fldrStmt->execute(); + } + // These cookies are defined in the libjs/image_selector.js file + // when the tree is created. + unset($_COOKIE['glm_image_browser_open'], $_COOKIE['glm_image_browser_selected']); + header('Location:' . BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ browseImages() + + /** + * Creates the browser window + * + * @param HTML_Template_Flexy $tEngine Flexy Rendering Engine Object + * + * @return string HTML page to browse images + * @access public + */ + public function browseImages(HTMl_Template_Flexy $tEngine) + { + $page = new stdClass(); + $page->baseUrl = BASE_URL; + $page->glmAppBaseUrl = GLM_APP_BASE_URL; + $page->originalPath = CKIMAGE; + $page->imageManager = IMAGE_MANAGER; + + if ($folderId = filter_input(INPUT_GET, 'folder', FILTER_VALIDATE_INT)) { + $folder = "&folder=$folderId"; + } else { + $folder = ''; + } + + $ckEditorFuncNum + = filter_input(INPUT_GET, 'CKEditorFuncNum', FILTER_VALIDATE_INT); + $ckEditor = filter_input(INPUT_GET, 'CKEditor'); + $langCode = filter_input(INPUT_GET, 'langCode'); + + $form = new HTML_QuickForm( + 'quick_upload', + 'post', + BASE_URL . "Toolkit/CKImages/controller.php?CKEditor=$ckEditor&CKEditorFuncNum=$ckEditorFuncNum&langCode=$langCode&command=UploadFile$folder" + ); + $form->addElement('file', 'upload'); + $page->quickUploadForm = $form->toHtml(); + + $folders = new Toolkit_CKImages_Folders($this->dbh); + $page->folders = $folders->getFolders(0); + + try { + $ckEditorFolderId = $folderId ? $folderId : 1; + $sql = " + SELECT * + FROM ckeditor_images + WHERE folder = :folder + ORDER BY id ASC"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':folder', $ckEditorFolderId, PDO::PARAM_INT); + $stmt->execute(); + + $images = $stmt->fetchAll(PDO::FETCH_ASSOC); + // loop thru images and reset their sizes + $isa = new Toolkit_FileServer_ImageAdapter(); + if (is_array($images) && !empty($images)) { + foreach ($images as &$img) { + // get real size for the CKImage Style +// var_dump(CKIMAGE . $img['name_on_disk']); + $imgData = $isa->getImageSize(CKIMAGE . $img['name_on_disk']); + $img['original_width'] = $imgData[0]; + $img['original_height'] = $imgData[1]; +// var_dump($imgData); + } + } +//var_dump($images); +//exit; + $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) + { + try { + if ($folder = filter_input(INPUT_GET, 'folder', FILTER_VALIDATE_INT)) { + // do nothing, $folder is already set and validated + } else { + $folder = 1; + } + $sql = " + INSERT INTO ckeditor_images (file_name, name_on_disk, folder, + original_width, original_height) + VALUES (:fname, :nod, :folder, :width, :height)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam( + ':fname', + $_FILES['upload']['name'], + PDO::PARAM_STR + ); + $stmt->bindParam(':nod', $imageName, PDO::PARAM_STR); + $stmt->bindValue(':folder', $folder, PDO::PARAM_INT); + $stmt->bindValue(':width', $dimensions['oWidth'], PDO::PARAM_INT); + $stmt->bindValue(':height', $dimensions['oHeight'], PDO::PARAM_INT); + + + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ quickUpload() + + + /** + * send uploaded image to image server + * + * @param Toolkit_FileServer_ImageAdapter $ia Image Server + * + * @return void + * @access public + */ + public function quickUpload(Toolkit_FileServer_ImageAdapter $ia) + { + try { + ob_start(); + $image = $ia->upload('upload'); + ob_end_clean(); + } catch (RangeException $e) { + Toolkit_Logger::logException('Runtime Error', $e); + throw new Toolkit_CKImages_Exception('Error uploading image'); + } + + $dimensions = $ia->getImageSize(CKIMAGE . $image['name']); + list($i['oWidth'], $i['oHeight'],) = $dimensions; + $this->handleUpload($image['name'], $i); + + unset($_GET['command']); + header('Location:' . BASE_URL . 'Toolkit/CKImages/browser.php?' . http_build_query($_GET)); + } + + // }}} + + // {{{ uploadFile() + + + /** + * send uploaded image to image server and select that file to be used + * + * @param Toolkit_FileServer_ImageAdapter $ia Image server object + * + * @return void + * @access public + */ + public function uploadFile(Toolkit_FileServer_ImageAdapter $ia) + { + if ($ckEditorFuncNum = filter_input(INPUT_GET, 'CKEditorFuncNum', FILTER_VALIDATE_INT)) { + // Do nothing, $ckEditorFuncNum set and validated + } else { + $ckEditorFuncNum = 1; + } + echo ''; + } + + // }}} +} +?> diff --git a/Toolkit/CKImages/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 100755 index 0000000..56bf0bd --- /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.1.1 2009/12/15 13:42:03 matrix 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 100755 index 0000000..3d48e8e --- /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.1.1.1 2009/12/15 13:42:03 matrix 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/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 100755 index 0000000..3152879 --- /dev/null +++ b/Toolkit/CKImages/browser.php @@ -0,0 +1,34 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: browser.php,v 1.2 2012/02/03 19:04:26 matrix Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * bootstrap + */ +require_once '../../setup.phtml'; + +Toolkit_CKImages_Factory::init(); +$connector = Toolkit_CKImages_Factory::instance('Connector'); +$connector->setDbh(Toolkit_Database::getInstance()); +$flexyOpts = $GLOBALS['flexyOptions']; +$flexyOpts['templateDir'] = BASE . 'Toolkit/CKImages/templates/'; +$flexyOpts['compileDir'] = BASE . 'Toolkit/CKImages/templates/compiled/'; +$tEngine = new HTML_Template_Flexy($flexyOpts); + +$connector->browseImages($tEngine); +?> diff --git a/Toolkit/CKImages/connector.php b/Toolkit/CKImages/connector.php new file mode 100755 index 0000000..a690a80 --- /dev/null +++ b/Toolkit/CKImages/connector.php @@ -0,0 +1,53 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: connector.php,v 1.1.1.1 2009/12/15 13:42:03 matrix Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * bootstrap + */ +require_once '../../setup.phtml'; + +Toolkit_CKImages_Factory::init(); +$connector = Toolkit_CKImages_Factory::instance('Connector'); +$connector->setDbh(Toolkit_Database::getInstance()); + +switch ($_GET['command']) { +case 'CreateFolder' : + $connector->createFolder(); + break; + +case 'DeleteFile' : + $connector->deleteFile(new Toolkit_Image_Server); + break; + +case 'DeleteFolder' : + $connector->deleteFolder(new Toolkit_Image_Server); + break; + +case 'Upload' : + $connector->uploadFile(new Toolkit_Image_Server); + break; + +case 'UploadFile' : + $connector->quickUpload(new Toolkit_Image_Server); + break; + +default : + die('not yet implemented'); + $connector->throwError(); + break; +} +?> diff --git a/Toolkit/CKImages/controller.php b/Toolkit/CKImages/controller.php new file mode 100644 index 0000000..db59059 --- /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.1 2012/02/03 19:04:26 matrix 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/database/Import.php b/Toolkit/CKImages/database/Import.php new file mode 100755 index 0000000..5c43cdd --- /dev/null +++ b/Toolkit/CKImages/database/Import.php @@ -0,0 +1,134 @@ +dbh = $pdo; + $this->pathToImages = BASE . 'images/ht_images/'; + $this->urlPathToImages = BASE_URL . 'images/ht_images/'; + $this->is = new Toolkit_Image_Server(); + } + // }}} + // {{{ addFolderToDatabase() + function addFolderToDatabase($folder, $parent) + { + static $stmt; + if (!$stmt) { + $sql = " + INSERT INTO ckeditor_folders + (name, parent) + VALUES + (:name, :parent) + RETURNING id"; + $stmt = $this->dbh->prepare($sql); + } + try { + $stmt->bindParam(":name", $folder, PDO::PARAM_STR); + $stmt->bindParam(":parent", $parent, PDO::PARAM_STR); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + // }}} + // {{{ addImageToDatabase() + function addImageToDatabase($file, $folder) + { + static $stmt; + if (!$stmt) { + $sql = " + INSERT INTO ckeditor_images + (file_name, name_on_disk, original_width, original_height, folder) + VALUES + (:file_name, :name_on_disk, :original_width, :original_height, :folder)"; + $stmt = $this->dbh->prepare($sql); + } + try { + $stmt->bindParam(":file_name", $file['file_name'], PDO::PARAM_STR); + $stmt->bindParam(":name_on_disk", $file['name_on_disk'], PDO::PARAM_STR); + $stmt->bindParam(":original_width", $file['original_width'], PDO::PARAM_STR); + $stmt->bindParam(":original_height", $file['original_height'], PDO::PARAM_STR); + $stmt->bindParam(":folder", $folder, PDO::PARAM_INT); + $stmt->execute(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + }// }}} + // {{{ processFilesArray + function processFilesArray($files, $parent = 1) + { + //echo '
    '.print_r($files, true).'
    '; + foreach ($files as $folderName => $file) { + if (is_array($file)) { + $fKey = key($file); + $folderToAdd = ereg_replace("/$", "", $fKey); + //echo '
    '.print_r($folderToAdd, true).'
    '; + $folder = $this->addFolderToDatabase($folderToAdd, $parent); + //echo '
    '.print_r($folder, true).'
    '; + //var_dump($files[$folderName][$fKey]); + // echo '
    '.print_r($file[$folderName][$fKey], true).'
    '; + $processedFile[] = $this->processFilesArray($files[$folderName][$fKey], $folder); + } else { + $processedFile[] = $this->sendToImageServer($file, $parent); + } + } + return $processedFile; + } + // }}} + // {{{ readImageDir() + function readImageDir($path = '') + { + $dirName = $this->pathToImages . ereg_replace("/$", "", $path); + //var_dump($dirName);echo '
    '; + $d = dir($dirName); + while (false !== ($entry = $d->read())) { + if (!ereg("^\.|^CVS", $entry)) { + $entryPath = $this->pathToImages . $path . $entry; + //var_dump($entryPath); echo '
    '; + if ($dirCheck = is_dir($entryPath)) { + $files[$path][] = $this->readImageDir($path . $entry . '/'); + } else if ($fileCheck = is_file($entryPath)) { + $files[$path][] = $path . $entry; + } + } + } + return $files; + } + // }}} + //{{{ runImport() + function runImport() + { + $files = $this->readImageDir(); + echo '
    '.print_r($files, true).'
    '; + $processedFiles = $this->processFilesArray($files['']); + //echo '
    '.print_r($processedFiles, true).'
    '; + } + //}}} + // {{{ sendToImageServer() + function sendToImageServer($file, $folder) + { + $file_name = basename($file); + $size = getImageSize($this->pathToImages . $file); + $name_on_disk = $this->is->imageUpload( + $this->urlPathToImages . '/' . ereg_replace(' ', '%20', $file) + ); + $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/ckeditorImages.sql b/Toolkit/CKImages/database/ckeditorImages.sql new file mode 100755 index 0000000..1f0ae0d --- /dev/null +++ b/Toolkit/CKImages/database/ckeditorImages.sql @@ -0,0 +1,27 @@ +drop table ckeditor_folders; + +create table ckeditor_folders( +id serial primary key, +name text not null, +parent integer default 1 not null +); + +grant all on ckeditor_folders_id_seq to nobody; +grant all on ckeditor_folders to nobody; + +insert into ckeditor_folders(id, name, parent) values(1, 'root', 0); + +drop table ckeditor_images; + +create table ckeditor_images( +id serial primary key, +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, +folder integer default 1 references ckeditor_folders (id) on delete set default +); + +grant all on ckeditor_images_id_seq to nobody; +grant all on ckeditor_images to nobody; \ No newline at end of file diff --git a/Toolkit/CKImages/database/importHtImages.php b/Toolkit/CKImages/database/importHtImages.php new file mode 100755 index 0000000..4e709ce --- /dev/null +++ b/Toolkit/CKImages/database/importHtImages.php @@ -0,0 +1,6 @@ +runImport(); +?> diff --git a/Toolkit/CKImages/imageFetch.php b/Toolkit/CKImages/imageFetch.php new file mode 100644 index 0000000..55951bc --- /dev/null +++ b/Toolkit/CKImages/imageFetch.php @@ -0,0 +1,44 @@ +prepare($sql); + $stmt->bindParam(':id', $_GET['file'], PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + +// $fileToFetch = empty($row['original_image']) +// ? $row['name_on_disk'] +// : $row['original_image']; + $fileToFetch = $row['name_on_disk']; +} catch (PDOException $e) { + Toolkit_Logger::logException('DB Error', $e); +} +set_time_limit(0); + +// file to save the info +$fp = fopen(dirname(__FILE__) . "/editedImages/$fileToFetch", 'w+'); + +// file we are downloading +$ch = curl_init(CKIMAGE_ORIGINAL . $fileToFetch); +curl_setopt($ch, CURLOPT_TIMEOUT, 50); +curl_setopt($ch, CURLOPT_FILE, $fp); +curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); +curl_exec($ch); +curl_close($ch); +fclose($fp); + +$path = urlencode(BASE . "Toolkit/CKImages/editedImages/$fileToFetch"); +$image_name = urlencode($row['file_name']); +header('Location: ' . BASE_URL . "Toolkit/PHPImageEditor/index.php?imagesrc=$path&image_name=$image_name"); +?> diff --git a/Toolkit/CKImages/libjs/image_selector.js b/Toolkit/CKImages/libjs/image_selector.js new file mode 100755 index 0000000..930bce2 --- /dev/null +++ b/Toolkit/CKImages/libjs/image_selector.js @@ -0,0 +1,142 @@ +var IMAGE_SELECTOR = +{ + parentFolder: null, + + init: function() + { + $('.tLeft').tipsy({gravity: 'sw'}); + $('.tCenter').tipsy({gravity: 's'}); + $('.tRight').tipsy({gravity: 'se'}); + $('.tDelete').tipsy({gravity: 'se'}); + + $('a.CKImageEdit').click(function(event) { + var $newWindow = window.open( + $(this).attr('href'), + '', + 'width=775,height=775', + true + ); + + $newWindow.focus(); + return false; + }); + + tree1 = new tree_component(); + tree1.init($("#folders"), { + cookies : { + prefix : "glm_image_browser", + opts : { path : '/' } + }, + ui : { + animation : 500 + } + }); + + // Make the tree default to all opened + $('#folders li.closed') + .toggleClass('open') + .toggleClass('closed'); + + $('#folders a').click(IMAGE_SELECTOR.viewFolder); + + // Stop clicks on the LI elements, so the folders branches + // will not close. + $('#folders li').click(function(event) { + event.stopImmediatePropagation(); + }); + + $('div.thumb span.CKImageUse').click(function() { + var img = $(this).parent().siblings('img'); + var funcNum = $('#CKEditorFuncNum').text(); + + window.opener.CKEDITOR.tools.callFunction(funcNum, img.attr('rel')); + window.close(); + }); + + $('div.thumb span.CKImageDelete').click(function(event) { + event.preventDefault(); + if (confirm('Are you sure you want to delete this image?')) { + var img = $(this).parent().siblings('img').attr('rel'); + var href = window.location.href.replace(/(.*)browser.php(.*)/, '$1controller.php$2&command=DeleteFile&img=' + img); + + window.location.href = href; + } + }); + + $('#imageDialog').dialog({ + bgiframe : true, + autoOpen : false, + resizable: false, + modal : true, + buttons : { + Cancel : function() { + $(this).dialog('close'); + }, + 'Upload Selected File' : function() { + if ($('#imageDialog form input[type=file]').val()) { + $('.ui-dialog-buttonpane button').attr('disabled', true); + $('#imageDialog form').trigger('submit'); + } else { + alert('You need to select a file first'); + } + } + } + }); + + $('#upload').click(function() { + $('#imageDialog').dialog('open'); + }); + + $('#newFolder').submit(IMAGE_SELECTOR.createFolder); + $('#folderDialog').dialog({ + bgiframe : true, + autoOpen : false, + resizable: false, + modal : true, + buttons: { + Cancel : function() { + $('#folderName').removeClass('ui-state-error'); + $(this).dialog('close'); + }, + 'Create' : IMAGE_SELECTOR.createFolder + } + }); + $('#folderNew').click(function() { + $('#folderDialog').dialog('open'); + }); + $('#folderDelete').click(function() { + if (confirm('Are you sure you want to delete this folder?')) { + var href = window.location.href.replace(/(.*)browser.php(.*)/, '$1controller.php$2&command=DeleteFolder'); + + window.location.href = href; + } + }); + }, + + createFolder: function(event) + { + event.preventDefault(); + // don't submit empty folder + var folderName = $('#folderName'); + var val = folderName.val(); + if (val == '') { + alert('You need to type a folder name first'); + return false; + } else { + $('.ui-dialog-buttonpane button').attr('disabled', true); + var href = window.location.href.replace(/(.*)browser.php(.*)/, '$1controller.php$2&command=CreateFolder&name=' + $('#folderName').val()); + if (IMAGE_SELECTOR.parentFolder != null) { + href += '&parentFolder=' + IMAGE_SELECTOR.parentFolder; + IMAGE_SELECTOR.parentFolder = null; + } + window.location.href = href; + } + }, + + viewFolder: function(event) + { + location.href = $(this).attr('href'); + } +}; + +$(document).ready(IMAGE_SELECTOR.init); diff --git a/Toolkit/CKImages/styles.css b/Toolkit/CKImages/styles.css new file mode 100755 index 0000000..50260c8 --- /dev/null +++ b/Toolkit/CKImages/styles.css @@ -0,0 +1,153 @@ +body { + font-family: arial, sans-serif; + font-size: 11px; + background: url(assets/night-fate-stock2.jpg) no-repeat fixed;/* #E3E3C7; */ + margin: 0; + padding: 0; +} +#wrapper { + width: 750px; + height: 1%; + overflow: hidden; + margin: 10px 0px 5px 10px; +} +h1 { + font-size: 24px; + margin: 0; + padding: 10px; + background: rgba(255, 255, 255, 0.8); + position: fixed; + } + +#toolbar { + background: #F1F1E3; + width: 140px; + border: 1px solid #D5D59D; + float: left; + padding: 8px; + margin-right: 20px; + margin-top: 60px; + position: fixed; + } +#toolbar > ul { + border-bottom: 1px solid #333; + padding: 0 0 6px 0; + margin: 0 0 6px 0; + } +#toolbar > ul, #toolbar > ul li { + list-style: none; + display: block; +} +#toolbar > ul li { + padding: 2px 2px 2px 26px; + line-height: 18px; + border: 1px solid #F1F1E3; + margin: 0; + background-position: 2px center; + background-repeat: no-repeat; + text-decoration: underline; + cursor: hand; + cursor: pointer; +} +#toolbar > ul li:hover { + border: 1px solid #D5D59D; + text-decoration: none; +} +#toolbar #upload { + background-image: url(http://app.gaslightmedia.com/assets/icons/add.png); +} +#toolbar #folderNew { + background-image: url(http://app.gaslightmedia.com/assets/icons/folder_add.png); +} +#toolbar #folderDelete { + background-image: url(http://app.gaslightmedia.com/assets/icons/folder_delete.png); +} +.tree ul { + margin: 0; + padding-top: 1px; +} +.tree li a { + background-image: url(http://app.gaslightmedia.com/assets/icons/folder.png); +} +.tree li.open { + background: none; + } +#pred_1 { + padding-left: 3px; + padding-top: 3px; +} +.tree li li.open { + background: transparent url(http://app.gaslightmedia.com/libjs/jsTree/source/images/li.gif) no-repeat scroll 7px 7px; +} +/* Main Section */ +#photo-gallery { + height: 1%; + overflow: hidden; + padding-top: 10px; + margin: 50px 0 0 180px; + } +.thumb { + width: 120px; + height: 160px; + float: left; + margin: 0 20px 20px 0; + background: #F1F1E3; + background: rgba(241, 241, 227, 0.5); + font-size: 10px; + border-radius:5px; + -moz-border-radius:5px; + -webkit-border-radius:5px; + border: 1px solid #D5D59D; + } +.rowTop { + height: 1%; + overflow: hidden; +} +.thumb img { + display: block; + margin: 0px 10px 2px 10px; + border: 1px dotted #ccc; + clear: left; +} + +.CKImageFunctions { + margin: 10px 5px; + } +.CKImageFunctions a, +.CKImageFunctions span { + display: block; + line-height: 16px; + margin: 0 5px 0 5px; + text-decoration: underline; + width: 16px; + height: 16px; + text-indent: -9000px; + float: left; + } + +/* cursor */ +.CKImageUse, .CKImageEdit, .CKImageDelete { + cursor: hand; + cursor: pointer; + } + +.CKImageUse {background: url(http://app.gaslightmedia.com/assets/icons/accept.png) no-repeat; } +.CKImageEdit {background: url(http://app.gaslightmedia.com/assets/icons/image_edit.png) no-repeat; } +.CKImageView {background: url(http://app.gaslightmedia.com/assets/icons/image.png) no-repeat;} +.CKImageDelete {background: url(http://app.gaslightmedia.com/assets/icons/image_delete.png) no-repeat;} + +.CKImageName { + display: none; +} + + +.CKImageProperties { + margin: 3px auto; + text-align: center; +} +.CKImageDate { + display: none; +} +#menuFolder, #menuImage, #column { + display: none; +} \ No newline at end of file diff --git a/Toolkit/CKImages/templates/thumbnails.html b/Toolkit/CKImages/templates/thumbnails.html new file mode 100755 index 0000000..3c35b36 --- /dev/null +++ b/Toolkit/CKImages/templates/thumbnails.html @@ -0,0 +1,70 @@ + + + +Thumbnail Images + + + + + + + + +

    GLM Image Browser

    +
    +
    +
      +
    • Upload New Image
    • +
    +
      +
    • Create New Folder
    • +
    • Delete This Folder
    • +
    +
    + Folders + {folders:h} +
    +
    + +
    + + + + + + + + + + + + + + + + + + + + diff --git a/Toolkit/Common.php b/Toolkit/Common.php new file mode 100644 index 0000000..19ff9bd --- /dev/null +++ b/Toolkit/Common.php @@ -0,0 +1,1041 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @release CVS: $Id: Common.php,v 1.3 2010/10/07 10:44:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Common collection of functions used throughout the GLM Toolkit + * + * @category Toolkit + * @package Toolkit_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 = 'errors@gaslightmedia.com'; + + /** + * 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); + } 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); + } 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); + } 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; + } + + // }}} + + // {{{ 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: '; + + 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() . ''; + } + $state .= '
    $_SERVER[\'QUERY_STRING\']: ' . $_SERVER['QUERY_STRING'] . "\n"; + $state .= '
    $_GET:
    ' . print_r($_GET, true) . '
    '; + $state .= '
    $_POST:
    ' . print_r($_POST, true) . '
    '; + /* + if (method_exists($obj, 'getBacktrace')) { + $backtrace = print_r($obj->getBacktrace(), true); + + $state .= "
    $backtrace
    "; + } + */ + + return $state; + } + + // }}} + + // {{{ 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; + } + + // }}} + + // {{{ 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 = 'bus_category', + $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); + } + } + + // }}} + // {{{ 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); + } + } + + // }}} + // {{{ 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(); + while ($row = $stmt->fetch()) { + $states[$row['state_id']] = $row['state_name']; + } + + return $states; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ handleError() + + /** + * Handles various script error + * + * @param Object $e Error Object + * @param boolean $developmentServer If we are on a development server + * + * @return false + * @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. + 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 + * + * @return void + * @access public + * @static + */ + public static function mailError(Mail $mail, $subject) + { + $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; + } + + 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() + + /** + * Performs the sql insert statement + * + * If using a Postgresql driver for the PDO, metadata is used when + * binding parameters to the prepared statement. + * + * @param object $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(); + } + + // }}} + + // {{{ recursiveArraySearch() + + /** + * Recursive multi-dimensional array search + * + * @param string $n Needle + * @param array $h Haystack + * + * @return mixed search result - false if not found + * @access public + * @static + */ + public static function recursiveArraySearch($n, array $h) + { + foreach ($h as $i => $j) { + $curr = $i; + if ($n === $j + || (is_array($j) && self::recursiveArraySearch($n, $j) !== false) + ) { + return $curr; + } + } + + return false; + } + + // }}} + + // {{{ show() + + /** + * Renders the calling class to the screen + * + * @access public + * @return string calls the toHTML function of calling class + */ + public function show() + { + echo $this->toHTML(); + } + + // }}} +} +?> diff --git a/Toolkit/Contacts/ContactUs.php b/Toolkit/Contacts/ContactUs.php new file mode 100755 index 0000000..4270746 --- /dev/null +++ b/Toolkit/Contacts/ContactUs.php @@ -0,0 +1,1141 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ContactUs.php,v 1.3 2009/12/28 19:40:04 cscott Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Error codes for Toolkit_Contacts_ContactUs + * + * Codes are mapped to textual messaged by errorMessage() method, + * if you add a new code be sure to add a new message for it to errorMessage() + * + * @see Toolkit_Contacts_ContactUs::errorMessage() + */ +define('FORM_OK', 1); +define('FORM_ERROR', -1); +define('NO_RECORD', -2); +define('INVALID_DB', -3); +define('MISSING_CONSTANT', -4); +define('MISSING_CONTACT_TYPE', -5); + +/** + * GLM Contact Us form + * + * This form handles rendering and processing the contact us form. + * Controls the email functionality of the form, whether the client + * has a contact DB to store contact records and how to insert/update + * submitted form values. + * + * @category Contacts + * @package Toolkit_Contacts + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_FormBuilder + */ +class Toolkit_Contacts_ContactUs + extends Toolkit_FormBuilder implements Toolkit_Form +{ + // {{{ properties + + /** + * Table in Database which holds the contact data + * + * @var string + * @access public + */ + public $tableName = 'contact'; + + /** + * Table meta data + * + * This is used when inserting/updating data for the records + * so the PDO's can use explicit data types for the parameters. + * + * @var array + * @access public + */ + public $tableMetaData = array(); + + /** + * Contact type to be inserted into the DB as when the form is submitted + * + * This property is only valid when the [hasContactDB] property is set + * to true. + * + * N.B. + * If you subclass this class out to other forms that are + * inserted into the contact db, be sure to make each one of their + * contactType properties unique. We don't check for duplicates. + * + * @var string + * @access protected + */ + protected $contactType = '1'; + + /** + * Who to send the email to when the contact form is submitted + * + * If you leave this blank, its value will get set to the OWNER_EMAIL + * in the constructor. + * + * If you ***DO NOT*** want any emails to go out when the form is submitted + * then set the value to false. Do not set it to 0 for false, because the + * check uses a strict type check to determine if the value is actually + * false. This is what allows for the empty value as an option, which sets + * the value to OWNER_EMAIL and won't override the $email property if + * this class gets subclassed and the value for this property gets set in + * the properties of the subclass and not in the constructor after this + * constructor function is called. + * + * tongue twister...I know. + * + * protected $email = false; + * + * + * @var string + * @access protected + */ + protected $email; + + /** + * From header in the owner email + * + * This just sets the From header in the owner email + * SITENAME + * + * It gets set to the constant SITENAME in the constructor if you leave + * empty here, but you can set it to something different here to override + * that if you desire. + * + * @var string + * @access protected + */ + protected $siteName; + + /** + * Email subject and

    header in email + * + * It gets set in the constructor if you leave empty here, but you + * can set it to something different here to override that if you desire. + * + * @var string + * @access protected + */ + public $subject; + + /** + * Whether the site has a contact DB to store contact records + * + * If this value is set to false, an email will still be sent to the + * addressed specified in the email property. + * + * @var boolean + * @access protected + */ + protected $hasContactDB = false; + + /** + * The interests from the contact db + * + * @var array + * @access protected + */ + protected $inquiries = array(); + + /** + * Message to display if the form is successfully submitted + * + * @var string + * @access protected + */ + protected $successMsg = ' +
    + Thank you for your questions or comments! +
    '; + + /** + * Extra rules for processesing + * + * This registers the Zip validation rules (and any others listed) for + * QuickForm. + * + * Zip validation checks both US and Canadian Zip codes + * + * @var array + * @access protected + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rules/Zip.php + */ + protected $registeredRules = array( + 'zip', + 'phone', + array( + 'checkEmail', + 'callback', + 'email', + 'Validate' + ), + ); + + /** + * Options for flexy templating engine + * + * Pulls the preset options from the setup.phtml file + * overwrites the templateDir and compileDir to match this classes needs + * + * @var array + * @access protected + */ + protected $flexyOptions; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param object $pdo PHP Data Object + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for
    tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @author Jamie Kahgee + * @access public + * @link http://pear.php.net/package/HTML_QuickForm/docs/latest/HTML_QuickForm/HTML_QuickForm.html + * @see HTML_QuickForm + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + // Make sure these end cases are never met. + // These are more for the development phase. + if ($this->email === false && $this->hasContactDB === false) { + PEAR::raiseError( + null, + NO_RECORD, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + if (!is_bool($this->hasContactDB)) { + PEAR::raiseError( + null, + INVALID_DB, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + // we haven't defined the FROM_NEWS_EMAIL constant and + // the email will default to relying on it. + if ( !defined('FROM_NEWS_EMAIL') + && (empty($this->email) && $this->email !== false) + ) { + PEAR::raiseError( + 'You need to define the FROM_NEWS_EMAIL + constant for this form to work correctly', + MISSING_CONSTANT, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + if (!is_numeric($this->contactType) && $this->hasContactDB) { + PEAR::raiseError( + null, + MISSING_CONTACT_TYPE, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + + // Default Renderer Form templates for QuickForm in respect to this + // classes needs. + $this->template = dirname(__FILE__) . '/templates/currentTables/'; + if ($this->email !== false && empty($this->email)) { + // Set to false to turn off email function. + $this->email = OWNER_EMAIL; + } + if (empty($this->siteName)) { + $this->siteName = SITENAME; + } + if (empty($this->subject)) { + $this->subject = 'Contact Request from website ' . SITENAME; + } + + /** + * Where are the flexy templates stored at for this class. + */ + define('TEMPLATES_DIR', BASE . 'Toolkit/Contacts/templates'); + + /** + * Where are the compiled flexy templates stored at for this class. + */ + define('COMPILED_DIR', BASE . 'Toolkit/Contacts/templates/compiled'); + $oldUmask = umask(0); + if (!is_dir(TEMPLATES_DIR)) { + mkdir(TEMPLATES_DIR, 0770, true); + } + if (!is_dir(COMPILED_DIR)) { + mkdir(COMPILED_DIR, 0770, true); + } + umask($oldUmask); + + $this->flexyOptions = $GLOBALS['flexyOptions']; + $this->flexyOptions['templateDir'] = TEMPLATES_DIR; + $this->flexyOptions['compileDir'] = COMPILED_DIR; + + $var = basename(__FILE__, '.php'); + + $callbackUrl = ($_SERVER['HTTPS'] == 'on') ? + BASE_SECURE_URL : BASE_URL; + + $this->captchaOptions = array( + 'width' => 100, + 'height' => 50, + 'callback' => "{$callbackUrl}Toolkit/qfcaptcha.php?var=$var", + 'sessionVar' => $var, + 'imageOptions' => array( + 'font_size' => 20, + 'font_path' => GLM_APP_BASE . 'glmPEAR/Image/Canvas/Fonts/', + 'font_file' => 'times.ttf', + 'background_color' => '#cccccc', + 'obfuscation' => false, + 'angle' => true, + ), + ); + } + + // }}} + + // {{{ configureConstats() + + /** + * Constant variables for the form + * + * These values won't get overridden by POST or GET vars + * + * @return void + * @access public + */ + public function configureConstants() + { + $constants = array( + 'user_agent' => $_SERVER['HTTP_USER_AGENT'], + 'remote_addr' => $_SERVER['REMOTE_ADDR'], + ); + $this->setupConstants($constants); + } + + // }}} + // {{{ configureDefaults() + + /** + * Initializes default form values + * + * @return void + * @access public + */ + public function configureDefaults() + { + $defaults = array( + 'state' => '', + 'mail_ok' => 1 + ); + + $this->setupDefaults($defaults); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + $this->setInterestFields(); + // Grouped Elements are defined here. + $this->interestsGroups =& $this->getInterestFields(); + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'user_agent' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'remote_addr' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'fname', + 'display' => 'First Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'lname', + 'display' => 'Last Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'org', + 'display' => 'Organization' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'address', + 'display' => 'Address 1' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'address2', + 'display' => 'Address 2' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'city', + 'display' => 'City' + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'state', + 'display' => 'State/Province', + 'opts' => $GLOBALS['states'] + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'zip', + 'display' => 'ZIP/Postal Code' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Email Address' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email_rmv', + 'display' => 'Verify Email Address' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'state', + 'display' => 'Business Type', + 'opts' => $this->getBusinessTypes() + ); + $radio[] = array('type' => 'radio', + 'req' => false, + 'name' => 'contact_method', + 'opts' => 'Email', + 'att' => 1 + ); + $radio[] = array('type' => 'radio', + 'req' => false, + 'name' => 'contact_method', + 'opts' => 'Phone', + 'att' => 2 + ); + $e[] = array( + 'type' => 'group', + 'req' => false, + 'name' => 'contact_method', + 'group' => $radio, + 'label' => 'How would you prefer to be contacted?', + 'seperator' => ' ', + 'appendName' => false + ); + /* + */ + if (is_array($this->interestsGroups)) { + foreach ($this->interestsGroups as $group => $gData) { + $this->myGroups[] = $gData; + $e[] = array( + 'type' => 'group', + 'req' => false, + 'name' => 'interest', + 'group' => $gData, + 'label' => $group, + 'seperator' => ' ', + 'appendName' => true + ); + } + } + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'comments', + 'display' => 'Comments' + ); + $e[] = array( + 'type' => 'CAPTCHA_Image', + 'req' => false, + 'name' => 'captcha_question', + 'display' => 'Verification code', + 'opts' => $this->captchaOptions + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'captcha_rmv', + 'display' => 'Enter verification code' + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit_rmv', + 'display' => 'Submit Form' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + // Form Rules + $r[] = array( + 'element' => array('email', 'email_rmv'), + 'message' => 'ERROR: Your Email Addresses Do Not Match!', + 'type' => 'compare', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'email', + 'message' => 'ERROR: Invalid Email Format!', + 'type' => 'checkEmail', + 'format' => array('use_rfc822' => true), + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + /* + $r[] = array( + 'element' => 'state', + 'message' => 'ERROR: Invalid State!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + */ + $r[] = array( + 'element' => 'phone', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'fax', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'zip', + 'message' => 'ERROR: Invalid Zip!', + 'type' => 'zip', + 'format' => array('requireDBCheck' => false), + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'mail_ok', + 'message' => 'ERROR: Invalid Value!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'captcha_rmv', + 'message' => 'ERROR: Incorrect verification code!', + 'type' => 'CAPTCHA', + 'format' => $this->captchaQuestion, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + // {{{ configureFilters() + + /** + * Form filter definitions + * + * Applies a data filter for the given fields when the form is submitted + * + * @return void + * @access public + */ + public function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Helper function, configures the entire form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + $this->configureDefaults(); + $this->configureConstants(); + } + + // }}} + // {{{ contactExists() + + /** + * Checks for a duplicate email address already in the DB. + * + * @param string $email The email address to check for in the DB + * + * @return boolean If the email address already exists + * @access protected + */ + protected function contactExists($email) + { + // Check if a contact w/ the submitted email already exists. + // if so, then we need to update, if not then do a fresh insert. + try { + $sql = " + SELECT count(*) AS count + FROM {$this->tableName} + WHERE email = :email"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':email', $email, PDO::PARAM_STR); + $stmt->execute(); + $stmt->bindColumn('count', $contactExists); + $stmt->fetch(); + + return (bool) $contactExists; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ emailOwner() + + /** + * Emails the owner the submitted data from the submitted form + * + * Uses a flexy template to render a nice looking html email. + * Fills in the supplied data from the form and doesn't add the + * empty fields the user didn't fill in. + * + * @param string $mailFactory What type of mail factory should we use + * + * @return boolean result of the mailing + * @access protected + */ + protected function emailOwner($mailFactory = 'mail') + { + if (!$this->email) { + return; + } + + $hasInterestField = $_POST['interest'];//$this->elementExists('interest'); + + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + // for comments textarea need to replace newlines with br + $this->formData['comments']['element'] = nl2br($this->getSubmitValue('comments')); + + $page->email_from = OWNER_EMAIL; + $page->subject = $this->subject; + $page->client_info = $this->clientInfo; + $page->fname = $this->getSubmitValue('fname'); + $page->lname = $this->getSubmitValue('lname'); + $page->formData = $this->formData; + + if ($hasInterestField) { + // Clean up the interests so they will look nice in the email + $page->formData['interest']['nowrap'] = 'nowrap'; + $page->formData['interest']['element'] = null; + + $g =& $this->getElement('interest'); + $ge =& $g->getElements(); + + $interests = array(); + foreach ($ge as $e) { + if ($e->getChecked()) { + $interests[] = $e->getText(); + } + } + $page->formData['interest']['element'] = implode('
    ', $interests); + } + + if ($this->elementExists('mail_ok')) { + // Clean up the mail_ok flag so its human readable + $page->formData['mail_ok']['element'] + = ($page->formData['mail_ok']['element']) ? 'Yes' : 'No'; + } + + $template->compile('emailOwner.tpl'); + $htmlMsg = $template->bufferedOutputObject($page); + + if ($hasInterestField) { + // Text version can't have HTML in it + // so reset the interests to use commas + $page->formData['interest']['element'] = implode(", ", $interests); + } + $msg = "{$page->subject}\n\n"; + $msg .= "From {$page->fname} {$page->lname}\n\n"; + $msg .= "Information\n\n"; + foreach ($page->formData as $i) { + $msg .= "{$i['label']}: {$i['element']}\n"; + } + + $mimeMail = new Mail_mime("\n"); + $mimeMail->setFrom("Online Form <{$page->email_from}>"); + $mimeMail->setSubject($this->subject); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $mail =& Mail::factory($mailFactory); + $body = $mimeMail->get(); + + $setHeader['Reply-To'] = "{$this->getSubmitValue('fname')} {$this->getSubmitValue('lname')} <{$this->getSubmitValue('email')}>"; + + $headers = $mimeMail->headers($setHeader); + + $res = $mail->send($this->email, $headers, $body); + if (PEAR::isError($res)) { + return Toolkit_Common::handleError($res); + } else { + return $res; + } + } + + // }}} + // {{{ error() + + /** + * Display errors with the form to the user + * + * @param object $error PEAR Error Object + * + * @return void + * @access public + */ + public function error($error) + { + // make the variables static so that is only has to do the defining + // on the first call. + static $errorMessages; + static $className; + + // define the various error messages + if (!isset($errorMessages)) { + $className = get_class($this); + $errorMessages = array( + FORM_OK => 'No error', + FORM_ERROR => 'Unknown error', + NO_RECORD => 'Setting both properties (email and hasContactDB) to false in the ' . $className . ' class will result in no email record being sent and no record being inserted into the database. There will be no record that this form was ever filled out.', + INVALID_DB => 'Please set the property hasContactDB to a boolean value in the class ' . $className . ' before continuing', + MISSING_CONSTANT => 'You have failed to set a CONSTANT for the class ' . $className . ' to function properly', + MISSING_CONTACT_TYPE => 'Please set the property contactType in the class '. $className . ' before continuing',); + } + + if (!is_null($error->message)) { + $message = $error->message; + } elseif (isset($errorMessages[$error->code])) { + $message = $errorMessages[$error->code]; + } else { + $message = $errorMessages[$error->code]; + $message = $errorMessages[FORM_ERROR]; + } + + echo "
    {$message}
    "; + } + + // }}} + // {{{ getBusinessTypes() + /** + * getBusinessTypes + * + * @access public + * @return string + */ + function getBusinessTypes() + { + return array( + '' => "Choose business", + "Advertising", + "Entertainment", + "Financial/Legal", + "Manufacturing", + "Publishing", + "Retail", + "Real Estate", + "Travel", + "Web Development", + "Wholesale", + "Other", + ); + } + // }}} + // {{{ getInterestFields() + + /** + * Returns the field definitions of the contact db interest fields + * + * @return array Group definitions for the interest fields + * @access protected + */ + protected function getInterestFields() + { + if (is_array($this->inquiries)) { + foreach ($this->inquiries as $group => $data) { + foreach ($data as $k => $v) { + $interests[$group][] = array('type' => 'checkbox', + 'req' => false, + 'name' => $k, + 'opts' => $v); + } + } + } + + return $interests; + } + + // }}} + + // {{{ insertData() + + /** + * Inserts contact data into the contact db + * + * @param array $values submitted values + * + * @return object result of db insert query + * @access protected + */ + protected function insertData($values) + { + unset($values['comments']); + $values['contact_type'] = ":{$this->contactType}:"; + if (is_array($values['interest']) && !empty($values['interest'])) { + foreach ($values['interest'] as $iGroup => $interests) { + $newInterest[] = implode(':', array_keys($interests)); + } + if (is_array($newInterest)) { + $values['interest'] = ':' . implode(':', $newInterest) . ':'; + } + } + try { + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ processData() + + /** + * Handles how to process the form when submitted + * + * @param array $values Form submitted values + * + * @return array Result of Insert / Update function + * @access protected + */ + public function processData($values) + { + // Form data used for the insert/update sql queries and + // the form email. + $e = array( + 'user_agent', + 'remote_addr', + 'contact_type', + ); + $this->setFormData($e); + + + // If no contact db, return true so we can send owner email. + if (!$this->hasContactDB) { + return true; + } + + // Get rid of any elements in the values array that + // aren't going to be used when inserting/updating the db. + $values = Toolkit_Common::cleanArray($values); + + // Send data off to StreamSend + if ( defined('STREAMSEND_FORMS_API') + && STREAMSEND_FORMS_API + && $values['mail_ok'] + ) { + // Insert the record into the streamsend server + $streamSend = new Toolkit_Contacts_StreamSend(); + $streamSend->addContact($values); + } + + // Check if we are updating an existing contact or not + // question: is this the best approach? what if someone else + // sends a form through w/ different data but the same emil addy + // the old users data can be completely wiped out. + $existingContact = $this->contactExists($values['email']); + + if ($existingContact) { + return $this->updateData($values); + } else { + return $this->insertData($values); + } + } + + // }}} + + // {{{ setInterestFields() + + /** + * Contact DB interests + * + * @return void + * @access protected + */ + protected function setInterestFields() + { + $this->inquiries['Area of Interest. Check all That Apply'] = array( + 'Web Site Development', + 'Web Hosting', + 'Search Engine Optimization Program', + 'Wireless Equipment/Connectivity', + 'Broadband/Connectivity', + 'Network Consultation', + ); + } + + // }}} + // {{{ setupRenderers() + // @codeCoverageIgnoreStart + + /** + * Custom rendering templates for special fields on the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + $required = ' * '; + $error = '
    {error}
    '; + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'interest'); + if (is_array($this->interestsGroups)) { + foreach ($this->interestsGroups as $group => $gData) { + $renderer->setGroupTemplate('
    {content}', 'interest['.$group.']'); + $renderer->setGroupElementTemplate('{element}', 'interest['.$group.']'); + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'interest['.$group.']'); + } + } + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'comments'); + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'submit_rmv'); + + $renderer->setElementTemplate('{element}', 'captcha_question'); + $renderer->setElementTemplate(''.$required.''.$error.'{element}What is this?', 'captcha_rmv'); + } + + // @codeCoverageIgnoreEnd + // }}} + // {{{ toHtml() + + /** + * Handles how to display the current step the user is at in the form + * + * destroying and resetting the captcha value dis-allows someone from + * re-sending a form on a previous captcha. + * + * @return string form HTML state + * @access public + */ + public function toHtml() + { + $this->setupRenderers(); + if ($this->validate()) { + $this->captchaQuestion->destroy(); + $this->cleanForm(); + + if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) { + $this->freeze(); + $this->emailOwner(); + $this->successMsg = '

    Thank You
    '.$_REQUEST['fname'].',
    a representative will be in contact with you promptly.

     

     

     

    '; + $output = $this->successMsg; + } + $this->sent = true; + } elseif ($this->isSubmitted()) { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + $output = $this->errorMsg; + $output .= parent::toHTML(); + } else { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + $output = parent::toHTML(); + } + return $output; + } + + // }}} + + // {{{ updateData() + + /** + * Updates the contact in the contact db + * + * @param array $values Form submitted values + * + * @return object Result of the update query + * @access protected + */ + protected function updateData($values) + { + unset($values['comments']); + if (is_array($values['interest']) && !empty($values['interest'])) { + foreach ($values['interest'] as $iGroup => $interests) { + $newInterest[] = implode(':', array_keys($interests)); + } + if (is_array($newInterest)) { + $values['interest'] = ':' . implode(':', $newInterest) . ':'; + } + } + + try { + // Get all the existing contact type data + $sql = " + SELECT contact_type + FROM {$this->tableName} + WHERE email = :email"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':email', $values['email'], PDO::PARAM_STR); + $stmt->execute(); + $stmt->bindColumn('contact_type', $cType); + $stmt->fetch(); + + $existingTypes = explode(':', $cType); + if (!in_array($this->contactType, $existingTypes)) { + $values['contact_type'] = "$cType{$this->contactType}:"; + } + + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('email = :email') + ); + + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} +} +?> diff --git a/Toolkit/Contacts/Payments.php b/Toolkit/Contacts/Payments.php new file mode 100755 index 0000000..0a23e1c --- /dev/null +++ b/Toolkit/Contacts/Payments.php @@ -0,0 +1,1243 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Payments.php,v 1.6 2010/10/06 18:02:55 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Error codes for Toolkit_Contacts_ContactUs + * + * Codes are mapped to textual messaged by errorMessage() method, + * if you add a new code be sure to add a new message for it to errorMessage() + * + * @see Toolkit_Contacts_ContactUs::errorMessage() + */ +define('FORM_OK', 1); +define('FORM_ERROR', -1); +define('NO_RECORD', -2); +define('INVALID_DB', -3); +define('MISSING_CONSTANT', -4); +define('MISSING_CONTACT_TYPE', -5); + +/** + * GLM Contact Us form + * + * This form handles rendering and processing the contact us form. + * Controls the email functionality of the form, whether the client + * has a contact DB to store contact records and how to insert/update + * submitted form values. + * + * @category Contacts + * @package Toolkit_Contacts + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_FormBuilder + */ +class Toolkit_Contacts_Payments + extends Toolkit_FormBuilder implements Toolkit_Form +{ + // {{{ properties + + /** + * Table in Database which holds the contact data + * + * @var string + * @access public + */ + public $tableName = 'contact'; + + private $_config; + + /** + * Table meta data + * + * This is used when inserting/updating data for the records + * so the PDO's can use explicit data types for the parameters. + * + * @var array + * @access public + */ + public $tableMetaData = array(); + + /** + * Contact type to be inserted into the DB as when the form is submitted + * + * This property is only valid when the [hasContactDB] property is set + * to true. + * + * N.B. + * If you subclass this class out to other forms that are + * inserted into the contact db, be sure to make each one of their + * contactType properties unique. We don't check for duplicates. + * + * @var string + * @access protected + */ + protected $contactType = '1'; + + /** + * Who to send the email to when the contact form is submitted + * + * If you leave this blank, its value will get set to the OWNER_EMAIL + * in the constructor. + * + * If you ***DO NOT*** want any emails to go out when the form is submitted + * then set the value to false. Do not set it to 0 for false, because the + * check uses a strict type check to determine if the value is actually + * false. This is what allows for the empty value as an option, which sets + * the value to OWNER_EMAIL and won't override the $email property if + * this class gets subclassed and the value for this property gets set in + * the properties of the subclass and not in the constructor after this + * constructor function is called. + * + * tongue twister...I know. + * + * protected $email = false; + * + * + * @var string + * @access protected + */ + protected $email; + + /** + * From header in the owner email + * + * This just sets the From header in the owner email + * SITENAME + * + * It gets set to the constant SITENAME in the constructor if you leave + * empty here, but you can set it to something different here to override + * that if you desire. + * + * @var string + * @access protected + */ + protected $siteName; + + /** + * Email subject and

    header in email + * + * It gets set in the constructor if you leave empty here, but you + * can set it to something different here to override that if you desire. + * + * @var string + * @access protected + */ + public $subject; + + /** + * Whether the site has a contact DB to store contact records + * + * If this value is set to false, an email will still be sent to the + * addressed specified in the email property. + * + * @var boolean + * @access protected + */ + protected $hasContactDB = false; + + /** + * The interests from the contact db + * + * @var array + * @access protected + */ + protected $inquiries = array(); + + /** + * Message to display if the form is successfully submitted + * + * @var string + * @access protected + */ + protected $successMsg = ' +
    + Thank you for your payment! +
    '; + + /** + * Extra rules for processesing + * + * This registers the Zip validation rules (and any others listed) for + * QuickForm. + * + * Zip validation checks both US and Canadian Zip codes + * + * @var array + * @access protected + * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rules/Zip.php + */ + protected $registeredRules = array( + 'zip', + 'phone', + array( + 'checkEmail', + 'callback', + 'email', + 'Validate' + ), + ); + + public $autoValidateDateElements = false; + + /** + * Options for flexy templating engine + * + * Pulls the preset options from the setup.phtml file + * overwrites the templateDir and compileDir to match this classes needs + * + * @var array + * @access protected + */ + protected $flexyOptions; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param object $pdo PHP Data Object + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @author Jamie Kahgee + * @access public + * @link http://pear.php.net/package/HTML_QuickForm/docs/latest/HTML_QuickForm/HTML_QuickForm.html + * @see HTML_QuickForm + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + // Make sure these end cases are never met. + // These are more for the development phase. + if ($this->email === false && $this->hasContactDB === false) { + PEAR::raiseError( + null, + NO_RECORD, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + if (!is_bool($this->hasContactDB)) { + PEAR::raiseError( + null, + INVALID_DB, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + // we haven't defined the FROM_NEWS_EMAIL constant and + // the email will default to relying on it. + if ( !defined('FROM_NEWS_EMAIL') + && (empty($this->email) && $this->email !== false) + ) { + PEAR::raiseError( + 'You need to define the FROM_NEWS_EMAIL + constant for this form to work correctly', + MISSING_CONSTANT, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + if (!is_numeric($this->contactType) && $this->hasContactDB) { + PEAR::raiseError( + null, + MISSING_CONTACT_TYPE, + PEAR_ERROR_CALLBACK, + array(&$this, 'error') + ); + } + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + + // Default Renderer Form templates for QuickForm in respect to this + // classes needs. + $this->template = dirname(__FILE__) . '/templates/currentTables/'; + if ($this->email !== false && empty($this->email)) { + // Set to false to turn off email function. + $this->email = PAYMENT_FORM_EMAIL; + } + if (empty($this->siteName)) { + $this->siteName = SITENAME; + } + if (empty($this->subject)) { + $this->subject = 'Online Payment from website ' . SITENAME; + } + + /** + * Where are the flexy templates stored at for this class. + */ + define('TEMPLATES_DIR', BASE . 'Toolkit/Contacts/templates'); + + /** + * Where are the compiled flexy templates stored at for this class. + */ + define('COMPILED_DIR', BASE . 'Toolkit/Contacts/templates/compiled'); + $oldUmask = umask(0); + if (!is_dir(TEMPLATES_DIR)) { + mkdir(TEMPLATES_DIR, 0770, true); + } + if (!is_dir(COMPILED_DIR)) { + mkdir(COMPILED_DIR, 0770, true); + } + umask($oldUmask); + + $this->flexyOptions = $GLOBALS['flexyOptions']; + $this->flexyOptions['templateDir'] = TEMPLATES_DIR; + $this->flexyOptions['compileDir'] = COMPILED_DIR; + + $var = basename(__FILE__, '.php'); + + $callbackUrl = ($_SERVER['HTTPS'] == 'on') ? + BASE_SECURE_URL : BASE_URL; + + $this->captchaOptions = array( + 'width' => 100, + 'height' => 50, + 'callback' => "{$callbackUrl}Toolkit/qfcaptcha.php?var=$var", + 'sessionVar' => $var, + 'imageOptions' => array( + 'font_size' => 20, + 'font_path' => GLM_APP_BASE . 'glmPEAR/Image/Canvas/Fonts/', + 'font_file' => 'times.ttf', + 'background_color' => '#cccccc', + 'obfuscation' => false, + 'angle' => true, + ), + ); + } + + // }}} + + // {{{ checkCvv() + + /** + * Check if the credit card CVV is properly formatted + * + * @param array $values credit card num and cvv number from the form + * + * @return boolean whether the cvv is properly formatted + * @access public + */ + public function checkCvv($values) + { + return Validate_Finance_CreditCard::cvv($values[0], $values[1]); + } + + // }}} + // {{{ checkNumber() + + /** + * Check if the credit card number is properly formatted + * + * Credit card numbers have a specific formatting based on the credit card + * types. + * i.e. (visa, discover, etc...) This call verifies if the # was properly + * formatted against the card type selected + * + * @param array $values credit card type and number from the form + * + * @return boolean if cc number is properly formatted based on the card type + * @access public + */ + public function checkNumber($values) + { + if (empty($values[1])) { + $values[1] = null; + } + + return Validate_Finance_CreditCard::number($values[0], $values[1]); + } + + // }}} + // + // {{{ configureConstats() + + /** + * Constant variables for the form + * + * These values won't get overridden by POST or GET vars + * + * @return void + * @access public + */ + public function configureConstants() + { + $constants = array( + 'user_agent' => $_SERVER['HTTP_USER_AGENT'], + 'remote_addr' => $_SERVER['REMOTE_ADDR'], + ); + $this->setupConstants($constants); + } + + // }}} + // {{{ configureDefaults() + + /** + * Initializes default form values + * + * @return void + * @access public + */ + public function configureDefaults() + { + $defaults = array( + 'state' => '', + 'mail_ok' => 1 + ); + + $this->setupDefaults($defaults); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $ccTypes = array( + '' => '-- Select --', + 'mastercard' => 'Master Card', + 'visa' => 'Visa', + ); + $e = array(); + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'name' => 'personalInfoHdr', + 'display' => 'Personal Information' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'user_agent' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'remote_addr' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'fname', + 'display' => 'First Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'lname', + 'display' => 'Last Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'company', + 'display' => 'Company Name' + ); + + $e[] = array( + 'type' => 'header', + 'name' => 'billingInfoHdr', + 'display' => 'Billing Information' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'address', + 'display' => 'Billing Address' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'city', + 'display' => 'City' + ); + $e[] = array( + 'type' => 'select', + 'req' => true, + 'name' => 'state', + 'display' => 'State/Province', + 'opts' => $GLOBALS['states'] + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'zip', + 'display' => 'ZIP/Postal Code' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'phone', + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email_rmv', + 'display' => 'Verify Email' + ); + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'creditCardInfoHdr', + 'display' => 'Credit Card Information' + ); + + $e[] = array( + 'type' => 'html', + + 'name' => ' +' + ); + + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'cc_fname', + 'display' => 'First Name on
    Credit Card', + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'cc_lname', + 'display' => 'Last Name on
    Credit Card', + ); + $e[] = array( + 'type' => 'select', + 'req' => true, + 'name' => 'cc_type', + 'display' => 'Credit Card Type', 'opts' => $ccTypes + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'cc_num', + 'display' => 'Credit Card Number' + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'cc_exp', + 'display' => 'Expiration Date', 'opts' => array('format' => 'm / Y', 'minYear' => date('Y'), 'maxYear' => date('Y') + 10, 'addEmptyOption' => true, 'emptyOptionText' => array('m' => 'mm', 'Y' => 'yyyy')) + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'cc_cvv', + 'display' => 'CVV' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'amount', + 'display' => 'Amount to pay' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'invoice_number', + 'display' => 'Invoice Number' + ); +/* +//removed this option list per Candace 10/06/10 jm'payment + $e[] = array( + 'type' => 'select', + 'req' => true, + 'name' => 'payment_type', + 'display' => 'Pay this', + 'opts' => array( + 'once' => 'Once', + 'monthy' => 'Monthly', + 'yearly' => 'Yearly' + ) + ); +*/ + $e[] = array( + 'type' => 'header', + 'name' => 'verificationHdr', + 'display' => 'Verification' + ); + $e[] = array( + 'type' => 'CAPTCHA_Image', + 'req' => false, + 'name' => 'captcha_question', + 'display' => 'Verification code', + 'opts' => $this->captchaOptions + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'captcha_rmv', + 'display' => 'Enter verification code' + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit_rmv', + 'display' => 'Submit Form' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + // Form Rules + $r[] = array( + 'element' => array('email', 'email_rmv'), + 'message' => 'ERROR: Your Email Addresses Do Not Match!', + 'type' => 'compare', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'phone', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'fax', + 'message' => 'ERROR: Invalid number (xxx) xxx-xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'zip', + 'message' => 'ERROR: Invalid Zip!', + 'type' => 'zip', + 'format' => array('requireDBCheck' => false), + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'amount', + 'message' => 'ERROR: Invalid Value!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'captcha_rmv', + 'message' => 'ERROR: Incorrect verification code!', + 'type' => 'CAPTCHA', + 'format' => $this->captchaQuestion, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => array('cc_num', 'cc_type'), + 'message' => 'ERROR: Number does not match card type!', + 'type' => 'callback', + 'format' => array(&$this, 'checkNumber'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => array('cc_cvv', 'cc_type'), + 'message' => 'ERROR: CVV does not match card type!', + 'type' => 'callback', + 'format' => array(&$this, 'checkCvv'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + // {{{ configureFilters() + + /** + * Form filter definitions + * + * Applies a data filter for the given fields when the form is submitted + * + * @return void + * @access public + */ + public function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Helper function, configures the entire form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + $this->configureDefaults(); + $this->configureConstants(); + } + + // }}} + // {{{ contactExists() + + /** + * Checks for a duplicate email address already in the DB. + * + * @param string $email The email address to check for in the DB + * + * @return boolean If the email address already exists + * @access protected + */ + protected function contactExists($email) + { + // Check if a contact w/ the submitted email already exists. + // if so, then we need to update, if not then do a fresh insert. + try { + $sql = " + SELECT count(*) AS count + FROM {$this->tableName} + WHERE email = :email"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':email', $email, PDO::PARAM_STR); + $stmt->execute(); + $stmt->bindColumn('count', $contactExists); + $stmt->fetch(); + + return (bool) $contactExists; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ emailOwner() + + /** + * Emails the owner the submitted data from the submitted form + * + * Uses a flexy template to render a nice looking html email. + * Fills in the supplied data from the form and doesn't add the + * empty fields the user didn't fill in. + * + * @param string $mailFactory What type of mail factory should we use + * + * @return boolean result of the mailing + * @access protected + */ + protected function emailOwner($mailFactory = 'mail') + { + if (!$this->email) { + return; + } + + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + + + // for comments textarea need to replace newlines with br + $this->formData['comments']['element'] = nl2br($this->getSubmitValue('comments')); + + $page->email_from = OWNER_EMAIL; + $page->subject = $this->subject; + $page->client_info = $this->clientInfo; + $page->fname = $this->getSubmitValue('fname'); + $page->lname = $this->getSubmitValue('lname'); + $page->formData = $this->formData; + + unset($page->formData['cc_cvv']); + foreach ($page->formData as $formFieldName => $i) { + if ($formFieldName == "cc_num") { + $ccNum = preg_replace('/\d/', '*', $i['element'], strlen($i['element']) - 4); + $page->formData['cc_num']['element'] = $ccNum; + } + } + + $template->compile('emailOwner.tpl'); + $htmlMsg = $template->bufferedOutputObject($page); + + $msg = "{$page->subject}\n\n"; + $msg .= "From {$page->fname} {$page->lname}\n\n"; + $msg .= "Information\n\n"; + foreach ($page->formData as $i) { + $msg .= "{$i['label']}: {$i['element']}\n"; + } + + $mimeMail = new Mail_mime("\n"); + $mimeMail->setFrom("Online Payment Form <{$page->email_from}>"); + $mimeMail->setSubject($this->subject); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $mail =& Mail::factory($mailFactory); + $body = $mimeMail->get(); + + $setHeader['Reply-To'] = "{$this->getSubmitValue('fname')} {$this->getSubmitValue('lname')} <{$this->getSubmitValue('email')}>"; + + $headers = $mimeMail->headers($setHeader); + + $res = $mail->send($this->email, $headers, $body); + if (PEAR::isError($res)) { + return Toolkit_Common::handleError($res); + } else { + return $res; + } + } + + // }}} + // {{{ emailReceipt() + + protected function emailReceipt() + { + $e1 =& $this->getElement('email'); + $email = $e1->getValue(); + if (!$email) { + return false; + } + try { + $headers['From'] = 'Gaslight Media Online Payment <'.OWNER_EMAIL.'>'; + $headers['Subject'] = 'Gaslight Media Online Payment'; + $headers['Reply-To'] = OWNER_EMAIL; + + $e =& $this->getElement('cc_num'); + $ccNum = $e->getValue(); + $ccNum = preg_replace('/\d/', '*', $ccNum, strlen($ccNum) - 4); + + $body = "Your card has been charged by " . SITENAME . ". Below is your receipt of payment.\n\n"; + $body .= "Confirmation #: {$this->transactionId} \n"; + $body .= "Amount: \${$this->formData['amount']['element']} \n"; + $body .= "Card Holder: {$this->formData['fname']['element']} {$this->formData['lname']['element']}\n"; + $body .= "Card Number: $ccNum\n"; + + $body .= "Please print or write down your confirmation number for your records.\n"; + $body .= "If you have questions regarding your payment, please call:\n\n"; + + $body .= "231.487.0692"; + + $mail =& Mail::factory('mail'); + $mail->send($email, $headers, $body); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // + // {{{ error() + + /** + * Display errors with the form to the user + * + * @param object $error PEAR Error Object + * + * @return void + * @access public + */ + public function error($error) + { + // make the variables static so that is only has to do the defining + // on the first call. + static $errorMessages; + static $className; + + // define the various error messages + if (!isset($errorMessages)) { + $className = get_class($this); + $errorMessages = array( + FORM_OK => 'No error', + FORM_ERROR => 'Unknown error', + NO_RECORD => 'Setting both properties (email and hasContactDB) to false in the ' . $className . ' class will result in no email record being sent and no record being inserted into the database. There will be no record that this form was ever filled out.', + INVALID_DB => 'Please set the property hasContactDB to a boolean value in the class ' . $className . ' before continuing', + MISSING_CONSTANT => 'You have failed to set a CONSTANT for the class ' . $className . ' to function properly', + MISSING_CONTACT_TYPE => 'Please set the property contactType in the class '. $className . ' before continuing',); + } + + if (!is_null($error->message)) { + $message = $error->message; + } elseif (isset($errorMessages[$error->code])) { + $message = $errorMessages[$error->code]; + } else { + $message = $errorMessages[$error->code]; + $message = $errorMessages[FORM_ERROR]; + } + + echo "
    {$message}
    "; + } + + // }}} + // {{{ getBusinessTypes() + /** + * getBusinessTypes + * + * @access public + * @return string + */ + function getBusinessTypes() + { + return array( + '' => "Choose business", + "Advertising", + "Entertainment", + "Financial/Legal", + "Manufacturing", + "Publishing", + "Retail", + "Real Estate", + "Travel", + "Web Development", + "Wholesale", + "Other", + ); + } + // }}} + // {{{ getInterestFields() + + /** + * Returns the field definitions of the contact db interest fields + * + * @return array Group definitions for the interest fields + * @access protected + */ + protected function getInterestFields() + { + if (is_array($this->inquiries)) { + foreach ($this->inquiries as $group => $data) { + foreach ($data as $k => $v) { + $interests[$group][] = array('type' => 'checkbox', + 'req' => false, + 'name' => $k, + 'opts' => $v); + } + } + } + + return $interests; + } + + // }}} + + // {{{ processAuthNet() + + /** + * Send payment to auth.net + * + * Test Cards + * Card Number Card Type + * =============== =============== + * 370000000000002 American Express + * 6011000000000012 Discover Card + * 5424000000000015 MasterCard + * 4000000000000000 Visa + * + * @param array $values Submitted values from the form + * + * @return array Auth.net response + * @access protected + */ + protected function processAuthNet($values) + { + $this->setFormData(); + + $authNetValues = array( + 'x_login' => $this->_config->auth_net->login, + 'x_version' => '3.1', + 'x_delim_char' => '|', + 'x_delim_data' => 'TRUE', + 'x_type' => 'AUTH_CAPTURE', + 'x_method' => 'CC', + 'x_tran_key' => $this->_config->auth_net->tran_key, + 'x_relay_response' => 'FALSE', + 'x_test_request' => $this->_config->auth_net->test ? "TRUE" : "FALSE", + 'x_card_num' => $values['cc_num'], + 'x_exp_date' => implode('', $values['cc_exp']), + 'x_amount' => $values['amount'], + 'x_first_name' => $values['cc_fname'], + 'x_last_name' => $values['cc_lname'], + 'x_address' => $values['address'], + 'x_city' => $values['city'], + 'x_state' => $values['state'], + 'x_zip' => $values['zip'], + 'x_phone' => $values['phone'], + 'x_invoice_num' => $values['invoice_number'], + 'x_company' => $values['company'], + 'x_email' => $values['email'], + 'x_customer_ip' => $values['remote_addr'], + 'x_duplicate_window' => $this->_config->auth_net->duplicate_window, + ); + + $fields = ''; + foreach ($authNetValues as $i => $j) { + $fields .= "$i=" . urlencode($j) . '&'; + } + + $ch = curl_init($this->_config->auth_net->url); + // set to 0 to elimindate header info from response + curl_setopt($ch, CURLOPT_HEADER, 0); + // Returns response data instead of TRUE(1) + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + // Use HTTP POST to send form data + curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($fields, "& ")); + // Uncomment this line if you get no gateway response. ### + // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + // Execute post and get results + $resp = curl_exec($ch); + curl_close($ch); + + $res = explode('|', $resp); + $this->transactionId = $res[6]; + return $res; + } + + // }}} + // {{{ processData() + + /** + * Handles how to process the form when submitted + * + * @param array $values Form submitted values + * + * @return array Result of Insert / Update function + * @access protected + */ + public function processData($values) + { + //echo '
    '.print_r($values, true).'
    '; + //exit; + //$this->setFormData(); + // Form data used for the insert/update sql queries and + // the form email. + $e = array( + 'user_agent', + 'remote_addr', + 'contact_type', + ); + return $this->processAuthNet($values); + + } + + // }}} + + // {{{ setInterestFields() + + /** + * Contact DB interests + * + * @return void + * @access protected + */ + protected function setInterestFields() + { + $this->inquiries['Area of Interest. Check all That Apply'] = array( + 'Web Site Development', + 'Web Hosting', + 'Search Engine Optimization Program', + 'Wireless Equipment/Connectivity', + 'Broadband/Connectivity', + 'Network Consultation', + ); + } + + // }}} + // {{{ setConfig() + + /** + * Contact DB interests + * + * @return void + * @access protected + */ + public function setConfig(Zend_Config_Ini $config) + { + $this->_config = $config; + } + + // }}} + // {{{ setupRenderers() + // @codeCoverageIgnoreStart + + /** + * Custom rendering templates for special fields on the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + $required = ' * '; + $error = '
    {error}
    '; + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'interest'); + if (is_array($this->interestsGroups)) { + foreach ($this->interestsGroups as $group => $gData) { + $renderer->setGroupTemplate('
    {content}', 'interest['.$group.']'); + $renderer->setGroupElementTemplate('{element}', 'interest['.$group.']'); + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'interest['.$group.']'); + } + } + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'comments'); + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'submit_rmv'); + + $renderer->setElementTemplate('{element}', 'captcha_question'); + $renderer->setElementTemplate(''.$required.''.$error.'{element}What is this?', 'captcha_rmv'); + } + + // @codeCoverageIgnoreEnd + // }}} + // {{{ toHtml() + + /** + * Handles how to display the current step the user is at in the form + * + * destroying and resetting the captcha value dis-allows someone from + * re-sending a form on a previous captcha. + * + * @return string form HTML state + * @access public + */ + public function toHtml() + { + $this->setupRenderers(); + if ($this->validate()) { + $this->captchaQuestion->destroy(); + $this->cleanForm(); + $ret = $this->process(array(&$this, 'processData')); + if (is_array($ret) && !empty($ret)) { + $this->freeze(); + if ($ret[0] == 1) { + // Success + $date = date('Y'); + $output = $this->successMsg; + + // Obscure CC Num so its not displayed. + $e =& $this->getElement('cc_num'); + $ccNum = $e->getValue(); + $newCCNum = preg_replace('/\d/', '*', $ccNum, strlen($ccNum) - 4); + $e->setValue($newCCNum); + + // Remove the CVV Num so its not displayed. + $this->removeElement('cc_cvv'); + $this->removeElement('verificationHdr'); + $this->removeElement('captcha_question'); + + $this->emailOwner(); + $this->emailReceipt(); + + // This is a continuation of the group element hack. + $html = parent::toHTML(); + $output .= preg_replace('/\(x\)<\/tt>/', '', $html, 1); + } elseif ($ret[0] == 2) { + // Declined + $output = '

    Your credit card has been declined.

    '; + $output .= '

    Please call us at 231.487.0692 for help.

    '; + } else { + // Error + $output = '

    There was an error processing your credit card.

    '; + $output .= '

    Please call us at 231.487.0692 for help.

    '; + } + } else { + $output = '

    There was an error processing your credit card.

    '; + $output .= '

    Please call us at 231.487.0692 for help.

    '; + } + } elseif ($this->isSubmitted()) { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + $output = $this->errorMsg; + $output .= parent::toHTML(); + } else { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + $output = parent::toHTML(); + } + return $output; + } + + // }}} +} diff --git a/Toolkit/Contacts/StreamSend.php b/Toolkit/Contacts/StreamSend.php new file mode 100755 index 0000000..112539c --- /dev/null +++ b/Toolkit/Contacts/StreamSend.php @@ -0,0 +1,201 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: StreamSend.php,v 1.1.1.1 2009/09/17 20:08:57 matrix Exp $ + * @link <> + */ + +/** + * Default parameters for contact create operations. + * Note that these are strings for use in XML data not true/false values. + * If false, the person will be created with a status of pending + */ +define('STREAMSEND_DEFAULT_ACTIVATE', 'false'); +/** + * If activate is false, setting this to true will trigger the sending of the built-in + * activation notification; if activate is true, this setting has no effect + */ +define('STREAMSEND_DEFAULT_DELIVER_ACTIVATION', 'true'); +/** + * If activate is true, setting this to true will trigger the sending of the built-in + * welcome notification; if activate is false, this setting has no effect + */ +define('STREAMSEND_DEFAULT_DELIVER_WELCOME', 'false'); +/** + * URI for streamsend API + */ +define('STREAMSEND_BASE_URL', "https://app.streamsend.com"); + +/** + * Toolkit_Contacts_StreamSend + * + * Contact support class for inergration with StreamSend API + * + * @category Contacts + * @package Toolkit_Contacts + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @link <> + */ +class Toolkit_Contacts_StreamSend +{ + // {{{ Class Properties + + + /** + * Description for public + * @var boolean + * @access public + */ + public $debug = false; + + /** + * streamSendFields + * + * array with key values matching the gaslight contact tabel to the + * StreamSend field (normal fields) + * + * @var array + * @access protected + */ + protected $streamSendFields = array( + 'email' => 'email-address', + 'fname' => 'first-name', + 'lname' => 'last-name', + 'address' => 'address1', + 'address2' => 'address2', + 'city' => 'city', + 'state' => 'stateprovince', + 'zip' => 'postal-code', + 'phone' => 'phone-number' + ); + + /** + * contactInqTypes + * + * array with key values matching the gaslight contact_inq tabel to the + * StreamSend field (Radio fields) + * key = id from contact_inq table + * value = name from contact_inq_table + * value is same name as the StreamSend fieldname + * + * @var array + * @access protected + */ + protected $contactInqTypes = array(); + + /** + * booleanTypes + * + * StreamSend fields (boolean fields) an array of field names for the + * boolean field types + * + * @var array + * @access protected + */ + protected $booleanTypes = array(); + // }}} + // {{{ __construct() + + + /** + * __construct( + * + * @return void + * @access public + */ + public function __construct() + { + } + + + // }}} + // {{{ addContact() + + + /** + * addContact + * + * Given $values from a Toolkit_Contacts Form add Contact + * + * @param array $values Parameter description (if any) ... + * + * @return boolean Return true if successfull + * @access public + */ + public function addContact($values) + { + // check the array $values to make sure it is correct + if (is_array($values) && !empty($values)) { + include_once GLM_APP_BASE.'StreamSend/class_streamsend_api.inc'; + // initialize the streamsend object + $ss = new streamSend (STREAMSEND_BASE_URL, STREAMSEND_LOGIN_ID, + STREAMSEND_KEY); + $ss->debug = $this->debug; + $contactData = array(); + $values[$type] = 1; + foreach ($this->streamSendFields as $glmName => $ssName) { + switch ($glmName) { + case "state": + $contactData[$ssName] = ($values[$glmName]) ? $GLOBALS['states'][$values[$glmName]]: ''; + break; + default: + $contactData[$ssName] = $values[$glmName]; + break; + } + } + foreach ($this->contactInqTypes as $contactInqId => $name) { + $slug = str_replace(" ", "-", strtolower($this->contactInqTypes[$contactInqId])); + if ($values['interest'][$contactInqId]) { + $contactData[$slug] = 'Yes'; + } else { + $contactData[$slug] = 'No'; + } + } + foreach ($this->booleanTypes as $name) { + if ($values[$name]) { + $contactData[$name] = 'Yes'; + } else { + $contactData[$name] = 'No'; + } + } + $contacts = $ss->contactCreate( + $contactData, + STREAMSEND_DEFAULT_ACTIVATE, + STREAMSEND_DEFAULT_DELIVER_ACTIVATION, + STREAMSEND_DEFAULT_DELIVER_WELCOME + ); + if (!$contacts) { + + // show errors if on development server + switch (GLM_HOST_ID) { + case "DEVELOPMENT": + echo "

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

    Debug Results

    '.$ss->debugBuffer.'

    '; + } + return true; + } + return false; + } + + + // }}} +} +?> diff --git a/Toolkit/Contacts/database-table-modifiers.sql b/Toolkit/Contacts/database-table-modifiers.sql new file mode 100644 index 0000000..b539d26 --- /dev/null +++ b/Toolkit/Contacts/database-table-modifiers.sql @@ -0,0 +1,46 @@ +CREATE SEQUENCE contact_id_seq + INCREMENT BY 1 + NO MAXVALUE + NO MINVALUE + CACHE 1; + +ALTER TABLE contact ALTER COLUMN id SET DEFAULT nextval('contact_id_seq'::regclass); + +ALTER TABLE ONLY contact + ADD CONSTRAINT contact_pkey PRIMARY KEY (id); + +CREATE INDEX contact_create_date_indx ON contact USING btree (create_date); + +CREATE INDEX contact_email_indx ON contact USING btree (email); + +CREATE INDEX contact_fname_indx ON contact USING btree (fname); + +CREATE UNIQUE INDEX contact_id_indx ON contact USING btree (id); + +CREATE INDEX contact_lname_indx ON contact USING btree (lname); + +CREATE UNIQUE INDEX news_response_id_indx ON contact USING btree (id); + +CREATE UNIQUE INDEX query_db_id_indx ON contact USING btree (id); + +CREATE SEQUENCE contact_inq_id_seq + INCREMENT BY 1 + NO MAXVALUE + NO MINVALUE + CACHE 1; + +ALTER TABLE contact_inq ALTER COLUMN id SET DEFAULT nextval('contact_inq_id_seq'::regclass); + +ALTER TABLE ONLY inq_group + ADD CONSTRAINT inq_group_pkey PRIMARY KEY (id); + +CREATE SEQUENCE inq_group_id_seq + INCREMENT BY 1 + NO MAXVALUE + NO MINVALUE + CACHE 1; + +ALTER TABLE inq_group ALTER COLUMN id SET DEFAULT nextval('inq_group_id_seq'::regclass); + +ALTER TABLE ONLY inq_group + ADD CONSTRAINT inq_group_pkey PRIMARY KEY (id); diff --git a/Toolkit/Contacts/database-tables.sql b/Toolkit/Contacts/database-tables.sql new file mode 100644 index 0000000..1b71879 --- /dev/null +++ b/Toolkit/Contacts/database-tables.sql @@ -0,0 +1,45 @@ +CREATE TABLE contact ( + id integer NOT NULL, + create_date date DEFAULT CURRENT_DATE, + fname text, + lname text, + company text, + address text, + address2 text, + city text, + state text, + zip text, + country text, + phone text, + fax text, + email text, + user_agent text, + remote_addr text, + interest text, + mail_ok boolean DEFAULT false, + visitorguide boolean DEFAULT false, + uidpdf text, + visitorguide_download boolean DEFAULT false, + email_verified boolean DEFAULT true, + contact_type text, + discover text, + member_ok boolean DEFAULT false, + staff boolean DEFAULT false, + comments text, + password text, + verify_password text +); + +CREATE TABLE inq_group ( + id integer NOT NULL, + name text +); + +CREATE TABLE contact_inq ( + id integer NOT NULL, + header text, + pos integer, + description text, + image text, + groupid integer +); diff --git a/Toolkit/Contacts/templates/brochurePage.html b/Toolkit/Contacts/templates/brochurePage.html new file mode 100755 index 0000000..b90d3d5 --- /dev/null +++ b/Toolkit/Contacts/templates/brochurePage.html @@ -0,0 +1,9 @@ + +
    DOWNLOAD: +

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

    +
    +
    + {pdfForm:h} +
    +

    ORDER BY MAIL:

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

    Your Trip Planner List

    +

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

    +

    Request Information by Phone from:

    +

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

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

    Request Information by Email from:

    +

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

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

    Plan Your Trip Information Request Form

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

    + + {subject:h} + +

    +

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

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

    Dear {fname}

    +

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

    +

    Message here.

    +
     

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

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

    +

    Brochure ({pdfFileSize})

    +

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

    +

    Sincerely,

    +

    {client_info[name]:h}

    +

    {client_info[url]:h}

    + + + diff --git a/Toolkit/DataGridBuilder.php b/Toolkit/DataGridBuilder.php new file mode 100644 index 0000000..691d539 --- /dev/null +++ b/Toolkit/DataGridBuilder.php @@ -0,0 +1,285 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ + +/** + * Create Datagrids for displaying data + * + * This abstract class handles all the base functionality of creating + * handeling all the details associated w/ a regular dataGrid. + * 1. Creation + * 2. Sorting (via column headers or sortform) + * 3. Pagenation + * + * @category Structures + * @package Toolkit_DataGridBuilder + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @Release CVS: $Id: DataGridBuilder.php,v 1.1.1.1 2009/09/17 20:08:55 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see Toolkit_SortForm, Structures_DataGrid + */ +abstract class Toolkit_DataGridBuilder extends Structures_DataGrid +{ + // {{{ properties + + /** + * Options to pass to DataGrid + * + * @var array + * @access protected + */ + protected $options; + + /** + * Rendering options for DataGrid + * + * @var array + * @access protected + */ + protected $rendererOptions = array( + 'sortIconASC' => '⇑', + 'sortIconDESC' => '⇓', + 'evenRowAttributes' => 'class="even"', + 'oddRowAttributes' => 'class="odd"', + 'sortingResetsPaging' => false, + ); + + /** + * Rendering options for DataGrid paging element + * + * @var array + * @access protected + */ + protected $pagerOptions = array( + 'nextImg' => 'Next', + 'prevImg' => 'Previous', + 'separator' => '', + 'spacesBeforeSeparator' => 0, + 'spacesAfterSeparator' => 0, + 'containerClass' => 'paging', + ); + + /** + * SQL query used to obtain the DataGrid + * + * @var unknown + * @access protected + */ + protected $sql; + + /** + * How many records must exist in the Datagrid before the sort form shows up + * + * @var integer + * @access protected + */ + protected $sortableAfter = 10; + + /** + * The HTML table id of the DataGrid + * + * @var string + * @access protected + */ + protected $tableId = 'dataGrid'; + + /** + * The HTML class name of the DataGrid + * + * @var string + * @access protected + */ + protected $tableClass = 'dataGrid'; + + /** + * The HTML id of the DataGrid sorting form (when present) + * + * @var string + * @access protected + */ + protected $sortFormId = 'gridSorter'; + + /** + * Message to display to users if no records were found + * + * @var String + * @access Protected + * @see Toolkit_DataGridBuilder::setNoRecordMessage() + */ + protected $noRecMessage = 'No Records'; + + // }}} + // {{{ __construct() + + /** + * DataGrid constructor + * + * Instantiates a DataGrid and sets up when to make the grid sortable + * + * @param PDO $pdo PDO object used in the datagrid + * @param integer $limit The number of records to display per page. + * @param integer $page The current page view. In most cases, + * this is useless. Note: if you specify + * this, the "page"GET variable will be ignored. + * @param string $rendererType The type of renderer to use. You may + * prefer to use the $type argument of + * render, fill or getOutput. + * + * @return void + * @access public + */ + public function __construct( + PDO $pdo, + $limit = null, + $page = null, + $rendererType = null + ) { + parent::__construct($limit, $page, $rendererType); + + $this->options = array('dbc' => $pdo); + if (!is_null($limit)) { + $this->sortableAfter = $limit; + } + } + + // }}} + + // {{{ configureColumns() + + /** + * configure retrieved columns + * + * Tells the DataGrid how to render the retrieved columns + * + * @return void + * @access protected + */ + abstract protected function configureColumns(); + + // }}} + + // {{{ setNoRecordMessage() + + /** + * The message to display if no results were found from the sql query + * + * @param string $msg No result message. + * + * @return void + * @access public + */ + public function setNoRecordMessage($msg) + { + $this->noRecMessage = $msg; + } + + // }}} + // {{{ setQuery() + + /** + * Sets the sql query to use in the DataGrid to get the results + * + * @param string $sql The SQL query + * + * @return void + * @access public + */ + public function setQuery($sql) + { + $this->sql = $sql; + } + + // }}} + // {{{ show() + + /** + * Displays the DataGrid results + * + * @return void + * @access public + */ + public function show() + { + echo $this->toHTML(); + } + + // }}} + + // {{{ toHTML() + + /** + * returns a HTML table of the datagrid + * + * @return string + * @access public + */ + public function toHTML() + { + $this->configureColumns(); + + try { + $bind = $this->bind($this->sql, $this->options, 'PDO'); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + + if (PEAR::isError($bind)) { + return Toolkit_Common::handleError($bind); + } elseif (($recCount = $this->getRecordCount()) > 0) { + $this->setRendererOptions($this->rendererOptions); + $renderer =& $this->getRenderer(); + // Allows us to turn off the id name for the table, + // when we subclass this class out. + if ($this->tableId) { + $renderer->setTableAttribute('id', $this->tableId); + } + // Allows us to turn off the class name for the table, + // when we subclass this class out. + if ($this->tableClass) { + $renderer->setTableAttribute('class', $this->tableClass); + } + $gridBody = $this->getOutput(); + + if (PEAR::isError($gridBody)) { + return Toolkit_Common::handleError($gridBody); + } + + $gridPager = $this->getOutput( + DATAGRID_RENDER_PAGER, + array('pagerOptions' => $this->pagerOptions) + ); + if (PEAR::isError($gridPager)) { + return Toolkit_Common::handleError($gridPager); + } + + if ($recCount > $this->sortableAfter) { + $form = new Toolkit_SortForm($this->sortFormId); + $options = array('directionStyle' => 'radio'); + $this->fill($form, $options, DATAGRID_RENDER_SORTFORM); + // Datagrid never ads a submit button. + $form->addElement('submit', null, 'Submit'); + $gridSorter = $form->toHTML(); + } + + return $gridPager . $gridSorter . $gridBody . $gridPager; + } else { + return "

    {$this->noRecMessage}

    "; + } + } + + // }}} +} +?> diff --git a/Toolkit/Database.php b/Toolkit/Database.php new file mode 100644 index 0000000..e5229ad --- /dev/null +++ b/Toolkit/Database.php @@ -0,0 +1,123 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Database.php,v 1.1 2009/12/15 20:18:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Database Singleton class + * + * @category Database + * @package Toolkit_Database + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Database +{ + // {{{ properties + + /** + * Database handler object + * + * @var PDO + * @access private + */ + private $_dbh; + + /** + * Class instance + * + * @var Toolkit_Database + * @access private + */ + private static $_instance; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * Make the database handler connection for the class + * + * @access private + */ + private function __construct() + { + 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->_dbh = new PDO($dsn, null, null, $driverOptions); + $this->_dbh->setAttribute( + PDO::ATTR_ERRMODE, + PDO::ERRMODE_EXCEPTION + ); + $this->_dbh->query("SET DATESTYLE TO 'SQL,US'"); + } 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 + } + + // }}} + + // {{{ 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. + * + * @return PDO $_instance database handler instance + * @access public + * @static + */ + public static function getInstance() + { + if (!(self::$_instance instanceof self)) { + self::$_instance = new self(); + } + + return self::$_instance->_dbh; + } + + // }}} +} +?> diff --git a/Toolkit/Events/AddEventForm.php b/Toolkit/Events/AddEventForm.php new file mode 100755 index 0000000..e6570b3 --- /dev/null +++ b/Toolkit/Events/AddEventForm.php @@ -0,0 +1,904 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: AddEventForm.php,v 1.1.1.1 2009/09/17 20:08:57 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * New Event Form + * + * @category Events + * @package Toolkit_Events + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Events_AddEventForm + extends Toolkit_FormBuilder implements Toolkit_Form +{ + // {{{ properties + + /** + * Table in Database which holds the contact data + * + * @var string + * @access public + */ + public $tableName = 'event'; + + /** + * Table meta data + * + * This is used when inserting/updating data for the records + * so the PDO's can use explicit data types for the parameters. + * + * @var array + * @access public + */ + public $tableMetaData; + + /** + * Who to send the email to when the contact form is submitted + * + * If you leave this blank, its value will get set to the OWNER_EMAIL + * in the constructor. + * + * If you ***DO NOT*** want any emails to go out when the form is submitted + * then set the value to false. Do not set it to 0 for false, because the + * check uses a strict type check to determine if the value is actually + * false. This is what allows for the empty value as an option, which sets + * the value to OWNER_EMAIL and won't override the $email property if + * this class gets subclassed and the value for this property gets set in + * the properties of the subclass and not in the constructor after this + * constructor function is called. + * + * tongue twister...I know. + * + * protected $email = false; + * + * + * @var unknown + * @access protected + */ + protected $email; + + /** + * From header in the owner email + * + * This just sets the From header in the owner email + * SITENAME + * + * It gets set to the constant SITENAME in the constructor if you leave + * empty here, but you can set it to something different here to override + * that if you desire. + * + * @var unknown + * @access protected + */ + protected $siteName; + + /** + * Email subject and

    header in email + * + * It gets set in the constructor if you leave empty here, but you + * can set it to something different here to override that if you desire. + * + * @var string + * @access protected + */ + protected $subject = 'New Event Submission'; + + /** + * Message to display if the form is successfully submitted + * + * @var string + * @access protected + */ + protected $successMsg = ' +
    + Thank you! +
    '; + + /** + * Extra rules for processesing + * + * This registers the Zip validation rules (and any others listed) for + * QuickForm. + * + * Zip validation checks both US and Canadian Zip codes + * + * @var array + * @access protected + */ + protected $registeredRules = array( + 'phone', + array( + 'checkEmail', + 'callback', + 'email', + 'Validate' + ), + array( + 'checkURI', + 'callback', + 'uri', + 'Validate' + ) + ); + + /** + * Options for flexy templating engine + * + * Pulls the preset options from the setup.phtml file + * overwrites the templateDir and compileDir to match this classes needs + * + * @var array + * @access protected + */ + protected $flexyOptions; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for
    tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + + // Default Renderer Form templates for QuickForm in respect to this + // classes needs. + $this->template = dirname(__FILE__) . '/templates/currentTables/'; + if ($this->email !== false && empty($this->email)) { + // Set to false to turn off email function. + $this->email = OWNER_EMAIL; + } + if (empty($this->siteName)) { + $this->siteName = SITENAME; + } + if (empty($this->subject)) { + $this->subject = 'Contact Request from website ' . SITENAME; + } + + $this->flexyOptions = $GLOBALS['flexyOptions']; + $this->flexyOptions['templateDir'] = dirname(__FILE__) . "/templates/"; + $this->flexyOptions['compileDir'] = dirname(__FILE__) . "/templates/compiled/"; + + $var = basename(__FILE__, '.php'); + + $callbackUrl = ($_SERVER['HTTPS'] == 'on') ? + BASE_SECURE_URL : BASE_URL; + + $this->captchaOptions = array( + 'width' => 100, + 'height' => 50, + 'callback' => "{$callbackUrl}Toolkit/qfcaptcha.php?var=$var", + 'sessionVar' => $var, + 'imageOptions' => array( + 'font_size' => 16, + 'font_path' => GLM_APP_BASE . 'glmPEAR/Image/Canvas/Fonts/', + 'font_file' => 'times.ttf', + 'background_color' => '#cccccc', + 'obfuscation' => false, + 'angle' => true, + ), + ); + } + + // }}} + + // {{{ checkDate() + + /** + * Validate date input + * + * allows for empty dates to be valid + * + * @param array $date date group from form + * + * @return boolean true if valid, false if not + * @access public + */ + public function checkDate($date) + { + $validate = false; + foreach ($date as $i) { + if (is_numeric($i)) { + $validate = true; + break; + } + } + + if ($validate) { + // at least on date list had a number in it. + $d = implode('-', $date); + return Validate::date($d, array('format' =>'%n-%j-%Y')); + } else { + // no date numbers were selected + return true; + } + } + + // }}} + // {{{ checkDateRange() + + /** + * Validate date input + * + * allows for empty end date to be valid + * + * @param array $d date group from form + * + * @return boolean true if valid, false if not + * @access public + */ + public function checkDateRange(array $d) + { + if (!$this->hasEndDate($d[1])) { + // no end date is a valid date range + return true; + } + + $t1 = mktime(0, 0, 0, $d[0]['m'], $d[0]['d'], $d[0]['Y']); + $bdate = new Date($t1); + $t2 = mktime(0, 0, 0, $d[1]['m'], $d[1]['d'], $d[1]['Y']); + $edate = new Date($t2); + + // 0 if the dates are equal - valid + // -1 if $bdate is before $edate - valid + // 1 if $bdate is after $edate - invalid + $res = Date::compare($bdate, $edate); + return ($res !== 1); + } + + // }}} + // {{{ 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' => 'text', + 'req' => true, + 'name' => 'header', + 'display' => 'Event Name' + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'bdate', + 'display' => 'Start Date', + 'opts' => array( + 'format' => 'm / d / Y', + 'minYear' => date('Y'), + 'maxYear' => date('Y') + 5, + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy' + ), + ), + 'att' => array('class' =>'sdate'), + ); + $e[] = array( + 'type' => 'date', + 'req' => false, + 'name' => 'edate', + 'display' => 'End Date', + 'opts' => array( + 'format' => 'm / d / Y', + 'minYear' => date('Y'), + 'maxYear' => date('Y') + 5, + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy' + ), + ), + 'att' => array('id' =>'edate'), + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'btime', + 'display' => 'Start Time', + 'opts' => array( + 'format' => 'h : i A', + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'h' => 'hh', + 'i' => 'mm', + 'A' => 'am/pm' + ), + 'optionIncrement' => array( + 'i' => 15, + ), + ), + 'error' => 'ERROR: You must select a start time!', + ); + $e[] = array( + 'type' => 'date', + 'req' => false, + 'name' => 'etime', + 'display' => 'End Time', + 'opts' => array( + 'format' => 'h : i A', + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'h' => 'hh', + 'i' => 'mm', + 'A' => 'am/pm' + ), + 'optionIncrement' => array( + 'i' => 15, + ), + ), + ); + $e[] = array( + 'type' => 'select', + 'req' => true, + 'name' => 'topicid', + 'display' => 'Topic', + 'opts' => $this->getTopicFields(), + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'loc', + 'display' => 'Location' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'url', + 'display' => 'Website' + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'descr', + 'display' => 'Description' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'contact', + 'display' => 'Contact Person' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Contact Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'phone', + 'display' => 'Contact Phone' + ); + if ($this->useCaptcha) { + $e[] = array( + 'type' => 'CAPTCHA_Image', + 'req' => false, + 'name' => 'captcha_question', + 'display' => 'Verification code', + 'opts' => $this->captchaOptions + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'captcha_rmv', + 'display' => 'Enter verification code', + ); + } + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit_rmv', + 'display' => 'Submit' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureFilters() + + /** + * Form filter definitions + * + * Applies a data filter for the given fields when the form is submitted + * + * @return void + * @access public + */ + public function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Helper function to handle setting up the form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @return void + * @access public + */ + public function configureRules() + { + // Form Rules + $r[] = array( + 'element' => 'topicid', + 'message' => 'ERROR: Invalid Topic!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'email', + 'message' => 'ERROR: Invalid Email Format!', + 'type' => 'checkEmail', + 'format' => array('use_rfc822' => true), + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => array('bdate', 'edate'), + 'message' => 'ERROR: Starting Date must be before Ending Date', + 'type' => 'callback', + 'format' => array(&$this, 'checkDateRange'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'bdate', + 'message' => 'ERROR: Invalid date!', + 'type' => 'callback', + 'format' => array(&$this, 'checkDate'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'edate', + 'message' => 'ERROR: Invalid date!', + 'type' => 'callback', + 'format' => array(&$this, 'checkDate'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'url', + 'message' => 'ERROR: Please include full address! ('.BASE_URL.')', + 'type' => 'checkURI', + 'format' => array( + 'allowed_schemes' => array('http', 'https'), + 'strict' => true + ), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'phone', + 'message' => 'ERROR: Invalid Phone Format (xxx) xxx - xxxx!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + if ($this->useCaptcha) { + $r[] = array( + 'element' => 'captcha_rmv', + 'message' => 'ERROR: What you entered didn\'t match!', + 'type' => 'CAPTCHA', + 'format' => $this->captchaQuestion, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + } + + $this->setupRules($r); + } + + // }}} + + // {{{ getTopicFields() + + /** + * get event topics + * + * @return array topics + * @access protected + */ + protected function getTopicFields() + { + try { + $sql = " + SELECT * + FROM topic + ORDER BY descr"; + + $topics = array('' => '-- Select --'); + foreach ($this->dbh->query($sql) as $row) { + $topics[$row['id']] = $row['descr']; + } + + return $topics; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ hasEndDate() + + /** + * verifies if we have a valid end date to work with + * + * @param array $d end date + * + * @return boolean if the end date is + */ + protected function hasEndDate(array $d) + { + return checkdate((int) $d['m'], (int) $d['d'], (int) $d['Y']); + } + + // }}} + + // {{{ emailOwner() + + /** + * Emails the owner the submitted data from the submitted form + * + * Uses a flexy template to render a nice looking html email. + * Fills in the supplied data from the form and doesn't add the + * empty fields the user didn't fill in. + * + * @return boolean result of the mailing + * @access protected + */ + protected function emailOwner() + { + if (!$this->email) { + return; + } + + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + // for comments textarea need to replace newlines with br + $this->formData['comments']['element'] = nl2br($this->getSubmitValue('comments')); + + // these values are required, therefor will always be part of + // the formData array + $bdate = explode('/', $this->formData['bdate']['element']); + $foo = array_map('trim', $bdate); + $this->formatValue($foo, '%02d/%02d/%d'); + $this->formData['bdate']['element'] = $foo; + + $btime = explode('/', $this->formData['btime']['element']); + $foo = array_map('trim', $btime); + $this->formatValue($foo, '%02d:%02d %s'); + $this->formData['btime']['element'] = $foo; + + // not required, so check to make sure it exists before trying + // to format the value + if (isset($this->formData['edate'])) { + $edate = explode('/', $this->formData['edate']['element']); + $foo = array_map('trim', $edate); + $this->formatValue($foo, '%02d/%02d/%d'); + $this->formData['edate']['element'] = $foo; + } + if (isset($this->formData['etime'])) { + $etime = explode('/', $this->formData['etime']['element']); + $foo = array_map('trim', $etime); + $this->formatValue($foo, '%02d:%02d %s'); + $this->formData['btime']['element'] = $foo; + } + + try { + $sql = " + SELECT descr + FROM topic + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam( + ':id', + $this->formData['topicid']['element'], + PDO::PARAM_INT + ); + $stmt->execute(); + $stmt->bindColumn('descr', $this->formData['topicid']['element']); + $stmt->fetch(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + + $page->email_from = FROM_NEWS_EMAIL; + $page->subject = $this->subject; + $page->formData = $this->formData; + $page->eventAdminURL = BASE_URL.'admin/Events/list_events.phtml?pending=t'; + + $template->compile('emailOwner.tpl'); + $htmlMsg = $template->bufferedOutputObject($page); + + // Text version can't have HTML in it + $msg = "{$page->subject}\n\n"; + $msg .= "From {$page->fname} {$page->lname}\n\n"; + $msg .= "Information\n\n"; + foreach ($page->formData as $i) { + $msg .= "{$i['label']}: {$i['element']}\n"; + } + + $crlf = "\n"; + $mimeMail = new Mail_mime($crlf); + $mimeMail->setFrom("{$this->siteName} <{$page->email_from}>"); + $mimeMail->setSubject($this->subject); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $mail =& Mail::factory('mail'); + $body = $mimeMail->get(); + $headers = $mimeMail->headers(); + + $res = $mail->send($this->email, $headers, $body); + if (PEAR::isError($res)) { + return Toolkit_Common::handleError($res); + } else { + return $res; + } + } + + // }}} + + // {{{ formatValue() + + /** + * Format an array into an acceptable string + * + * @param mixed &$i array values to format or null value for + * element that was not filled in + * @param string $format string to format values into + * + * @return string formatted string + * @access public + */ + public function formatValue(&$i, $format) + { + // Allow for 0 to be not empty. This allows for minutes in the + // time arrays to be valid if they are on the hour ie. (1:00 pm) + $notEmpty = create_function('$v', 'return strlen($v) > 0;'); + if (is_array($i) && count(array_filter($i, $notEmpty)) == 3) { + list($x, $y, $z) = array_values($i); + eval("\$i = sprintf('$format', $x, $y, $z);"); + } else { + $i = null; + } + } + + // }}} + + // {{{ insertData() + + /** + * Inserts contact data into the contact db + * + * @param array $values submitted values + * + * @return object result of db insert query + * @access protected + */ + protected function insertData($values) + { + try { + // need to set the dates up first + $this->formatValue($values['bdate'], '%02d/%02d/%d'); + $this->formatValue($values['edate'], '%02d/%02d/%d'); + $this->formatValue($values['btime'], '%02d:%02d %s'); + $this->formatValue($values['etime'], '%02d:%02d %s'); + + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ processData() + + /** + * Handles how to process the form when submitted + * + * @param array $values Form submitted values + * + * @return array Result of Insert / Update function + * @access protected + */ + public function processData($values) + { + // Form data used for the insert/update sql queries and + // the form email. + $e = array(); + $this->setFormData($e); + + // Get rid of any defined un-needed elements. + // un-needed elements after the form is submitted are defined + // by the ending _rmv name. + foreach ($values as $k => &$v) { + if (preg_match('/^.+_rmv$/', $k)) { + unset($values[$k]); + } + } + + return $this->insertData($values); + } + + // }}} + + // {{{ setupRenderers() + + /** + * Custom rendering templates for special fields on the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + $required = '*'; + $error = '
    {error}
    '; + + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'descr'); + $renderer->setElementTemplate(''.$required.'{label}'.$error.'{element}', 'submit_rmv'); + + if ($this->useCaptcha) { + $renderer->setElementTemplate('{element}', 'captcha_question'); + $renderer->setElementTemplate(''.$required.''.$error.'{element}What is this?', 'captcha_rmv'); + } + } + + // }}} + + // {{{ toHtml() + + /** + * Handles how to display the current step the user is at in the form + * + * destroying and resetting the captcha value dis-allows someone from + * re-sending a form on a previous captcha. + * + * @return string form HTML state + * @access public + */ + public function toHtml() + { + $this->setupRenderers(); + if ($this->validate()) { + //$this->captchaQuestion->destroy(); + $this->cleanForm(); + + if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) { + $this->freeze(); + $this->emailOwner(); + $output = $this->successMsg; + } + $this->sent = true; + } elseif ($this->isSubmitted()) { + if ($this->useCaptcha) { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + } + $output = $this->errorMsg; + $output .= parent::toHtml(); + } else { + if ($this->useCaptcha) { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + } + $output = parent::toHtml(); + } + return $output; + } + + // }}} +} +?> diff --git a/Toolkit/Events/events.sql b/Toolkit/Events/events.sql new file mode 100644 index 0000000..21a4f18 --- /dev/null +++ b/Toolkit/Events/events.sql @@ -0,0 +1,33 @@ +CREATE TABLE event ( +id SERIAL PRIMARY KEY, +topicid INTEGER DEFAULT 0, +bdate DATE, +edate DATE, +loc TEXT, +header TEXT, +descr TEXT, +img TEXT, +url TEXT, +contact TEXT, +phone TEXT, +email TEXT, +btime TEXT, +etime TEXT, +visable BOOLEAN DEFAULT false, +home BOOLEAN DEFAULT false, +ds timestamp, +daysow INTEGER, +dayom INTEGER, +reacur BOOLEAN DEFAULT false, +weekom TEXT, +all_day BOOLEAN DEFAULT false, +file TEXT, +filename TEXT, +member_id INTEGER REFERENCES member (member_id) ON DELETE CASCADE +); + +CREATE TABLE topic ( +id SERIAL PRIMARY KEY, +descr TEXT, +topiccolor TEXT +); diff --git a/Toolkit/Events/templates/currentTables/Element.tpl b/Toolkit/Events/templates/currentTables/Element.tpl new file mode 100755 index 0000000..595457b --- /dev/null +++ b/Toolkit/Events/templates/currentTables/Element.tpl @@ -0,0 +1,14 @@ + + + + * + + + + + +
    {error}
    + + {element} + + diff --git a/Toolkit/Events/templates/currentTables/Form.tpl b/Toolkit/Events/templates/currentTables/Form.tpl new file mode 100755 index 0000000..f59286a --- /dev/null +++ b/Toolkit/Events/templates/currentTables/Form.tpl @@ -0,0 +1,7 @@ +
    + + + {content} +
    + +
    diff --git a/Toolkit/Events/templates/currentTables/Group.tpl b/Toolkit/Events/templates/currentTables/Group.tpl new file mode 100755 index 0000000..cdd24cf --- /dev/null +++ b/Toolkit/Events/templates/currentTables/Group.tpl @@ -0,0 +1,5 @@ + + + {content} + +
    diff --git a/Toolkit/Events/templates/currentTables/GroupElement.tpl b/Toolkit/Events/templates/currentTables/GroupElement.tpl new file mode 100755 index 0000000..1a4ba27 --- /dev/null +++ b/Toolkit/Events/templates/currentTables/GroupElement.tpl @@ -0,0 +1,9 @@ + + + {element} + + * + + {label} + + diff --git a/Toolkit/Events/templates/currentTables/Header.tpl b/Toolkit/Events/templates/currentTables/Header.tpl new file mode 100755 index 0000000..64ac244 --- /dev/null +++ b/Toolkit/Events/templates/currentTables/Header.tpl @@ -0,0 +1,5 @@ + + + {header} + + diff --git a/Toolkit/Events/templates/currentTables/RequiredNote.tpl b/Toolkit/Events/templates/currentTables/RequiredNote.tpl new file mode 100755 index 0000000..dad5d0b --- /dev/null +++ b/Toolkit/Events/templates/currentTables/RequiredNote.tpl @@ -0,0 +1 @@ +* = Required Fields diff --git a/Toolkit/Events/templates/emailOwner.tpl b/Toolkit/Events/templates/emailOwner.tpl new file mode 100755 index 0000000..d7d8d76 --- /dev/null +++ b/Toolkit/Events/templates/emailOwner.tpl @@ -0,0 +1,29 @@ + + + + + {title:h} + + + +

    {subject:h}

    +

    Information

    + + + + + {if:v[nowrap]} + + {else:} + + {end:} + + +
    {v[label]:h}{v[element]:h}{v[element]:h}
    +

    A new Event Record has been created from "Add Your Event"

    +

    The record needs to be approved before changes go live.

    +

    Goto Pending Records to View and Approve their changes.

    + + diff --git a/Toolkit/FileServer/AdapterAbstract.php b/Toolkit/FileServer/AdapterAbstract.php new file mode 100644 index 0000000..92494cc --- /dev/null +++ b/Toolkit/FileServer/AdapterAbstract.php @@ -0,0 +1,401 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: AdapterAbstract.php,v 1.1 2012/02/03 19:04:13 matrix 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 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)... + */ +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) + { + $ch = curl_init(); + + $fileData = array( + 'request' => $this->buildFileServerXML($name, 'Delete') + ); + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + try { + $xmlDoc = new DOMDocument; + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $successCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + + if ($successCode != 0) { + throw new RangeException( + "Invalid response `$response` - `$message`" + ); + } + + return $message; + } catch (RangeException $e) { + Toolkit_Logger::logException('Image Server', $e); + throw new Toolkit_FileServer_Exception( + 'Invalid File Server Response' + ); + } + } + + // }}} + + // {{{ getFileElement() + + + /** + * Gets the file element used in the XML sent to the file server + * + * @param DOMDocument $xml DOM object used to build the xml string + * @param string $type Type of manipulation (Upload, URL, Delete) + * @param string $fName File name + * + * @return DOMElement $file File xml element + * @access protected + */ + abstract protected function getFileElement( + DOMDocument $xml, + $type, + $fName + ); + + // }}} + // {{{ getErrorMessage() + + /** + * Gets an appropriate error message for file upload errors + * + * @param integer Error code + * + * @return string Error message + * @access protected + */ + protected function getErrorMessage($code) + { + switch ($code) { + case UPLOAD_ERR_INI_SIZE : + $message = 'The Uploaded file exceeds the upload max filesize directive in php.ini'; + break; + + case UPLOAD_ERR_FORM_SIZE : + $message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'; + break; + + case UPLOAD_ERR_PARTIAL : + $message = 'The uploaded file was only partially uploaded'; + break; + + case UPLOAD_ERR_NO_FILE : + $message = 'No file was uploaded'; + break; + + case UPLOAD_ERR_NO_TMP_DIR : + $message = 'Missing a temporary folder'; + break; + + case UPLOAD_ERR_CANT_WRITE : + $message = 'Failed to write file to disk'; + break; + + case UPLOAD_ERR_EXTENSION : + $message = 'A PHP extension stopped the file upload'; + break; + + default : + $message = 'Unknown error uploading file'; + break; + } + + return $message; + } + + // }}} + + // {{{ upload() + + /** + * Upload a file to the File Server + * + * @param string $name $_FILES index key that holds the file data + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function upload($name) + { + $fileType = null; + if (preg_match('/^http/', $name)) { + $fileType = 'URL'; + } elseif (isset($_FILES[$name]) && is_array($_FILES[$name])) { + $fileType = 'Upload'; + } + + if ($_FILES[$name]['error'] != 0) { + $message = $this->getErrorMessage($_FILES[$name]['error']); + throw new Toolkit_FileServer_Exception( + $message, + $_FILES[$name]['error'] + ); + } + + if (is_null($fileType)) { + return false; + } else { + $request = $this->buildFileServerXML($name, $fileType); + + $ch = curl_init(); + if ($fileType == 'URL') { + $fileData = array( + 'request' => $request + ); + } else { + $fileData = array( + 'request' => $request, + 'file_upload' => "@{$_FILES[$name]['tmp_name']}", + 'file_upload_name' => $_FILES[$name]['name'] + ); + } + + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + try { + $xmlDoc = new DOMDocument(); + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $successCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $storedName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $storedSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $mediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + + if ($successCode != 0) { + throw new RangeException( + "Invalid response `$response` - `$message`" + ); + } + + $extension = end(explode('.', $storedName)); + return array( + 'name' => $storedName, + 'size' => $storedSize, + 'type' => $mediaType, + 'extension' => $extension, + ); + } catch (RangeException $e) { + Toolkit_Logger::logException('Image Server', $e); + throw new Toolkit_FileServer_Exception( + 'Invalid File Server Response' + ); + } + } + } + + // }}} + + // {{{ xmlPathContent() + + /** + * Extract a XML node value + * + * @param DOMDocument $dom DOM object holding the XML + * @param string $content Node name to extract content from + * + * @return mixed Node value on success, false if can't find the value + * @access protected + */ + protected function xmlPathContent(DOMDocument $dom, $content) + { + $xPath = new DOMXPath($dom); + $nodeList = $xPath->query($content); + if ($nodeList->length > 0) { + $node = $nodeList->item(0); + return $node->nodeValue; + } + + return false; + } + + // }}} +} diff --git a/Toolkit/FileServer/Exception.php b/Toolkit/FileServer/Exception.php new file mode 100644 index 0000000..8739c0f --- /dev/null +++ b/Toolkit/FileServer/Exception.php @@ -0,0 +1,5 @@ + diff --git a/Toolkit/FileServer/FileAdapter.php b/Toolkit/FileServer/FileAdapter.php new file mode 100644 index 0000000..14ea220 --- /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.1 2012/02/03 19:04:13 matrix 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 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_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..0d31fab --- /dev/null +++ b/Toolkit/FileServer/ImageAdapter.php @@ -0,0 +1,248 @@ + + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version CVS: $Id: ImageAdapter.php,v 1.1 2012/02/03 19:04:13 matrix 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 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_ImageAdapter extends Toolkit_FileServer_AdapterAbstract +{ + // {{{ getAllowedMimeTypes() + + /** + * Get the mime types that are allowed to be uploaded + * + * @return array allowed mime types + */ + public function getAllowedMimeTypes() + { + return array( + 'image/jpe', + 'image/jpeg', + 'image/jpg', + 'image/jfif', + 'image/pjpeg', + 'image/pjp', + 'image/gif', + 'image/gif', + 'image/png', + ); + } + + // }}} + // {{{ getFileElement() + + /** + * Creates the file element for the XML string + * + * @param DOMDocument $xml XML object used to build the string + * @param string $type Type of action to take on the file (Upload, Delete) + * @param string $fName file name to delete + * + * @return DOMElement $file File xml element + * @access protected + * @throws RuntimeException + */ + protected function getFileElement(DOMDocument $xml, $type, $fName) + { + $file = $xml->createElement('File'); + + switch ($type) { + case 'Upload' : + $action = $xml->createElement('FileAction', 'Submit'); + $delivery = $xml->createElement('DeliveryMethod', 'Submit'); + $fieldName = $xml->createElement('FieldName', 'file_upload'); + + $file->appendChild($action); + $file->appendChild($delivery); + $file->appendChild($fieldName); + break; + + case 'URL': + $action = $xml->createElement('FileAction', 'Submit'); + $delivery = $xml->createElement('DeliveryMethod', 'URL'); + $src = $xml->createElement('Src', $fName); + + $file->appendChild($action); + $file->appendChild($delivery); + $file->appendChild($src); + break; + + case 'Delete': + $action = $xml->createElement('FileAction', 'Delete'); + $file->appendChild($action); + + $fileName = $xml->createElement('FileName', $fName); + $file->appendChild($fileName); + break; + + default : + throw new RuntimeException("Invalid XML type - `$type`."); + break; + } + + return $file; + } + + // }}} + // {{{ getImageSize() + + /** + * getImageSize + * + * Return image data on an image from image server + * + * @param string $image Full URI to image + * http://is0/userId/imageStyle/imageName + * Must be a full URI including an authority. + * No relative URIs, the // are mandatory + * + * @return array Image data 0 => width, 1 => height, 2 => html + * @access public + * @throws Exception + */ + public function getImageSize($image) + { + $options = array('allowed_schemes' => array('http','https')); + if (!Validate::uri($image, $options)) { + throw new Exception('Invalid URI for the image'); + } + + $ch = curl_init(); + $curlOptions = array( + CURLOPT_URL => "{$image}/info", + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + if (!@simplexml_load_string($response)) { + $logger = Toolkit_Logger::getLogger(); + $logger->warning("$response - $image"); + } + + $wPattern = '/(.*)<\/width>/'; + preg_match($wPattern, $response, $matches); + $width = $matches[1]; + $hPattern = '/(.*)<\/height>/'; + preg_match($hPattern, $response, $matches); + $height = $matches[1]; + $html = "width=\"{$width}\" height=\"{$height}\""; + return array($width, $height, $html); + } + + // }}} + // {{{ uploadImageFile() + + /** + * Upload a file to the File Server + * + * @param string $fname full path to image file + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function uploadImageFile($fname) + { + if (!file_exists($fname)) { + throw new RuntimeException("could not find file `$fname`"); + } + + $request = $this->buildFileServerXML(basename($fname), 'Upload'); + + $ch = curl_init(); + $fileData = array( + 'request' => $request, + 'file_upload' => "@$fname", + 'file_upload_name' => basename($fname) + ); + + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + + try { + $xmlDoc = new DOMDocument(); + $response = str_replace('', '', $response); + $xmlDoc->loadXML($response); + $successCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $storedName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $storedSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $mediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + + if ($successCode != 0) { + throw new RangeException( + "Invalid response `$response` - `$message`" + ); + } + + return array( + 'name' => $storedName, + 'size' => $storedSize, + 'type' => $mediaType, + ); + } catch (RangeException $e) { + Toolkit_Logger::logException('Image Server', $e); + throw new Toolkit_FileServer_Exception( + 'Invalid File Server Response' + ); + } + } + + // }}} +} +?> diff --git a/Toolkit/FileServer/Mock/ImageAdapter.php b/Toolkit/FileServer/Mock/ImageAdapter.php new file mode 100644 index 0000000..9479eef --- /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 2012/02/03 19:04:13 matrix Exp $ + * @link <> + * @see References to other sections (if any)... + */ + +/** + * Mock Image Adapter + * + * Mocks uploading and deleting images from the image server + * This script prevents unneeded resources from being uploaded + * or deleted from the file server + * + * @category FileServer + * @package Toolkit_FileServer + * @author Jamie Kahgee + * @copyright 2010 Jamie Kahgee + * @license http://www.gaslightmedia.com/ Gaslightmedia + * @version Release: @package_version@ + * @link <> + * @see References to other sections (if any)... + */ +class Toolkit_FileServer_Mock_ImageAdapter + extends Toolkit_FileServer_ImageAdapter +{ + // {{{ getImageSize() + + /** + * getImageSize + * + * Return image data on an image from image server + * + * @param string $image Full URI to image + * http://is0/userId/imageStyle/imageName + * Must be a full URI including an authority. + * No relative URIs, the // are mandatory + * + * @return array Image data 0 => width, 1 => height, 2 => html + * @access public + * @throws Exception + */ + public function getImageSize($image) + { + $width = $height = 1; + $html = "width=\"{$width}\" height=\"{$height}\""; + return array($width, $height, $html); + } + + // }}} + // {{{ uploadImageFile() + + /** + * Upload a file to the File Server + * + * @param string $fname full path to image file + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function uploadImageFile($fname) + { + return array( + 'name' => 'is00-mock-image.jpg', + 'size' => 100, + 'type' => 'image/jpeg', + ); + } + + // }}} + // {{{ upload() + + /** + * Upload a file to the File Server + * + * @param string $name $_FILES index key that holds the file data + * + * @return array Uploaded file data + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function upload($name) + { + return array( + 'name' => 'is00-mock-image.jpg', + 'size' => 100, + 'type' => 'image/jpeg', + ); + } + + // }}} + // {{{ delete() + + /** + * Delete a file from the file server + * + * @param string $name File name + * + * @return string file name + * @access public + * @throws Toolkit_FileServer_Exception + */ + public function delete($name) + { + return true; + } + + // }}} +} +?> diff --git a/Toolkit/FlexyDataGridBuilder.php b/Toolkit/FlexyDataGridBuilder.php new file mode 100644 index 0000000..4127582 --- /dev/null +++ b/Toolkit/FlexyDataGridBuilder.php @@ -0,0 +1,207 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: FlexyDataGridBuilder.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link <> + */ + +/** + * Create Flexy templating Datagrids for displaying data + * + * This abstract class handles all the base functionality of creating + * handeling all the details associated w/ a Flexy template datagrid + * 1. Creation + * 2. Sorting (via column headers or sortform) + * 3. Pagenation + * + * @category Structures + * @package Toolkit_FlexyDataGridBuilder + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com/Gaslightmedia Gaslightmedia + * @link http://pear.php.net/package/Structures_DataGrid/docs + * @see Structures_DataGrid_Renderer_Flexy, HTML_Template_Flexy + */ +abstract class Toolkit_FlexyDataGridBuilder extends Toolkit_DataGridBuilder +{ + // {{{ properties + + /** + * Name of the table which we will be dealing with + * + * @var string + * @access protected + */ + protected $tableName; + + /** + * The name of the template that renders this datagrid + * + * @var string + * @access protected + */ + protected $template; + + /** + * Output an object as $t to the template + * + * converts array keys to objects usable in a template form. + * + * + * $this->ctrlObj['url'] = BASE_URL; + * + * + * + * {row[img]} src= + * + * + * @var array + * @access protected + */ + protected $ctrlObj = array(); + + /** + * Rendering options for DataGrid + * + * @var array + * @access protected + */ + protected $rendererOptions = array( + 'sortIconASC' => '⇑', + 'sortIconDESC' => '⇓', + 'sortingResetsPaging' => false, + ); + + /** + * The HTML id of the DataGrid + * + * @var string + * @access protected + */ + protected $gridId = 'dataGrid'; + + /** + * The HTML class of the DataGrid + * + * @var string + * @access protected + */ + protected $gridClass = 'dataGrid'; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * Builds the DataGrid class. + * + * @param PDO $pdo PDO object used in the datagrid + * @param integer $limit The number of records to display per page. + * @param integer $page The current page view. In most cases, + * this is useless. Note: if you specify + * this, the "page"GET variable will be ignored. + * @param string $rendererType The type of renderer to use. You may + * prefer to use the $type argument of + * render, fill or getOutput. + * + * @return void + * @access public + */ + public function __construct( + PDO $pdo, + $limit = null, + $page = null, + $rendererType = null + ) { + $this->dbh = $pdo; + if (ctype_digit($_GET['setPerPage'])) { + $limit = $_GET['setPerPage']; + } + + parent::__construct($pdo, $limit, $page, $rendererType); + + // If all records show on one page, then hide sort form. + if (!is_null($limit)) { + $this->sortableAfter = $limit; + } + } + + // }}} + + // {{{ show() + + /** + * Displays the DataGrid results + * + * @param Structures_DataGrid_Renderer_Flexy $renderer Rendering engine used to render DG + * + * @return void + * @access public + */ + public function show(Structures_DataGrid_Renderer_Flexy $renderer) + { + echo $this->toHtml($renderer); + } + + // }}} + + // {{{ toHtml() + + /** + * Returns the DataGrid + * + * @param Structures_DataGrid_Renderer_Flexy $renderer Rendering engine used to render DG + * + * @return string html templated datagrid results + * @access public + */ + public function toHtml(Structures_DataGrid_Renderer_Flexy $renderer) + { + $this->configureColumns(); + + try { + $bind = $this->bind($this->sql, $this->options, 'PDO'); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + + if (PEAR::isError($bind)) { + return Toolkit_Common::handleError($bind); + } + + if (method_exists($this, 'setControlObject')) { + $this->setControlObject(); + foreach ($this->ctrlObj as $k => $v) { + $renderer->$k = $v; + } + } + + $renderer->setOptions($this->rendererOptions); + $renderer->setOptions(array('pagerOptions' => $this->pagerOptions)); + + $this->attachRenderer($renderer); + $tpl = $renderer->getContainer(); + $tpl->compile($this->template); + + // Get the entire datagrid body. + $gridBody = $this->getOutput(); + if (PEAR::isError($gridBody)) { + return Tolkit_Common::handleError($gridBody); + } + + return $gridSorter . $gridBody; + } + + // }}} +} +?> diff --git a/Toolkit/Form.php b/Toolkit/Form.php new file mode 100644 index 0000000..e5c0238 --- /dev/null +++ b/Toolkit/Form.php @@ -0,0 +1,144 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Form.php,v 1.1.1.1 2009/09/17 20:08:55 matrix 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 Form + * @package Toolkit_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..3f51aad --- /dev/null +++ b/Toolkit/FormBuilder.php @@ -0,0 +1,1183 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: FormBuilder.php,v 1.2 2009/12/15 20:18:15 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 Forms + * @package Toolkit_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 + + /** + * 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'; + + /** + * 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 . 'templates/forms/'; + $this->dbh = Toolkit_Database::getInstance(); + } + + // }}} + // {{{ __destruct() + + /** + * Destructor + * + * @return void + * @access public + * @todo remove the need to unset any dbh's, they should be passed in + * via parameters if they are needed. + */ + public function __destruct() + { + } + + // }}} + + // {{{ 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); + + } + + // }}} + + // {{{ 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)) { + 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') { + $r[$i['name']][] = array( + 'ERROR: 100 characters max!', + 'maxlength' + ); + } elseif ($i['type'] == 'textarea') { + $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()) + { + 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); + $renderer =& $this->defaultRenderer(); + 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); + } + } + } + + // }}} + // {{{ setUseCaptcha() + + /** + * 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->useCaptcha = $useCaptcha; + } + + // }}} + // {{{ show() + + /** + * Shows the form + * + * @return void + * @access public + */ + public function show() + { + Toolkit_Common::show(); + } + + // }}} +} +?> diff --git a/Toolkit/Image/Server.php b/Toolkit/Image/Server.php new file mode 100755 index 0000000..fc562ff --- /dev/null +++ b/Toolkit/Image/Server.php @@ -0,0 +1,369 @@ + + * @copyright 2008 Steve Sutton + * @license Gaslight Media + * @version CVS: $Id: Server.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Description for define + */ +define('IS_VALIDATE_SECRET', 'Glm0IS1secreT'); + +/** + * Description for define + */ +define('IS_SUBMIT_URL', 'is0.gaslightmedia.com/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 Images + * @package Toolkit_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) + { + if ($name) { + $request = $this->buildImageServerXML($name, 'Delete'); + $ch = curl_init(); + $fileData = array( + 'request' => $request + ); + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + $xmlDoc = new DOMDocument; + $response = str_replace("", "", $response); + $xmlDoc->loadXML($response); + $SuccessCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $Message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $Owner = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/Owner' + ); + $StoredName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $StoredSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $MediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + return $Message; + } + } + + // }}} + // {{{ imageUpload() + + /** + * imageUpload + * + * Upload image to server + * + * @param string $name Form field name of image + * + * @return string Image name + * @access public + */ + function imageUpload($name) + { + $fileType = null; + if (preg_match("/^http/", $name)) { + $fileType = 'URL'; + } elseif (is_array($_FILES[$name])) { + $fileType = 'Upload'; + } + if ($fileType) { + $request = $this->buildImageServerXML($name, $fileType); + $ch = curl_init(); + if ($fileType == "URL") { + $fileData = array( + 'request' => $request + ); + } else { + $fileData = array( + 'request' => $request, + 'file_upload' => '@'.$_FILES[$name]['tmp_name'], + 'file_upload_name' => $_FILES[$name]['name'] + ); + } + $curlOptions = array( + CURLOPT_URL => IS_SUBMIT_URL, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_POSTFIELDS => $fileData + ); + curl_setopt_array($ch, $curlOptions); + + $response = curl_exec($ch); + curl_close($ch); + $xmlDoc = new DOMDocument; + $response = str_replace("", "", $response); + $xmlDoc->loadXML($response); + $SuccessCode = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/SuccessCode' + ); + $Message = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/ReplyStatus/Message' + ); + $Owner = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/Owner' + ); + $StoredName = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredName' + ); + $StoredSize = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/StoredSize' + ); + $MediaType = $this->xmlPathContent( + $xmlDoc, + '/FileServerResponse/File/MediaType' + ); + if ($SuccessCode != 0) { + echo '
    '.print_r($response, true).'
    '; + return false; + 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')); + if (!Validate::uri($image, $options)) { + return PEAR::raiseError('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); + $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..a5835c4 --- /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.1 2012/02/03 19:04:26 matrix 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/Members.php b/Toolkit/Members.php new file mode 100644 index 0000000..5ef8da4 --- /dev/null +++ b/Toolkit/Members.php @@ -0,0 +1,281 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Members.php,v 1.2 2009/12/15 20:18:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Base class for the memberdb + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members +{ + // {{{ __construct() + + /** + * Constructor + * + * @access public + */ + public function __construct() + { + HTTP_Session2::useCookies(false); + HTTP_Session2::start('MemberDB'); + if (HTTP_Session2::get('newSearch')) { + HTTP_Session2::set('newSearch', false); + HTTP_Session2::set('searchResults', $_SERVER['HTTP_REFERER']); + } + } + + // }}} + + // {{{ toHtml() + + /** + * Determine which form to show to the user + * + * When editing a member the (a)ction in the URL controls + * which form is displayed to the user. Member Id's from + * the database should be passed along as the ID in the $_GET array. + * + * @return void + * @access public + */ + public function toHtml() + { + $pdo = Toolkit_Database::getInstance(); + // application configuration + $conf = new Config; + $root =& $conf->parseConfig(BASE . 'Toolkit/Members/members.ini', 'IniFile'); + + $nav =& new Toolkit_Members_RecordNavigation($root); + $nav->setupAdminNavStructure(); + + $tplOpts = Toolkit_Members::getFlexyOptions(); + $tEngine = new HTML_Template_Flexy($tplOpts); + + switch ($_GET['tab']) { + case 6 : + $mc =& new Toolkit_Members_EditMemberContacts( + Toolkit_Database::getInstance(), + 'edit_contacts', + 'post', + null, + null, + null, + true + ); + if ($_GET['d'] == 't' && is_numeric($_GET['cid'])) { + $mc->removeContact($_GET['cid'], $_GET['id']); + } + $mc->setConfig($root); + $mc->configureForm(); + $out = $mc->toHtml(); + break; + + case 5 : + $mf =& new Toolkit_Members_EditMemberFile( + $pdo, + 'edit_files' + ); + $mf->setConfig($root); + $mf->configureForm(); + $out = $mf->toHtml(); + break; + + case 4 : + $ma =& new Toolkit_Members_EditMemberAmenities( + $pdo, + 'edit_amenities', + 'post', + null, + null, + null, + true + ); + $ma->setConfig($root); + $ma->configureForm(); + $out = $ma->toHtml(); + break; + + case 3 : + $mp = new Toolkit_Members_Admin_EditPackages( + $pdo, + $tEngine + ); + $mp->setupPage(); + $out = $mp->getPage($nav); + break; + + case 2 : + // Object to use when rendering the page template + $page = new stdClass(); + // Page navigation + $page->nav = $nav->getPageNav(); + + // Linked List of member photos + $linkedList = new Toolkit_Members_Photos(null, $_GET['id']); + $linkedList->createMemberList( + $pdo, + $root + ); + // Member Object to get calculate attributes about a member + $member = new Toolkit_Members_Member( + $pdo, + $root + ); + // Server side caching + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + // Image server for processing uploaded images + $is = new Toolkit_Image_Server(); + + if ($member->canAddPhotos($linkedList, $root)) { + $aForm = new Toolkit_Members_Admin_AddPhoto( + $pdo, + 'new_member_photo', + 'post', + BASE_URL . "admin/members.php?cat=2&subCat=2&tab=2&id={$_GET['id']}", + '', + null, + true + ); + $aForm->configureForm($root); + $page->uploadForm = $aForm->toHtml( + $tEngine, + $cache, + $root, + $is, + $linkedList + ); + } + + if ($member->hasUploadedPhotos($linkedList)) { + $editForms = array(); + $linkedList->rewind(); + + foreach ($linkedList as $i) { + if (!$i->getPending()) { + $id = $i->getId(); + $eForm = new Toolkit_Members_Admin_EditPhoto( + $pdo, + $linkedList, + "edit_member_photo_$id", + 'post', + BASE_URL . "admin/members.php?cat=2&subCat=2&tab=2&id={$_GET['id']}", + '', + array('id' => $id), + true + ); + $eForm->configureForm($root); + $page->editForms[$id] = $eForm->toHtml( + $tEngine, + $cache, + $is, + $root + ); + } + } + } + + // get reference to [photos] section of config file + $config =& $root->getItem('section', 'photos'); + $template =& $config->getItem('directive', 'editGalleryTemplate'); + + $tEngine->compile($template->getContent()); + $out = $tEngine->bufferedOutputObject($page); + break; + + case 1 : + default : + $mr =& new Toolkit_Members_EditMemberInfo( + $pdo, + 'edit_member', + 'post', + null, + null, + null, + true + ); + + $mr->setStates( + Toolkit_Common::getStates($pdo) + ); + $mr->setConfig($root); + $mr->configureForm(); + $out = $mr->toHtml(); + break; + } + + return $out; + } + + // }}} + + // {{{ getCacheOptions() + + /** + * Get the cache options defined for the memberdb app + * + * @return array Cache_Lite options defined for the memberdb app + * @access public + * @static + */ + public static function getCacheOptions() + { + $options = $GLOBALS['cacheOptions']; + $options['cacheDir'] = BASE . 'Toolkit/Members/cache/'; + return $options; + } + + // }}} + // {{{ getFlexyOptions() + + /** + * Get the flexy options defined for the memberdb app + * + * @return array Flexy template options defined for the memberdb app + * @access public + * @static + */ + public static function getFlexyOptions() + { + $options = $GLOBALS['flexyOptions']; + $options['templateDir'] = BASE . 'Toolkit/Members/templates/'; + $options['compileDir'] = BASE . 'Toolkit/Members/templates/compiled/'; + return $options; + } + + // }}} + + // {{{ show() + + /** + * Show the page + * + * @return void + * @access public + */ + public function show() + { + echo $this->toHtml(); + } + + // }}} +} +?> diff --git a/Toolkit/Members/AddPhoto.php b/Toolkit/Members/AddPhoto.php new file mode 100644 index 0000000..0316124 --- /dev/null +++ b/Toolkit/Members/AddPhoto.php @@ -0,0 +1,198 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: AddPhoto.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see Toolkit/Image/Server.php + */ + + +/** + * The image server processing class + */ +require_once BASE . 'Toolkit/Image/Server.php'; + +/** + * Form to handle creating a new photo in the members only area + * + * Handles inserting new photo into db as a pending photo and creating a + * tuple in the member_updates table which will allow the admin to + * approve/deny the new photo request. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_AddPhoto extends Toolkit_Members_Admin_AddPhoto +{ + // {{{ createPendingPhoto() + + /** + * Adds photo to member and makes a pending row in the updates table + * + * Adds a photo to the member_photos table but sets the pending field + * to true and then inserts a row into the updates table to make the field + * pending. If the photo gets rejected we will have to delete from both + * the updates table and the member_photos table. + * + * @param array &$values submitted values from the form. + * + * @return boolean Result of creating a pending photo + * @access protected + */ + protected function createPendingPhoto(&$values) + { + try { + // Get the last photo inserted. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE pending = true + AND member_id = :member_id + ORDER BY id DESC"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam( + ':member_id', + $GLOBALS['memberAuth']->getAuthData('member_id'), + PDO::PARAM_INT + ); + $stmt->execute(); + $photo = $stmt->fetch(); + + // Insert the picture into the updates table for approval. + $label = ''.$values['image'].''; + $update = false; + $dataType = 'boolean'; + $field = 'pending'; + + $sql = " + INSERT INTO " . Toolkit_Membersonly::PENDING_TABLE . " + (member_id, field, update , db_table, + data_type, label, foreign_key) + VALUES (:member_id, :field, :update, :db_table, + :data_type, :label, :foreign_key)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam( + ':member_id', + $GLOBALS['memberAuth']->getAuthData('member_id'), + PDO::PARAM_INT + ); + $stmt->bindParam(':field', $field, PDO::PARAM_STR); + $stmt->bindParam(':update', $update, PDO::PARAM_BOOL); + $stmt->bindParam(':db_table', $this->tableName, PDO::PARAM_STR); + $stmt->bindParam(':data_type', $dataType, PDO::PARAM_STR); + $stmt->bindParam(':label', $label, PDO::PARAM_STR); + $stmt->bindParam(':foreign_key', $photo['id'], PDO::PARAM_STR); + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ processData() + + /** + * Handles setting up the from processing and which function to get it done + * + * @param array $values Submitted values from the form. + * + * @return void + * @access protected + */ + protected function processData($values) + { + try { + $this->dbh->beginTransaction(); + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + + $res = Toolkit_Common::processQuery($this->dbh, $sql, $values); + + + if ($values['pending']) { + $this->createPendingPhoto($values); + } + $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + + header('Location:' . $this->getAttribute('action')); + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @param HTML_Template_Flexy $tEngine Templating Engine + * @param Cache_Lite $cache Caching Engine + * @param Config_Container $c Application configuration + * @param Toolkit_Image_Server $is Image Server + * @param Toolkit_Members_Photos $ll Linked List of member photos + * + * @return string The rendered form + * @access public + */ + public function toHtml( + HTML_Template_Flexy $tEngine, + Cache_Lite $cache, + Config_Container $c, + Toolkit_Image_Server $is, + Toolkit_Members_Photos $ll + ) { + if ($this->validate()) { + $config = $c->getItem('section', 'conf'); + $strictPending = $config->getItem('directive', 'strictPending'); + + $id = $GLOBALS['memberAuth']->getAuthData('member_id'); + $cache->remove("Member-$id", 'Profile'); + + // Inject some data into the submitted values + $this->_submitValues['image'] = $is->imageUpload('file'); + $this->_submitValues['pos'] = $ll->getListSize() + 1; + $this->_submitValues['member_id'] = $id; + $this->_submitValues['pending'] = (int) $strictPending->getContent(); + + unset($this->_submitValues['MAX_FILE_SIZE'], + $this->_submitValues['submit']); + + $this->process(array(&$this, 'processData'), false); + } + + $this->setupRenderers($tEngine); + + return $tEngine->bufferedOutputObject($this->view); + } + + // }}} +} +?> diff --git a/Toolkit/Members/AddYourBusiness.php b/Toolkit/Members/AddYourBusiness.php new file mode 100755 index 0000000..543812b --- /dev/null +++ b/Toolkit/Members/AddYourBusiness.php @@ -0,0 +1,1246 @@ + + * @copyright 2008 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: AddYourBusiness.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +require_once 'FormBuilder.php'; + +/** + * Description for require_once + */ +require_once 'Members/CategoryTree.php'; + +/** + * Creates, Renders, Processes form for request to be added to Business DB + * + * This Form just sends the primary advisee an HTML email of the data + * that was filled in and requires them to add the users to the Business DB + * themselves. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_AddYourBusiness + extends Toolkit_FormBuilder implements Toolkit_Form +{ + // {{{ properties + + /** + * PDO connections + * + * @var string + * @access public + */ + public $dbh; + + /** + * Allow duplicate member names to be valid or not + * + * @var boolean + * @access private + */ + private $_preventDupNames; + + /** + * The name of the DB table that holds the member records + * + * @var array + * @access protected + */ + public $tableName = 'member'; + + /** + * What do you want the success msg to be if the form validates successfully + * + * @var string + * @access protected + */ + protected $successMsg = ' +
    + Your business Information has been successfully submitted. + A representative will be contacting you shortly to follow up. +
    '; + + /** + * Primary email address to send notification a record has been updated + * + * Set this value to false and it will turn off the email + * update notifications. + * + * @var string + * @access protected + */ + protected $primaryAdvisee; + + /** + * Email address of people that might also want to be advised of updates + * + * A list of all email address that might also want to be advised + * updates have been made on a business record. You can add as many + * as you would like and they will be CC in the email. + * + * If you use associative key values then they will be appended + * to the email string. i.e. + * Jamie Kahgee + * Other wise the address will just be added. + * + * N.B. You cannot make this array bigger than 5 people or you will need to + * rewrite the function to handle the server spam issue. + * + * @var array + * @access private + */ + protected $secondaryAdvisees = array( + ); + + /** + * If the admin needs to approve members before they are allowed to join + * + * @var boolean + * @access protected + * @see $authNetAccount + */ + protected $approvalNeeded = true; + + /** + * Should the captcha be included in the form + * + * If credit card processing is being handled in the form there is usually + * no need to include the captcha. + * Setting this value to false will cause the captcha to be excluded + * + * @var boolean + * @access protected + * @see $authNetAccount + */ + protected $includeCaptcha = false; + + /** + * If new members will use auth.net to pay and create a new account + * + * This will override the approvalNeeded property, as a paid member + * account should not need to have thier account authorized twice. + * + * + * protected $autNetAccount = array( + * 'auth_net_login_id' => '1234key', + * 'auth_net_tran_key' => '1234567890key', + * ); + * + * + * @var boolean + * @access protected + */ + protected $authNetAccount = false; + + /** + * Flexy options used in the renderer + * + * @var array + * @access protected + */ + protected $flexyOptions; + + /** + * The default rules to register for validating + * + * @var array + * @access protected + */ + protected $registeredRules = array(); + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional) Form's method defaults to 'POST' + * @param string $action (optional) Form's action. + * @param string $target (optional) Form's target defaults to '_self' + * @param mixed $attributes (optional) Extra attributes for
    tag. + * @param bool $trackSubmit (optional) Whether to track if the form was + * submitted by adding a special hidden + * field. + * + * @access public + * @see Toolkit_FormBuilder, HTML_QuickForm + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->template = dirname(__FILE__) . '/templates/currentTables/'; + + $this->dbh = $pdo; + if (!$this->approvalNeeded && is_array($this->authNetAccount)) { + $this->approvalNeeded = false; + } + + if ($this->primaryAdvisee !== false && empty($this->primaryAdvisee)) { + // Set to false to turn off email function. + $this->primaryAdvisee = OWNER_EMAIL; + } + + $this->flexyOptions = Toolkit_Members::getFlexyOptions(); + $var = basename(__FILE__, '.php'); + + $callbackUrl = ($_SERVER['HTTPS'] == 'on') ? + BASE_SECURE_URL : BASE_URL; + + $this->captchaOptions = array( + 'width' => 100, + 'height' => 50, + 'callback' => "{$callbackUrl}Toolkit/qfcaptcha.php?var=$var", + 'sessionVar' => $var, + 'imageOptions' => array( + 'font_size' => 16, + 'font_path' => GLM_APP_BASE . 'glmPEAR/Image/Canvas/Fonts/', + 'font_file' => 'times.ttf', + 'background_color' => '#cccccc', + 'obfuscation' => false, + 'angle' => true, + ), + ); + } + + // }}} + + // {{{ checkCvv() + + /** + * Check if the credit card CVV is properly formatted + * + * @param array $values credit card num and cvv number from the form + * + * @return boolean whether the cvv is properly formatted + * @access public + */ + public function checkCvv($values) + { + return Validate_Finance_CreditCard::cvv($values[0], $values[1]); + } + + // }}} + // {{{ checkDateInput() + + /** + * Checks the validation of a m-d-Y date + * + * This function will only be called if the autoValidateDateElements + * property is set to true + * + * @param array $value Date element from form. + * + * @return boolean + * @access public + * @see Toolkit_FormBuilder::autoValidateDateElements + */ + public function checkDateInput($value) + { + $res1 = is_numeric($value['m']); + $res2 = is_numeric($value['Y']); + + if (!($res1 && $res2)) { + return false; + } + + $date = implode('-', $value); + + return Validate::date($date, array('format' => '%j-%Y')); + } + + // }}} + // {{{ checkMemberLogin() + + /** + * Check to see if the member name is valid (doesn't already exists) + * + * @param string $uname desired user name to check + * + * @return boolean if the username is valid (doesn't exist) + * @access public + */ + public function checkMemberLogin($uname) + { + try { + $sql = " + SELECT count(*) AS total + FROM {$this->tableName} + WHERE member_login = :uname"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':uname', $uname, PDO::PARAM_STR); + $stmt->execute(); + $stmt->bindColumn('total', $isValid); + $stmt->fetch(); + + return (bool) !$isValid; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ checkMemberName() + + /** + * Checks for duplicate member names + * + * @param string $name Member name to check for + * + * @return boolean if the name is valid (doesn't exist) + * @access public + */ + public function checkMemberName($name) + { + try { + $sql = " + SELECT count(*) AS total + FROM {$this->tableName} + WHERE member_name = :name"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':name', $name, PDO::PARAM_STR); + $stmt->execute(); + $stmt->bindColumn('total', $isValid); + $stmt->fetch(); + + return (bool) !$isValid; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ checkNumber() + + /** + * Check if the credit card number is properly formatted + * + * Credit card numbers have a specific formatting based on the credit card + * types. + * i.e. (visa, discover, etc...) This call verifies if the # was properly + * formatted against the card type selected + * + * @param array $values credit card type and number from the form + * + * @return boolean if cc number is properly formatted based on the card type + * @access public + */ + public function checkNumber($values) + { + if (empty($values[1])) { + $values[1] = null; + } + + return Validate_Finance_CreditCard::number($values[0], $values[1]); + } + + // }}} + // {{{ configureConstants() + + /** + * Sets the constants for the form + * + * @return void + * @access public + */ + public function configureConstants() + { + if ($this->approvalNeeded || !is_array($this->authNetAccount)) { + $newMember = 1; + } else { + $newMember = 0; + } + $constants = array( + 'new_member' => $newMember, + ); + + $this->setupConstants($constants); + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + // get reference to [listing type] section of config file + $config =& $this->config->getItem('section', 'listing type'); + // get coupon + $singularDirective =& $config->getItem('directive', 'singular'); + $singularType = $singularDirective->getContent(); + $pluralDirective =& $config->getItem('directive', 'plural'); + $pluralType = $pluralDirective->getContent(); + + $this->setCategories(); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + // Member Information + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'new_member' + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'yourInfoHdr', + 'display' => 'Your Information' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'fname', + 'display' => 'First Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'lname', + 'display' => 'Last Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'member_contact_email', + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'member_contact_email_rmv', + 'display' => 'Confirm Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'businessInfoHdr', + 'display' => "$singularType Information", + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'member_name', + 'display' => "$singularType Name", + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'member_login', + 'display' => 'Username' + ); + $e[] = array( + 'type' => 'password', + 'req' => true, + 'name' => 'member_passwd', + 'display' => 'Password' + ); + $e[] = array( + 'type' => 'password', + 'req' => true, + 'name' => 'member_passwd_rmv', + 'display' => 'Confirm Password' + ); + $e[] = array( + 'type' => 'CAPTCHA_Image', + 'req' => false, + 'name' => 'captcha_question', + 'display' => 'Verification code', + 'opts' => $this->captchaOptions + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'captcha_rmv', + 'display' => 'Enter verification code' + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit_rmv', + 'display' => 'Submit' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureFilters() + + /** + * Setup the filters to apply to the elements before we are + * handed the values submitted + * + * @return void + * @access public + */ + public function configureFilters() + { + $f = array(); + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Helper method to setup the entire form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureRules(); + $this->configureFilters(); + $this->configureConstants(); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up all the rules to be used when the form is validated. + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + $r[] = array( + 'element' => 'member_contact_email', + 'message' => 'ERROR: Invalid email address!', + 'type' => 'email', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => array( + 'member_contact_email', + 'member_contact_email_rmv' + ), + 'message' => 'ERROR: Your email addresses do not match!', + 'type' => 'compare', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => array( + 'member_passwd', + 'member_passwd_rmv' + ), + 'message' => 'ERROR: Your passwords do not match!', + 'type' => 'compare', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + if ($this->_preventDupNames) { + $r[] = array( + 'element' => 'member_name', + 'message' => 'ERROR: This name already exists!', + 'type' => 'callback', + 'format' => array(&$this, 'checkMemberName'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + } + $r[] = array( + 'element' => 'member_login', + 'message' => 'ERROR: This username is taken already!', + 'type' => 'callback', + 'format' => array(&$this, 'checkMemberLogin'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + if (is_array($this->authNetAccount)) { + $r[] = array( + 'element' => array('cc_num', 'cc_type'), + 'message' => 'ERROR: Number does not match card type!', + 'type' => 'callback', + 'format' => array(&$this, 'checkNumber'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => array('cc_cvv', 'cc_type'), + 'message' => 'ERROR: CVV does not match card type!', + 'type' => 'callback', + 'format' => array(&$this, 'checkCvv'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + } + if ($this->includeCaptcha) { + $r[] = array( + 'element' => 'captcha_rmv', + 'message' => 'ERROR: What you entered didn\'t match!', + 'type' => 'CAPTCHA', + 'format' => $this->captchaQuestion, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + } + + $this->setupRules($r); + } + + // }}} + // {{{ createCategories() + + /** + * Creates an array from the array of category tree objects + * + * @param array $tree linear category tree array + * @param integer $depth what level we are on + * + * @return array The array list of categories that + * that can be loaded into a select element + * @access protected + */ + protected function createCategories($tree, $depth = 0) + { + $this->records[] = $tree->category; + if ($depth == 0) { + $this->categories[$tree->catid] = "{$tree->category}"; + } else { + $this->categories[$tree->catid] = $tree->category; + } + if (empty($tree->children)) { + return; + } else { + ++$depth; + foreach ($tree->children as $miniTrees) { + $this->createCategories($miniTrees, $depth); + } + } + } + + // }}} + + // {{{ getCategories() + + /** + * Creates array structure of the category tree for use in a select element. + * + * This method will also instantiate a class property called tree for your + * class. This object will hold the tree structure of the categories list + * from the Database. + * + * @return array The array list of categories that can be loaded + * into a select element + * + * @access protected + */ + protected function getCategories() + { + try { + $sql = " + SELECT * + FROM category + WHERE parent_id = 0 + ORDER BY name"; + foreach ($this->dbh->query($sql) as $row) { + $this->tree[] = new Toolkit_Members_CategoryTree($row['category_id'], $row['name'], $this->dbh); + } + if (!empty($this->tree)) { + foreach ($this->tree as $t) { + $this->createCategories($t); + } + } + + if (empty($this->categories)) { + $this->categories = array('' => '-- No Categories Created Yet --'); + } else { + $this->categories + = array('' => '-- Select Category --') + $this->categories; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertData() + + /** + * Inserts contact data into the contact db + * + * @param array $values submitted values + * + * @return object result of db insert query + * @access protected + */ + protected function insertData($values) + { + try { + // If they are paying via auth.net and their account + // doesn't go through, then don't actually insert the member. + if (is_array($this->authNetAccount)) { + if (!$this->processAuthNet()) { + return false; + } + } + + $this->dbh->beginTransaction(); + $memberCategory = $values['category_id']; + unset($values['category_id']); + $params = implode(', ', array_keys($values)); + $bindParams = ':' . implode(', :', array_keys($values)); + + $sql = " + INSERT INTO {$this->tableName} ($params) + VALUES ($bindParams)"; + $stmt = $this->dbh->prepare($sql); + foreach ($values as $k => &$v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } 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. + if (empty($v) && $v !== 0) { + $v = null; + $dataType = PDO::PARAM_NULL; + } + $stmt->bindParam(":$k", $v, $dataType); + } + $stmt->execute(); + + $sql = " + SELECT member_id + FROM {$this->tableName} + ORDER BY member_id DESC LIMIT 1"; + + $row = $this->dbh->query($sql)->fetch(); + + $sql = " + INSERT INTO member_category (member_id, category_id) + VALUES (:mid, :cid)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $row['member_id']); + $stmt->bindParam(':cid', $memberCategory, PDO::PARAM_INT); + $stmt->execute(); + + // If they are paying via auth.net and their account + // doesn't go through, then don't actually insert the member. + if (is_array($this->authNetAccount)) { + $res = $this->processAuthNet($authValues); + if (is_array($res) && !empty($res)) { + if ($res[0] == 1) { + // CC was Accepted. + $this->dbh->commit(); + return true; + } elseif ($res[0] == 2) { + // CC was Declined. + $this->dbh->rollback(); + return 2; + } else { + // There was a CC processing error. + $this->dbh->rollback(); + return $res[0]; + } + } else { + // There was a CC processing error. + $this->dbh->rollback(); + return false; + } + } else { + // Not paying by CC so just commit the insert. + return $this->dbh->commit(); + } + } catch (PDOException $e) { + $this->dbh->rollback(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ processAuthNet() + + /** + * Send payment to auth.net + * + * Test Cards + * Card Number Card Type + * =============== =============== + * 370000000000002 American Express + * 6011000000000012 Discover Card + * 5424000000000015 MasterCard + * 4000000000000000 Visa + * + * @param array $values Submitted values from the form + * + * @return array Auth.net response + * @access protected + */ + protected function processAuthNet($values) + { + $this->setFormData(); + $authNetLoginId = $this->authNetAccount['auth_net_login_id']; + $authNetTranKey = $this->authNetAccount['auth_net_tran_key']; + $authNetUrl = "https://secure.authorize.net/gateway/transact.dll"; + + $authNetValues = array( + 'x_login' => $authNetLoginId, + 'x_version' => '3.1', + 'x_delim_char' => '|', + 'x_delim_data' => 'TRUE', + 'x_type' => 'AUTH_CAPTURE', + 'x_method' => 'CC', + 'x_tran_key' => $authNetTranKey, + 'x_relay_response' => 'FALSE', + 'x_card_num' => $values['cc_num'], + 'x_exp_date' => implode('', $values['cc_exp']), + 'x_amount' => $values[$values['member_type']], + 'x_first_name' => $values['cc_fname'], + 'x_last_name' => $values['cc_lname'], + ); + + $fields = ''; + foreach ($authNetValues as $i => $j) { + $fields .= "$i=" . urlencode($j) . '&'; + } + + $ch = curl_init($authNetUrl); + // set to 0 to elimindate header info from response + curl_setopt($ch, CURLOPT_HEADER, 0); + // Returns response data instead of TRUE(1) + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + // Use HTTP POST to send form data + curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($fields, "& ")); + // Uncomment this line if you get no gateway response. ### + // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + // Execute post and get results + $resp = curl_exec($ch); + curl_close($ch); + + $res = explode('|', $resp); + return $res; + } + + // }}} + // {{{ processData() + + /** + * Handles how to process the form when submitted + * + * @param array $values Form submitted values + * + * @return array Result of Insert / Update function + * @access protected + */ + public function processData($values) + { + $values['primary_contact'] = "{$values['fname']} {$values['lname']}"; + unset($values['fname'], $values['lname']); + + // Form data used for the insert/update sql queries and + // the form email. + $e = array(); + $this->setFormData($e); + + // Get rid of any defined un-needed elements. + // un-needed elements after the form is submitted are defined + // by the ending _rmv name. + foreach ($values as $k => &$v) { + if (preg_match('/^.+_rmv$/', $k)) { + unset($values[$k]); + } + } + + Toolkit_Common::getTableMetaData(); + + return $this->insertData($values); + } + + // }}} + + // {{{ sendAdminEmail() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param boolean $test Parameter description (if any) ... + * + * @return boolean Return description (if any) ... + * @access public + */ + public function sendAdminEmail($test = false) + { + if ($this->primaryAdvisee === false) { + return true; + } else { + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + + $page->base_url = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL : + BASE_URL; + $page->approval_needed = $this->approvalNeeded; + $page->member_name = $this->formData['member_name']['element']; + $page->client_name = SITENAME; + $page->email_from = OWNER_EMAIL; + + $template->compile('addYourBusinessAdminEmail.tpl'); + // Merge the compiled template with the $page object. + $htmlMsg = $template->bufferedOutputObject($page); + + $msg = ''; + + $crlf = "\n"; + $mimeMail = new Mail_mime($crlf); + $mimeMail->setFrom(SITENAME . " <{$page->email_from}>"); + $mimeMail->setSubject('Add Your Business Request From ' . SITENAME); + if (!empty($this->secondaryAdvisees)) { + // Spam will choke if we CC: more than 5 addresses. + // so if the user puts more than 5 in, we'll only + // accept the first 5. This is stated in the property + // description for secondaryAdvisees + if (count($this->secondaryAdvisees) > 5) { + $this->secondaryAdvisees = array_slice($this->secondaryAdvisees, 0, 5); + } + foreach ($this->secondaryAdvisees as $k => $v) { + if (is_string($k) && !is_numeric($k)) { + $email = "$k <$v>"; + } else { + $email = $v; + } + $mimeMail->addCC($email); + } + } + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + // If we're testing the interface then don't actually send out the mail + $interface = $test ? 'mock' : 'mail'; + $mail =& Mail::factory($interface); + $body = $mimeMail->get(); + $headers = $mimeMail->headers($hdrs); + + $res = $mail->send($this->primaryAdvisee, $headers, $body); + + return PEAR::isError($res) ? Toolkit_Common::handleError($res) : $res; + } + } + + // }}} + // {{{ sendMemberEmail() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param boolean $test Parameter description (if any) ... + * + * @return unknown Return description (if any) ... + * @access public + */ + public function sendMemberEmail($test = false) + { + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + + $page->base_url = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL : + BASE_URL; + $page->member_category = MEMBERS_CATEGORY; + $page->approval_needed = $this->approvalNeeded; + $page->first_name = $this->formData['fname']['element']; + $page->member_name = $this->formData['member_name']['element']; + $page->username = $this->formData['member_login']['element']; + $page->password = $this->formData['member_passwd']['element']; + $page->client_name = SITENAME; + + $template->compile('addYourBusinessMemberEmail.tpl'); + // Merge the compiled template with the $page object. + $htmlMsg = $template->bufferedOutputObject($page); + + $msg = ''; + + $crlf = "\n"; + $mimeMail = new Mail_mime($crlf); + $mimeMail->setFrom(SITENAME . ' <'.OWNER_EMAIL.'>'); + $mimeMail->setSubject('Add Your Business Request From ' . SITENAME); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + // If we're testing the interface then don't actually send out the mail + $interface = $test ? 'mock' : 'mail'; + $mail =& Mail::factory($interface); + $body = $mimeMail->get(); + $headers = $mimeMail->headers($hdrs); + + $res = $mail->send($this->formData['member_contact_email']['element'], $headers, $body); + + return PEAR::isError($res) ? Toolkit_Common::handleError($res) : $res; + } + + // }}} + // {{{ setCategories() + + /** + * Creates array structure of the category tree for use in a select element. + * + * This method will also instantiate a class property called tree for your + * class. This object will hold the tree structure of the categories list + * from the Database. + * + * @return array The array list of categories that can be loaded + * into a select element + * + * @access protected + */ + protected function setCategories() + { + try { + $sql = " + SELECT * + FROM category + WHERE parent_id = 0 + ORDER BY name"; + foreach ($this->dbh->query($sql) as $row) { + $this->tree[] = new Toolkit_Members_CategoryTree($row['category_id'], $row['name'], $this->dbh); + } + if (!empty($this->tree)) { + foreach ($this->tree as $t) { + $this->createCategories($t); + } + } + + if (empty($this->categories)) { + $this->categories = array('' => '-- No Categories Created Yet --'); + } else { + $this->categories + = array('' => '-- Choose Category --') + $this->categories; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setConfig() + + /** + * Sets the query to use to fetch the datagrid results + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function setConfig(Config_Container $c) + { + $this->config = $c; + } + + // }}} + // {{{ setupRenderers() + + /** + * Setup how the form should render + * + * We also need to attach a couple specific rendering templates to + * a few special elements. + * + * @return void + * @access protected + * @see Toolkit_FormBuilder::setupRenderers() + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + $required = '*'; + $error = '
    {error}
    '; + + $renderer->setElementTemplate('{element}', 'submit_rmv'); + + $renderer->setElementTemplate('{element}', 'captcha_question'); + $renderer->setElementTemplate(''.$required.''.$error.'{element}What is this?', 'captcha_rmv'); + } + + // }}} + // {{{ preventDuplicateMembers() + + /** + * Sets the ability for duplicate member names to exist or not + * + * @param boolean $prevent true to reject, false to allow + * + * @return void + * @access public + */ + public function preventDuplicateMembers($prevent = true) + { + $this->_preventDupNames = $prevent; + } + + // }}} + + // {{{ toHtml() + + /** + * Call the rendering function to get the form in a string + * + * destroying and resetting the captcha value dis-allows someone from + * re-sending a form on a previous captcha. + * + * @return string The Form to be rendered or success msg. + * @access public + */ + public function toHtml() + { + $this->setupRenderers(); + if ($this->validate()) { + if ($this->includeCaptcha) { + $this->captchaQuestion->destroy(); + } + + $res = $this->process(array(&$this, 'processData'), $this->mergeFiles); + + if ($res === true) { + $this->cleanForm(); + $this->sendAdminEmail(); + $this->sendMemberEmail(); + $this->freeze(); + $output = $this->successMsg; + if (is_array($this->authNetAccount)) { + $rem = array( + 'cc_cvv', + 'cc_type', + 'cc_fname', + 'cc_lname', + 'member_login', + 'member_passwd', + 'captcha_question', + ); + foreach ($rem as $i) { + if ($this->elementExists($i)) { + $this->removeElement($i); + } + } + + if ($this->elementExists('cc_num')) { + // Obscure th CC Num so its not displayed. + $e =& $this->getElement('cc_num'); + $ccNum = $e->getValue(); + $newCCNum = preg_replace( + '/\d/', + '*', + $ccNum, + strlen($ccNum) - 4 + ); + $e->setValue($newCCNum); + } + } + } elseif ($res == 2) { + $this->_errors['cc_num'] = 'ERROR: Your credit card has been declined!'; + if ($this->includeCaptcha) { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + } + $output = $this->errorMsg; + $output .= parent::toHtml(); + } else { + $this->_errors['cc_num'] = 'ERROR: There was an error processing your credit card!'; + if ($this->includeCaptcha) { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + } + $output = $this->errorMsg; + $output .= parent::toHtml(); + } + } else if ($this->isSubmitted()) { + if ($this->includeCaptcha) { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + } + $output = $this->errorMsg; + $output .= parent::toHtml(); + } else { + if ($this->includeCaptcha) { + $this->captchaQuestion->destroy(); + $this->captchaAnswer->setValue(''); + } + $output = parent::toHtml(); + } + return $output; + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/AddPhoto.php b/Toolkit/Members/Admin/AddPhoto.php new file mode 100644 index 0000000..c416bdd --- /dev/null +++ b/Toolkit/Members/Admin/AddPhoto.php @@ -0,0 +1,344 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: AddPhoto.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see Toolkit/Image/Server.php + */ + + +/** + * The image server processing class + */ +require_once BASE . 'Toolkit/Image/Server.php'; + +/** + * Form to handle creating a new photo in the members only area + * + * Handles inserting new photo into db as a pending photo and creating a + * tuple in the member_updates table which will allow the admin to + * approve/deny the new photo request. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_AddPhoto extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * The table name in the database used to store the data + * + * @var string + * @access public + */ + public $tableName = 'member_photos'; + + /** + * The template used to render the form + * + * @var string + * @access protected + */ + protected $formTemplate = 'addPhoto.tpl'; + + /** + * Success message when a photo gets successfully uploaded + * @var string + * @access protected + */ + protected $successMsg = ' +
    + You successfully uploaded your photo. +
    '; + + /** + * Description for protected + * @var array + * @access protected + */ + protected $registeredRules = array(); + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional) Form's method defaults to 'POST' + * @param string $action (optional) Form's action. + * @param string $target (optional) Form's target defaults to '_self' + * @param mixed $attributes (optional) Extra attributes for tag. + * @param bool $trackSubmit (optional) Whether to track if the form was + * submitted by adding a special hidden + * field. + * + * @access public + * @see Toolkit_Members_Admin_EditPhotos + */ + public function __construct( + $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->dbh = $pdo; + } + + // }}} + + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @param Config_Container $c application configuration + * + * @return void + * @access public + */ + public function configureElements(Config_Container $c) + { + $e = array(); + + $config =& $c->getItem('section', 'photos'); + $maxLength =& $config->getItem('directive', 'maxCaptionLength'); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'file', + 'req' => true, + 'name' => 'file', + 'display' => 'Upload a Photo', + 'opts' => array('class' => 'submit') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'caption', + 'display' => 'Caption', + 'opts' => array( + 'class' => 'text', + 'maxlength' => $maxLength->getContent(), + ), + 'noCharLimit' => true + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit', + 'display' => 'Upload new photo', + 'opts' => array('class' => 'submit') + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureForm() + + /** + * helper function to set up entire form definition + * + * @param Config_Container $c application configuration + * + * @return void + * @access public + */ + public function configureForm(Config_Container $c) + { + $this->configureElements($c); + $this->configureRules($c); + } + + // }}} + // {{{ configureRules() + + /** + * Configure rules for form + * + * @param Config_Container $c application configuration + * + * @return void + * @access public + */ + public function configureRules(Config_Container $c) + { + $config =& $c->getItem('section', 'photos'); + $maxLength =& $config->getItem('directive', 'maxCaptionLength'); + + $mimeTypes = array( + 'image/jpe', + 'image/jpeg', + 'image/jpg', + 'image/jfif', + 'image/pjpeg', + 'image/pjp', + 'image/gif', + 'image/png', + ); + + $r = array(); + + $r[] = array( + 'element' => 'file', + 'message' => 'ERROR: You must select a file!', + 'type' => 'uploadedfile', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'caption', + + 'message' => "ERROR: {$maxLength->getContent()} characters max!", + 'type' => 'maxlength', + 'format' => $maxLength->getContent(), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'file', + 'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!', + 'type' => 'mimetype', + 'format' => $mimeTypes, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ processData() + + /** + * Handles setting up the from processing and which function to get it done + * + * @param array $values Submitted values from the form. + * + * @return void + * @access protected + */ + protected function processData($values) + { + try { + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + + $res = Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + + header('Location:' . $this->getAttribute('action')); + } + + // }}} + + // {{{ setupRenderers() + + /** + * Set up the rendering engine we are going to use to display this form + * + * @param HTML_Template_Flexy &$tEngine Templating Engine + * + * @return void + * @access protected + */ + protected function setupRenderers(HTML_Template_Flexy &$tEngine) + { + $renderer =& new HTML_QuickForm_Renderer_ObjectFlexy($tEngine); + + $this->accept($renderer); + $this->view = new stdClass(); + $this->view->form = $renderer->toObject(); + $tEngine->compile($this->formTemplate); + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @param HTML_Template_Flexy $tEngine Templating Engine + * @param Cache_Lite $cache Caching Engine + * @param Config_Container $c Application configuration + * @param Toolkit_Image_Server $is Image Server + * @param Toolkit_Members_Photos $ll Linked List of member photos + * + * @return string The rendered form + * @access public + */ + public function toHtml( + HTML_Template_Flexy $tEngine, + Cache_Lite $cache, + Config_Container $c, + Toolkit_Image_Server $is, + Toolkit_Members_Photos $ll + ) { + if ($this->validate()) { + $cache->remove("Member-{$_GET['id']}", 'Profile'); + + // Put the processed photo's new name into the submitted values + $this->_submitValues['image'] = $is->imageUpload('file'); + $this->_submitValues['pos'] = $ll->getListSize() + 1; + $this->_submitValues['member_id'] = $_GET['id']; + $this->_submitValues['pending'] = 0; + + unset($this->_submitValues['MAX_FILE_SIZE'], + $this->_submitValues['submit']); + + $this->process(array(&$this, 'processData'), false); + } + + $this->setupRenderers($tEngine); + + return $tEngine->bufferedOutputObject($this->view); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/AuthorizeNewMemberForm.php b/Toolkit/Members/Admin/AuthorizeNewMemberForm.php new file mode 100755 index 0000000..7a464db --- /dev/null +++ b/Toolkit/Members/Admin/AuthorizeNewMemberForm.php @@ -0,0 +1,572 @@ + + * @copyright 2008 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: AuthorizeNewMemberForm.php,v 1.2 2009/12/15 20:18:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +require_once 'FormBuilder.php'; + +/** + * Description for require_once + */ +require_once 'HTML/Template/Flexy.php'; + +/** + * Description for require_once + */ +require_once 'Mail/mime.php'; + +/** + * Description for require_once + */ +require_once 'Mail.php'; + +/** + * Creates, Renders, Processes form for request to be added to Business DB + * + * This Form just sends the primary advisee an HTML email of the data + * that was filled in and requires them to add the users to the Business DB + * themselves. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_AuthorizeNewMemberForm extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * PDO connections + * + * @var string + * @access public + */ + public $dbh; + + /** + * The name of the DB table that holds the member records + * + * @var array + * @access protected + */ + public $tableName = 'member'; + + /** + * States array for select list + * + * @var array + * @access protected + */ + protected $states; + + /** + * What do you want the success msg to be if the form validates successfully + * + * @var string + * @access protected + */ + protected $successMsg = '
    '; + + /** + * Primary email address to send notification a record has been updated + * + * Set this value to false and it will turn off the email + * update notifications. + * + * @var string + * @access protected + */ + protected $primaryAdvisee = 'jamie@gaslightmedia.com'; + + /** + * Flexy options used in the renderer + * + * @var array + * @access protected + */ + protected $flexyOptions; + + /** + * The name of the template used to email the owner for any updates + * + * When a member makes an update to thier record, this is the template + * we will use to send out the email notification to the site owner. + * + * @var string + * @access protected + */ + protected $emailTemplate = 'addYourBusinessEmailOwner.tpl'; + + /** + * The flexy template object which holds the rendered object + * + * @var object + * @access protected + */ + protected $template; + + // }}} + + // {{{ __construct() + + /** + * Constructor + * + * @param string $formName Form's name. + * @param string $method (optional) Form's method defaults to 'POST' + * @param string $action (optional) Form's action. + * @param string $target (optional) Form's target 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 + * @see Toolkit_FormBuilder, HTML_QuickForm + */ + public function __construct( + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->template = dirname(__FILE__) . '/../templates/currentTables/'; + $this->states = $states_US; + $this->registeredRules = array('zip', 'phone', 'memberlogo'); + + $this->dbh = Toolkit_Database::getInstance(); + + /** + * Where are the flexy templates stored at for this class. + */ + define('TEMPLATES_DIR', BASE . 'Toolkit/Members/templates'); + + /** + * Where are the compiled flexy templates stored at for this class. + */ + define('COMPILED_DIR', BASE . 'Toolkit/Members/templates/compiled'); + + $oldUmask = umask(0); + if (!is_dir(TEMPLATES_DIR)) { + mkdir(TEMPLATES_DIR, 0770, true); + } + if (!is_dir(COMPILED_DIR)) { + mkdir(COMPILED_DIR, 0770, true); + } + umask($oldUmask); + + $this->flexyOptions = $GLOBALS['flexyOptions']; + $this->flexyOptions['templateDir'] = TEMPLATES_DIR; + $this->flexyOptions['compileDir'] = COMPILED_DIR; + + $this->configureElements(); + $this->configureRules(); + $this->configureFilters(); + $this->configureDefaults(); + $this->configureConstants(); + } + + // }}} + + // {{{ approveMember() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return mixed Return description (if any) ... + * @access protected + */ + protected function approveMember() + { + try { + $sql = " + UPDATE {$this->tableName} + SET new_member = false + WHERE member_id = ?"; + + $stmt = $this->dbh->prepare($sql); + return $stmt->execute(array($_GET['id'])); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ denyMember() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return mixed Return description (if any) ... + * @access protected + */ + protected function denyMember() + { + try { + $sql = " + DELETE FROM {$this->tableName} + WHERE member_id = ?"; + + $stmt = $this->dbh->prepare($sql); + return $stmt->execute(array($_GET['id'])); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureConstants() + + /** + * Sets the constants for the form + * + * @return void + * @access protected + */ + protected function configureConstants() + { + $c = array( + 'new_member' => 0, + ); + + $this->setupConstants($c); + } + + // }}} + // {{{ configureDefaults() + + /** + * Sets the defaults for the form + * + * @return array $defaults Returns the array of defaults + * so children who call this function + * can obtain a copy of these values. + * @access protected + * @see Toolkit_FormBuilder::setupDefaults() + */ + protected function configureDefaults() + { + $defaults = array(); + + try { + if (is_numeric($_GET['id'])) { + $sql = " + SELECT m.*, c.name AS category + FROM {$this->tableName} m + JOIN member_category mc USING (member_id) + JOIN category c USING (category_id) + WHERE m.member_id = :mid + AND m.new_member = true"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + if ($row = $stmt->fetch()) { + foreach ($row as $i => $j) { + $defaults[$i] = $j; + } + } + + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + + $this->setupDefaults($defaults); + return $defaults; + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @return void + * @access protected + * @see Toolkit_FormBuilder::setupElements() + */ + protected function configureElements() + { + $e = array(); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'approve', + 'display' => 'Approve', + 'opts' => array('id' => 'approve') + ); + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'deny', + 'display' => 'Deny', + 'opts' => array('id' => 'deny') + ); + + // Member Information + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'new_member' + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'newMemberHdr', + 'display' => 'New ' . Toolkit_Members_Admin_Controller::$listingType['singular'] . ' Request Information' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'member_name', + 'display' => Toolkit_Members_Admin_Controller::$listingType['singular'] . ' Name' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'primary_contact', + 'display' => 'Primary Contact' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'member_contact_email', + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'category', + 'display' => 'Category' + ); + $e[] = array( + 'type' => 'group', + 'req' => false, + 'name' => 'decision', + 'group' => $submitBtns, + 'seperator' => '', + 'appendName' => false + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureFilters() + + /** + * Setup the filters to apply to the elements before we are + * handed the values submitted + * + * @return void + * @access protected + */ + protected function configureFilters() + { + $f = array(); + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up all the rules to be used when the form is validated. + * + * @return void + * @access Protected + */ + protected function configureRules() + { + $this->setupRules($rules); + } + + // }}} + // {{{ emailMember() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $status Parameter description (if any) ... + * @param boolean $test Parameter description (if any) ... + * + * @return unknown Return description (if any) ... + * @access public + */ + public function emailMember($status, $test = false) + { + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + + $data = $this->configureDefaults(); + $page->base_url = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL : + BASE_URL; + $page->client_name = SITENAME; + $page->member_login = $data['member_login']; + $page->member_passwd = $data['member_passwd']; + $page->first_name = strtok($data['primary_contact'], ' '); + $page->member_category = MEMBERS_CATEGORY; + + $tpl = $status ? 'newMemberApproval.tpl' : 'newMemberDenial.tpl'; + $template->compile($tpl); + // Merge the compiled template with the $page object. + $htmlMsg = $template->bufferedOutputObject($page); + + $crlf = "\n"; + $mimeMail = new Mail_mime($crlf); + $mimeMail->setFrom(SITENAME . ' <' . OWNER_EMAIL . '>'); + $mimeMail->setSubject('New ' . Toolkit_Members_Admin_Controller::$listingType['singular'] . ' Request'); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $interface = $test ? 'mock' : 'mail'; + $mail =& Mail::factory($interface); + $body = $mimeMail->get(); + $headers = $mimeMail->headers($hdrs); + + try { + $sql = " + SELECT member_contact_email + FROM {$this->tableName} + WHERE member_id = ?"; + + $stmt = $this->dbh->prepare($sql); + $stmt->execute(array($_GET['id'])); + $stmt->bindColumn('member_contact_email', $email); + $stmt->fetch(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + + $res = $mail->send($email, $headers, $body); + + return PEAR::isError($res) ? Toolkit_Common::handleError($res) : $res; + } + + // }}} + + // {{{ processData() + + /** + * Handles how to process the form when submitted + * + * @param array $values Form submitted values + * + * @return array Result of Insert / Update function + * @access protected + */ + public function processData($values) + { + if (array_key_exists('deny', $values)) { + $this->emailMember(false); + return $this->denyMember(); + } elseif (array_key_exists('approve', $values)) { + $this->emailMember(true); + return $this->approveMember(); + } + } + + // }}} + + // {{{ setupRenderers() + + /** + * Setup how the form should render + * + * We also need to attach a couple specific rendering templates to + * a few special elements. + * + * @return void + * @access protected + * @see Toolkit_FormBuilder::setupRenderers() + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + $required = '*'; + $error = '
    {error}
    '; + + $renderer->setElementTemplate('{element}', 'decision'); + } + + // }}} + + // {{{ toHTML() + + /** + * Call the rendering function to get the form in a string + * + * @access protected + * @return string $output The Form to be rendered or success msg. + */ + public function toHTML() + { + $this->setupRenderers(); + $this->freeze(); + if ($this->validate()) { + $this->cleanForm(); + if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) { + header('Location: ' . BASE_URL . 'admin/members.php?cat=2&subCat=4'); + } + } else if ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHTML(); + } else { + $output = parent::toHTML(); + } + return $output; + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/AuthorizeUpdates.php b/Toolkit/Members/Admin/AuthorizeUpdates.php new file mode 100755 index 0000000..9fd3e0f --- /dev/null +++ b/Toolkit/Members/Admin/AuthorizeUpdates.php @@ -0,0 +1,1681 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: AuthorizeUpdates.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Handle processing all the update requests from members + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_AuthorizeUpdates extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * The member we are going to process updates for + * + * @var integer + * @access private + */ + private $_mid; + + /** + * The Table name used to store the data of the member record in the database. + * + * @var string + * @access public + */ + public $tableName = 'member_updates'; + + /** + * Array of data that holds the meta data info on the table + * + * Contains information on the type of fields in the database. + * That way when we run our automated SQL queries with our PDO + * we can properly bind data to our SQL queries. This will + * allow for one more layer of protection against any sql + * injection attempts. + * + * @var string + * @access public + * @see Toolkit_Common::processData() + */ + public $tableMetaData; + + /** + * The name of the template used to render the business info form. + * + * @var string + * @access protected + */ + protected $formTemplate = 'authorizeChanges.tpl'; + + /** + * Form access from inside the template + * + * @var object + * @access protected + */ + protected $view; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + + $this->flexyOptions = Toolkit_Members::getFlexyOptions(); + } + + // }}} + + // {{{ commitUpdates + + /** + * Commit the updates requested by the member + * + * @param string $table The table to commit any updates for + * @param array $fields The fields to update + * @param array $updates The updates + * + * @return boolean true on success, false on error + * @access protected + */ + protected function commitUpdates($table, array $fields, array $updates) + { + foreach ($fields as $k => &$v) { + $orig = $v; + list ($id, $v) = explode('_', $v, 2); + if (array_key_exists("{$orig}_update", $updates)) { + $updates["{$v}_update"] = $updates["{$orig}_update"]; + unset($updates["{$orig}_update"]); + } + } + try { + $this->dbh->beginTransaction(); + // This will be the query we will use at the end to update the + // members record. + $sql = $this->getUpdateQuery($table, $fields); + + // hack to fix states trying to update w/ the + // text ie (North Carolina - go heels!) vs. field id. + unset($updates['state_id_update']); + $updateStmt = $this->dbh->prepare($sql); + $updateStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + + // This will be the query we will use to remove the updates + // from the update table. By removing the field from the updates + // table it takes that field out of a "pending" state, by removing all + // of the fields for a member out of the updates table it removes + // that member from being in a "pending" state. + $sql = " + DELETE FROM {$this->tableName} + WHERE field = :field + AND member_id = :member_id"; + + $deleteStmt = $this->dbh->prepare($sql); + $deleteStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + + // This will be the query we will use to get the updated fields + // information. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id in ( + SELECT max(id) + FROM {$this->tableName} + WHERE member_id = :member_id + AND field = :field)"; + + $fetchStmt = $this->dbh->prepare($sql); + $fetchStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + foreach ($fields as $k => &$f) { + unset($v); + // Get the newest row for this field for this member. + $fetchStmt->bindParam(':field', $f, PDO::PARAM_STR); + $fetchStmt->execute(); + $row = $fetchStmt->fetch(PDO::FETCH_ASSOC); + + // Get the update to apply. + if (array_key_exists("{$f}_update", $updates)) { + $v = $updates["{$f}_update"]; + } else { + $v = $row['update']; + } + + // Get the dataType for the PDO Statement. + $metaData = $row['data_type']; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + // for empty values that are not actually a zero (0), we + // want to insert null's. + // This will help hold the unique values for member_logins, + // as empty values '', are not considered unique + if (empty($v) && $v !== 0) { + $v = null; + $dataType = PDO::PARAM_NULL; + } + // Bind the update for later execution. + $updateStmt->bindParam(":$f", $v, $dataType); + + // Remove this field from the updates + $deleteStmt->bindParam(':field', $f, PDO::PARAM_STR); + $deleteStmt->execute(); + } + $updateStmt->execute(); + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollback(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureDefaults() + + /** + * Sets the defaults for the an existing member + * + * Populates data for the main member form. Also grabs + * data to populate the modules on the form if needed. + * + * @return array $defaults Returns the array of defaults + * so children who call this function + * can obtain a copy of these values. + * @access public + */ + public function configureDefaults() + { + $updatedFieldValues = $this->getUpdatedFieldValues(); + $originalFieldValues = $this->getOriginalFieldValues(); + + if (is_array($updatedFieldValues)) { + $defaults = $updatedFieldValues; + } + + if (is_array($originalFieldValues)) { + if (is_array($defaults)) { + $defaults += $originalFieldValues; + } else { + $defaults = $originalFieldValues; + } + } + + $this->setupDefaults($defaults); + return $defaults; + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * Categories are populated into the protected class property $categories. + * These categories are used to populate the select list of categories. + * Modules are configured before any elements are setup, that way we will + * know if we need to include them in the rendering of the form. + * + * @return void + * @access public + */ + public function configureElements() + { + // Get the newest updates in the update table for this member + // for each field that was updated. + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id IN ( + SELECT max(id) + FROM {$this->tableName} + WHERE member_id = :member_id + GROUP BY field, foreign_key) + ORDER BY db_table, foreign_key, id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch()) { + // If we are dealing w/ a credit card, this + // will extract the name of the card. + // Otherwise, it will leave the value unchanged. + $pattern = '/creditCards\[(.+)\]/'; + $replacement = '$1'; + $row['field'] = preg_replace($pattern, $replacement, $row['field']); + $updates[] = $row; + switch ($row['field_type']) { + case 'select' : + case 'checkbox' : + $elementsToFreeze[$row['id']] = $row['field']; + break; + + default : + break; + } + } + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + + if (is_array($updates)) { + // We're going to need to alter how some of the fields + // are displayed on the page. This is where we set them up. + foreach ($updates as $u) { + unset($type, $opts); + // Determine which fields should be a text field so + // the admin can update them w/ thier own text. + switch ($u['data_type']) { + case 'text' : + case 'integer' : + $textField = true; + break; + + default : + $textField = false; + break; + } + if ($textField) { + switch ($u['label']) { + case 'Description' : + case 'Special Package Description' : + case 'Golf Package Description' : + $type = 'textarea'; + $opts = array( + 'id' => 'd' . microtime(), + 'rows' => 8, + 'cols' => 43, + ); + break; + + default : + $type = 'text'; + $opts = array('class' => 'text'); + break; + } + } + // If we are dealing w/ the fields for the restaurant module + // we need to alter the labels of the text fields. + // Otherwise we could potentially have multiple [To] or [From] + // fields and no way to discern which meal they represent. + if ($u['db_table'] == 'member_restaurants') { + if ($u['data_type'] == 'text') { + $u['label'] = ucwords(str_replace('_', ' ', $u['field'])); + } + } + if ($u['db_table'] == 'member' && $u['field'] == 'logo') { + $u['label'] = ''; + } + if ($u['db_table'] == 'member_packages' && $u['field'] == 'image') { + unset($type, $opts); + } + if (!isset($type)) { + $type = 'static'; + } + $labels[$u['id']][$u['field']]['label'] = $u['label']; + $labels[$u['id']][$u['field']]['db_table'] = $u['db_table']; + + $fields[$u['id']][$u['field']][] = array('type' => 'static', 'req' => false, 'name' => "{$u['id']}_{$u['field']}_orig"); + $fields[$u['id']][$u['field']][] = array('type' => $type, 'req' => false, 'name' => "{$u['id']}_{$u['field']}_update", 'opts' => $opts); + } + + $elements[] = array('type' => 'header', 'req' => false, 'name' => 'memberInfoHdr', 'display' => 'Updates', 'col1' => true); + foreach ($fields as $rowid => $field) { + foreach ($field as $k => $arr) { + if ($table != $labels[$rowid][$k]['db_table']) { + $elements[] = array('type' => 'header', 'req' => false, 'name' => 'table', 'display' => ucwords(str_replace('_', ' ', $labels[$rowid][$k]['db_table']))); + $table = $labels[$rowid][$k]['db_table']; + } + $elements[] = array('type' => 'group', 'req' => false, 'name' => "{$rowid}_{$k}", 'group' => $field[$k], 'label' => $labels[$rowid][$k]['label'], 'seperator' => ' ', 'appendName' => false); + } + } + } + + $this->setupElements($elements); + + + if (!empty($elementsToFreeze)) { + foreach ($elementsToFreeze as $k => $v) { + $eName = "{$k}_{$v}"; + if ($this->elementExists($eName)) { + $e =& $this->getElement($eName); + if (PEAR::isError($e)) { + return Toolkit_Common::handleError($e); + } else { + $e->freeze(); + } + } + } + } + } + + // }}} + // {{{ configureFilters() + + /** + * Setup the filters to apply to the elements before we are + * handed the values submitted + * + * @return void + * @access public + */ + public function configureFilters() + { + $filters[] = array('element' => '__ALL__', 'filter' => 'trim'); + + $this->setupFilters($filters); + } + + // }}} + // {{{ configureForm() + + /** + * Wrapper function to handle setting up the form + * + * @return mixed PEAR error if no member id is set, otherwise true + * @access public + */ + public function configureForm() + { + if (!is_numeric($this->_mid)) { + return PEAR::raiseError('Invalid member id'); + } + + $this->configureElements(); + $this->configureFilters(); + //$this->configureRules(); + $this->configureDefaults(); + + return true; + } + + // }}} + // {{{ configureModules() + + /** + * Turns on a modules if the member has the appropriate category + * + * @return void + * @access protected + */ + protected function configureModules() + { + if (is_array($this->memberCategories)) { + try { + $sql = " + SELECT * + FROM category + WHERE category_id = :cid"; + + $stmt = $this->dbh->prepare($sql); + foreach ($this->memberCategories as $cid => $v) { + $stmt->bindParam(':cid', $cid, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if ($row['accommodations'] == 't') { + $this->accommodations = true; + } + if ($row['restaurant'] == 't') { + $this->restaurant = true; + } + if ($row['golf'] == 't') { + $this->golf = true; + } + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + } + + // }}} + // {{{ configureRules() + + /** + * Sets up all the rules to be used when the form is validated. + * + * @return void + * @access public + */ + public function configureRules() + { + // Define the rules for each element in the group. + $num_rule = array('ERROR: Must contain a valid positive or negative decimal number!', 'numeric'); + // Collect together the rules for each element. + $lat_rules = array('lat' => array($num_rule)); + $lon_rules = array('lon' => array($num_rule)); + + $rules[] = array('element' => 'reservation_id', 'message' => 'ERROR: Must be an integer!', 'type' => 'numeric', 'format' => null, 'validation' => $this->validationType, 'reset' => false, 'force' => false); + $rules[] = array('element' => 'num_rooms', 'message' => 'ERROR: Must be an integer!', 'type' => 'numeric', 'format' => null, 'validation' => $this->validationType, 'reset' => false, 'force' => false); + $rules[] = array('element' => 'latitude', 'message' => 'ERROR:', 'type' => 'group', 'format' => $lat_rules, 'validation' => $this->validationType, 'reset' => false, 'force' => false); + $rules[] = array('element' => 'longitude', 'message' => 'ERROR:', 'type' => 'group', 'format' => $lon_rules, 'validation' => $this->validationType, 'reset' => false, 'force' => false); + $rules[] = array('element' => 'member_name', 'message' => 'ERROR: Name Already used!', 'type' => 'callback', 'format' => array($this, 'checkMemberName'), 'validation' => $this->validationType, 'reset' => false, 'force' => false); + $rules[] = array('element' => 'member_login', 'message' => 'ERROR: Already used, Please choose another!', 'type' => 'callback', 'format' => array($this, 'checkUName'), 'validation' => $this->validationType, 'reset' => false, 'force' => false); + $rules[] = array('element' => 'zip', 'message' => 'ERROR: Invalid Zip Code!', 'type' => 'zip', 'format' => array('requireDBCheck' => false), 'validation' => $this->validationType, 'reset' => false, 'force' => false); + $rules[] = array('element' => 'phone', 'message' => 'ERROR: Invalid Phone Number!','type' => 'phone', 'format' => null, 'validation' => $this->validationType, 'reset' => false, 'force' => false); + $rules[] = array('element' => 'fax', 'message' => 'ERROR: Invalid Phone Number!','type' => 'phone', 'format' => null, 'validation' => $this->validationType, 'reset' => false, 'force' => false); + + $this->setupRules($rules); + } + + // }}} + + // {{{ getMultipleFieldUpdates() + + /** + * Gets the current values for multiple fields of members + * + * Multiple fields are ones that a member can have many of. They idealy + * need a foreign key, but it is impossible to set up dynamic foreign keys. + * examples of these fields are photo captions or file name, or newly added + * files. Since a member can have multiple of these fields pending at the + * same time, we need to figure out the original value for the file names, + * captions, etc... of these fields. + * + * To get these fields, figure out which ones have updates in the updates + * table and get corresponding field from the original table. Then use the + * psuedo foreign_key to get the corresponding match in the actual table. + * + * @return array All the original updates made by the member + * @access protected + * @see Toolkit_Members_authorizeupdates::getOriginalFieldValues() + */ + protected function getMultipleFieldUpdates() + { + $tables = array(); + // Then we need to get all the tables which DO NOT have DISTINCT + // fields in the updates table. That means they DO have a + // psuedo foreign_key pointing back to them. These are going + // to take a little more work to obtain the original values. + $sql = " + SELECT DISTINCT db_table + FROM {$this->tableName} + WHERE foreign_key is NOT NULL"; + foreach ($this->dbh->query($sql) as $row) { + $tables[] = $row['db_table']; + } + + if (empty($tables)) { + return $tables; + } + + // This query will get all the fields that we need to get + // from the original table. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id in ( + SELECT max(id) + FROM {$this->tableName} + WHERE db_table = :db_table + AND member_id = :member_id + GROUP BY field, foreign_key)"; + + $getFieldStmt = $this->dbh->prepare($sql); + $getFieldStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + + $defaults = array(); + foreach ($tables as $t) { + $getFieldStmt->bindParam(':db_table', $t, PDO::PARAM_STR); + $getFieldStmt->execute(); + + // This query will get the current value that the member + // has stored in the DB for the field we want. + $sql = " + SELECT %s + FROM $t + WHERE id = %d"; + + while ($row = $getFieldStmt->fetch()) { + if ($row['data_type'] == 'text') { + $newSql = sprintf($sql, $row['field'], $row['foreign_key']); + $current + = $this->dbh->query($newSql)->fetch(); + if (empty($current[$row['field']])) { + $current[$row['field']] = 'Did not previously exist.'; + } elseif ($t == 'member_packages') { + if ($row['field'] == 'image') { + $current[$row['field']] + = '
    Old + '.$current[$row['field']].' +
    '; + } + } + $defaults["{$row['id']}_{$row['field']}_orig"] + = $current[$row['field']]; + } + } + } + + return $defaults; + } + + // }}} + // {{{ getOriginalFieldValues() + + /** + * Gets all the original values for the fields that have pending updates + * + * @return array of updates for all the fields that the member sent + * @access protected + */ + protected function getOriginalFieldValues() + { + try { + $staticUpdates = $this->getSingleFieldUpdates(); + $dynamicUpdates = $this->getMultipleFieldUpdates(); + + $defaults = array_merge($staticUpdates, $dynamicUpdates); + + return $defaults; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getSingleFieldUpdates() + + /** + * Gets the current values for single fields of members + * + * Single fields are ones that can only show reference one field from + * the updates table to a member. Such as, url, description, num_rooms, + * etc... + * These field will only come from the member table or any member module + * table (golf, restaurant, accommodations). + * + * To get these fields, figure out which ones have updates in the updates + * table and get corresponding field from the original table. + * + * @return array + * @access protected + * @see Toolkit_Members_authorizeupdates::getOriginalFieldValues() + */ + protected function getSingleFieldUpdates() + { + $tables = array(); + // We need to get all the tables which have DISTINCT fields + // in the updates table. That means they do not have a + // psuedo foreign_key pointing back to them. These will be + // easier to get the original values for. + $sql = " + SELECT DISTINCT db_table + FROM {$this->tableName} + WHERE foreign_key is null"; + foreach ($this->dbh->query($sql) as $row) { + $tables[] = $row['db_table']; + } + + if (empty($tables)) { + return $tables; + } + + // This query will get all the fields that we need to get + // from the original table. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id in ( + SELECT max(id) + FROM {$this->tableName} + WHERE db_table = :db_table + AND member_id = :member_id + GROUP BY field)"; + + $getFieldStmt = $this->dbh->prepare($sql); + $getFieldStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + + $defaults = array(); + // We need to get all the tables which have DISTINCT fields + foreach ($tables as &$t) { + $getFieldStmt->bindParam(':db_table', $t, PDO::PARAM_STR); + $getFieldStmt->execute(); + + // This query will get the current value that the member + // has stored in the DB for the field we want. + $sql = " + SELECT %s + FROM $t + WHERE member_id = {$this->_mid}"; + + while ($row = $getFieldStmt->fetch()) { + if ($row['data_type'] == 'text') { + $newSql = sprintf($sql, $row['field']); + $current + = $this->dbh->query($newSql)->fetch(); + + $defaults["{$row['id']}_{$row['field']}_orig"] + = $current[$row['field']]; + } + if ($row['field'] == 'state_id') { + $locationNames = ' + ,( + select state_name + from state + where state.state_id = member.state_id) as state_id'; + + $newSql = sprintf($sql, $row['field'] . $locationNames); + $current + = $this->dbh->query($newSql)->fetch(); + + $defaults["{$row['id']}_{$row['field']}_orig"] + = $current[$row['field']]; + } + } + } + + return $defaults; + } + + // }}} + // {{{ getUpdateQuery() + + /** + * Get the update query for a table in the database + * + * @param string $tname The table name to update in the database + * @param array $accepted All the accepted updates/changes + * + * @return string The update query to run against the database + * @access protected + */ + protected function getUpdateQuery($tname, array $accepted) + { + $params = array_values($accepted); + $length = count($params); + for ($i = 0; $i < $length; ++$i) { + $bindParams .= "{$params[$i]} = :{$params[$i]}"; + if ($i < ($length - 1)) { + $bindParams .= ', '; + } + } + $sql = " + UPDATE $tname + SET $bindParams + WHERE member_id = :member_id"; + return $sql; + } + + // }}} + // {{{ getUpdatedFieldValues() + + /** + * Gets all the values for the newest updates + * + * @return array The updated values + * @access protected + */ + protected function getUpdatedFieldValues() + { + try { + // Get all the latest updates, When we are dealing w/ the state_id + // fields, get the state name vs showing the id number. + // users won't know what the # is. + $sql = " + SELECT *, + CASE + WHEN field = 'state_id' THEN ( + SELECT state_name + FROM state + WHERE state_id = CAST(UPDATE AS integer) ) + WHEN field ~* 'creditCards' AND update = '0' THEN 'Removed' + WHEN field ~* 'creditCards' AND update = '1' THEN 'Added' + WHEN db_table = 'member_amenity' AND update = '0' THEN 'Removed' + WHEN db_table = 'member_amenity' AND update = '1' THEN 'Added' + ELSE UPDATE END AS + UPDATE + FROM {$this->tableName} + WHERE id IN ( + SELECT MAX(id) + FROM {$this->tableName} + WHERE member_id = :member_id + GROUP BY field, foreign_key) + ORDER BY db_table, foreign_key, id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + // If we are dealing w/ a credit card, this + // will extract the name of the card. + // Otherwise, it will leave the value unchanged. + $pattern = '/creditCards\[(.+)\]/'; + $replacement = '$1'; + $row['field'] = preg_replace($pattern, $replacement, $row['field']); + if (empty($row['update'])) { + if ($row['data_type'] == 'boolean') { + $row['update'] = 'Off'; + } + } elseif ($row['data_type'] == 'boolean') { + $row['update'] = 'On'; + } + + // Handle all the member photos requests + if ($row['db_table'] == 'member_photos') { + // The boolean field will only be for the pending status + // if the data_type is boolean we know we are dealing + // with a newly uploaded image + if ($row['data_type'] == 'boolean') { + // No need to show any instructions for + // the accept/reject buttons + $row['update'] = 'Added'; + } + } + if ($row['db_table'] == 'member') { + if ($row['field'] == 'logo') { + $row['update'] = 'Updated'; + } + } + if ($row['db_table'] == 'member_files') { + // if the data_type is boolean we know we are dealing + // with a newly uploaded file + if ($row['data_type'] == 'boolean') { + // No need to show any instructions for + // the accept/reject buttons + $row['update'] = 'Added'; + } + } + if ($row['db_table'] == 'member_packages') { + if ($row['field_type'] == 'file') { + $row['update'] = '
    + New + '.$row['update'].'
    '; + } + } + $defaults["{$row['id']}_{$row['field']}_update"] = $row['update']; + } + + return $defaults; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ group() + + /** + * Gets the group [table name] the field is supposed to be a part of + * + * @param string $field the name of the field in the db. + * + * @return string + * @access public + */ + public function group($field) + { + // The field is going to come in as [id]_[field name] + // so we need to extract the field name from the id. + list($id, $field) = explode('_', $field, 2); + try { + $sql = " + SELECT db_table + FROM {$this->tableName} + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + return $row['db_table']; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ processData() + + /** + * Handles processing the submitted forms data. + * + * Sets up the table meta data so we can insert into the member table. + * removes any unwanted fields from the values array. these fields + * will be denoted by the '_rmv' at the end of thier name in the + * configureElements function + * + * + * ... 'name' => 'remove_rmv', ... + * + * + * This function also verifies that the lat/lon values were properly filled + * out, if they were left blank then the values will either be looked up + * via google maps or through our own zip DB. These values will then be + * inserted into the values array AND also injected into the form field + * values so they will display when the form comes back around. + * + * The form then decides if it is handeling a new member or not and calls + * the appropriate function to insert or update data. + * + * @param array $values The array of all submitted form values. + * + * @return boolean Whether the insert/update succeeded. + * @access protected + * @see Toolkit_Members_EditMemberInfo::configureElements() + */ + protected function processData($values) + { + Toolkit_Common::getTableMetaData(); + + foreach ($values as $k => $v) { + switch ($k) { + default : + if (preg_match('/^.+_rmv$/', $k)) { + unset($values[$k]); + } + break; + } + } + + $this->updateData($values); + $listPage = BASE_URL . "admin/members.php?cat=2&subCat=3"; + header("Location: $listPage"); + } + + // }}} + + // {{{ setMember() + + /** + * Sets the member id to use for updating + * + * @param integer $mid Target Member Id + * + * @return object PEAR Error on invalid member id + * @access public + */ + public function setMember($mid) + { + if (!is_numeric($mid)) { + return PEAR::raiseError('Invalid member id'); + } elseif (!ctype_digit($mid) && !is_int($mid)) { + return PEAR::raiseError('Invalid member id string'); + } + $this->_mid = $mid; + } + + // }}} + // {{{ setupRenderers() + + /** + * Handles compiling and rendering the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $renderer =& new HTML_QuickForm_Renderer_Object(true); + + $this->accept($renderer); + + $this->template =& new HTML_Template_Flexy($this->flexyOptions); + + // Make the view a copy of the $this object + // That way we have access to call functions in + // this class from within the template. + $this->view = $this; + $this->view->form = $renderer->toObject(); + $this->template->compile($this->formTemplate); + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @return string The rendered form + * @access public + */ + public function toHtml() + { + // We need to validate (and freeze if needed) + // before we render the form. That way the + // template knows about any errors on the form. + $this->validated = $this->validate(); + + if ($this->validated) { + $processed = $this->process( + array(&$this, 'processData'), + $this->mergeFiles + ); + } + + // ProcessData handles settingup the lat/lon coordinates if they were + // not entered into the form. these values ar calculated and then + // inserted into the forms element values. So we need to process the + // data first and then render the form. + $this->setupRenderers(); + + return $this->template->bufferedOutputObject($this->view); + } + + // }}} + + // {{{ updateAmenities() + + /** + * Handle updating any approvals or rejections on the member amenities + * + * @param array $amenities The amenity update statuses submitted from the form + * + * @return bool True on success, false on error. + * @access protected + */ + protected function updateAmenities($amenities) + { + if (empty($amenities)) { + return true; + } + try { + $this->dbh->beginTransaction(); + // Stmt to find the newest request in the updates table. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + + $fetchStmt = $this->dbh->prepare($sql); + // Stmt to add amenity to member. + $sql = " + INSERT INTO member_amenity(member_id, amenity_id) + VALUES (:member_id, :aid)"; + + $insStmt = $this->dbh->prepare($sql); + $insStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + // Stmt to remove amenity from member. + $sql = " + DELETE FROM member_amenity + WHERE amenity_id = :aid"; + + $delStmt = $this->dbh->prepare($sql); + // Remove from updates table. + $sql = " + DELETE FROM {$this->tableName} + WHERE member_id = :member_id + AND db_table = 'member_amenity' + AND field = :aid"; + + $remStmt = $this->dbh->prepare($sql); + $remStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + // Loop through all the amenities and see if the update was + // accepted or not. If it was accepted, get the update + // row from the updates table and find out if the update + // was to add [update = 1] the card or remove [update = 0]. + // Perform the update, and then remove the requests from the + // updates table. + foreach ($amenities as $aid => $accepted) { + list($id, $aid) = explode('_', $aid, 2); + if ($accepted == 'yes') { + $fetchStmt->bindParam(':id', $id, PDO::PARAM_INT); + $fetchStmt->execute(); + $row = $fetchStmt->fetch(PDO::FETCH_ASSOC); + + if ($row['update']) { + // Remove the the cards from from the db to make + // sure we don't try to insert the same card to + // a member twice and conflict w/ the unique + // constraint on member_id and ccard_id + $delStmt->bindParam(':aid', $aid, PDO::PARAM_STR); + $delStmt->execute(); + // Insert the card as a row into the db. + $insStmt->bindParam(':aid', $aid, PDO::PARAM_STR); + $insStmt->execute(); + } else { + // Remove the the cards from from the db. + $delStmt->bindParam(':aid', $aid, PDO::PARAM_STR); + $delStmt->execute(); + } + + // Remove field from the member_updates table. + $remStmt->bindParam(':aid', $aid, PDO::PARAM_STR); + $remStmt->execute(); + } else { + // Remove field from the member_updates table. + $remStmt->bindParam(':aid', $aid, PDO::PARAM_STR); + $remStmt->execute(); + } + } + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ updateCCards() + + /** + * Handle updating any approvals or rejections on the member credit cards + * + * @param array $cards The cards update status submitted from the form + * + * @return bool True on success, false on error. + * @access protected + */ + protected function updateCCards($cards) + { + if (empty($cards)) { + return true; + } + foreach ($cards as $k => $v) { + $orig = $k; + list($id, $k) = explode('_', $k, 2); + $cards[$k] = $v; + unset($cards[$orig]); + } + try { + $this->dbh->beginTransaction(); + // Stmt to find the newest request in the updates table. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id in ( + SELECT max(id) + FROM {$this->tableName} + WHERE member_id = :member_id + AND field = :field)"; + + $fetchStmt = $this->dbh->prepare($sql); + $fetchStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + // Stmt to add card to member. + $sql = " + INSERT INTO member_ccard_type (member_id, ccard_type_id) + SELECT :member_id, ccard_type_id + FROM ccard_type + WHERE ccard_type_name = :name"; + + $insStmt = $this->dbh->prepare($sql); + $insStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + // Stmt to remove card from member. + $sql = " + DELETE FROM member_ccard_type + WHERE member_id = :member_id + AND ccard_type_id in ( + SELECT ccard_type_id + FROM ccard_type + WHERE ccard_type_name = :name)"; + + $delStmt = $this->dbh->prepare($sql); + $delStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + // Remove from updates table. + $sql = " + DELETE FROM {$this->tableName} + WHERE member_id = :member_id + AND label = :name"; + + $remStmt = $this->dbh->prepare($sql); + $remStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + // Loop through all the cards and see if the update was + // accepted or not. If it was accepted, get the update + // row from the updates table and find out if the update + // was to add [update = 1] the card or remove [update = 0]. + // Perform the update, and then remove the requests from the + // updates table. + foreach ($cards as $card => $accepted) { + if ($accepted == 'yes') { + $field = "creditCards[$card]"; + $fetchStmt->bindParam(':field', $field, PDO::PARAM_STR); + $fetchStmt->execute(); + $row = $fetchStmt->fetch(PDO::FETCH_ASSOC); + + if ($row['update']) { + // Remove the the cards from from the db to make + // sure we don't try to insert the same card to + // a member twice and conflict w/ the unique + // constraint on member_id and ccard_id + $delStmt->bindParam(':name', $card, PDO::PARAM_STR); + $delStmt->execute(); + // Insert the card as a row into the db. + $insStmt->bindParam(':name', $card, PDO::PARAM_STR); + $insStmt->execute(); + } else { + // Remove the the cards from from the db. + $delStmt->bindParam(':name', $card, PDO::PARAM_STR); + $delStmt->execute(); + } + + // Remove field from the member_updates table. + $remStmt->bindParam(':name', $card, PDO::PARAM_STR); + $remStmt->execute(); + } else { + // Remove field from the member_updates table. + $remStmt->bindParam(':name', $card, PDO::PARAM_STR); + $remStmt->execute(); + } + } + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ updateData() + + /** + * Handles updating all approvals and rejections of pending updates + * + * @param array $values All elements submitted from the form + * + * @return boolean True on success, false on error + * @access protected + */ + protected function updateData($values) + { + // Credit Cards are a special case and handled seperately + $ccardUpdates = $values['member_ccard_type']; + $amenityUpdates = $values['member_amenity']; + $photoUpdates = $values['member_photos']; + $fileUpdates = $values['member_files']; + $packageUpdates = $values['member_packages']; + unset ($values['member_ccard_type'], + $values['member_amenity'], + $values['member_files'], + $values['member_photos'], + $values['member_packages'] + ); + + foreach ($values as $k => $v) { + if (!is_array($v)) { + $updates[$k] = $v; + unset($values[$k]); + } + } + // The values array should now hold all the submitted updates + // in a grouped format and tell you if the field was approved + // to be updated or not. Fields from each table will be grouped + // together and any text field that "could" be changed by the + // admin to fix typos or errors will be in thier own array. + // These updates will have the same associative array key name + // as thier corresponding field with '_update' appended. + // ie. street => street_update, url => url_update, etc.. + // (values example:) + // Array + // ( + // [member] => Array + // ( + // [street] => yes + // [url] => no + // [description] => yes + // ) + // + // [member_accommodations] => Array + // ( + // [num_rooms] => yes + // [year_round] => no + // ) + // + // [member_restaurants] => Array + // ( + // [breakfast] => yes + // ) + // ) + // (updates example:) + // Array + // ( + // [street_update] => 139 Dove Cottage Ln + // [url_update] => www.google.com + // [description_update] => test update 8 + // ) + + try { + // Remove from updates table. + $sql = " + DELETE FROM {$this->tableName} + WHERE member_id = :member_id + AND field = :field + AND db_table = :db_table"; + + $remStmt = $this->dbh->prepare($sql); + $remStmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + // For each of the "rejected" updates, loop through + // and remove them from the arrays as well as from the + // updates DB table. + + // Tables + foreach ($values as $table => &$fields) { + // Fields + // + // The field key names will come in as + // [id_fieldName] => yes + // [id_fieldName] => no + // The id # is the primary key row id number of the update + // in the updates table. + // The fieldName is the name of column that was updated. + foreach ($fields as $k => &$v) { + if ($v == 'no') { + list($id, $field) = explode('_', $k, 2); + $remStmt->bindParam(':field', $field, PDO::PARAM_STR); + $remStmt->bindParam(':db_table', $table, PDO::PARAM_STR); + $remStmt->execute(); + unset($fields["{$id}_{$field}"], + $updates["{$id}_{$field}_update"]); + } + } + // Do some cleanup while we're right here. + // If all the updates were rejected for a single group, + // then unset this array, that way we won't waste our time + // trying to run updates against it later. + if (empty($values[$table])) { + unset($values[$table]); + } + } + + foreach ($values as $k => &$v) { + if (!is_array($updates)) { + $updates = array(); + } + $this->commitUpdates($k, array_keys($v), $updates); + } + $this->updatePackages($packageUpdates); + $this->updateCCards($ccardUpdates); + $this->updateAmenities($amenityUpdates); + $this->updatePhotos($photoUpdates); + $this->updateFiles($fileUpdates); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + return true; + } + + // }}} + // {{{ updateFiles() + + /** + * Handle updating any approvals or rejections on the member files + * + * @param array $files an array of file updates and their update status + * + * @return bool True on success, false on error. + * @access protected + */ + protected function updateFiles($files) + { + if (empty($files)) { + return true; + } + try { + $this->dbh->beginTransaction(); + // Stmt to find the newest request in the updates table for + // a specific field. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + + $fetchStmt = $this->dbh->prepare($sql); + // Stmt to update the file + $updateSql = " + UPDATE member_files + SET %s = :update + WHERE id = :id"; + // Stmt to remove file from member. + $sql = " + DELETE FROM member_files + WHERE id = :id"; + + $delStmt = $this->dbh->prepare($sql); + // Stmt to remove any file name updates for a file that + // are still in the updates table. + $sql = " + DELETE FROM {$this->tableName} + WHERE field = 'file_name' + AND foreign_key = :id"; + + $delFileNameStmt = $this->dbh->prepare($sql); + // Remove from updates table. + $sql = " + DELETE FROM {$this->tableName} + WHERE field = :field + AND foreign_key = :id"; + + $remStmt = $this->dbh->prepare($sql); + // Loop through all the files and see if the update was + // accepted or not. If it was accepted, get the update + // row from the updates table and find out if the update + // was to add [update = 1] the card or remove [update = 0]. + // Perform the update, and then remove the requests from the + // updates table. + foreach ($files as $field => $accepted) { + list($id, $field) = explode('_', $field, 2); + $fetchStmt->bindParam(':id', $id, PDO::PARAM_INT); + $fetchStmt->execute(); + $row = $fetchStmt->fetch(PDO::FETCH_ASSOC); + + if ($accepted == 'yes') { + $updtStmt = $this->dbh->prepare(sprintf($updateSql, $field)); + // we are dealing w/ the file_name + // update the files name. + $updtStmt->bindParam(':update', $row['update'], PDO::PARAM_STR); + $updtStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT); + $updtStmt->execute(); + + // Remove field from the member_updates table. + $remStmt->bindParam(':field', $field, PDO::PARAM_STR); + $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT); + $remStmt->execute(); + } else { + // Remove field from the member_updates table. + $remStmt->bindParam(':field', $field, PDO::PARAM_STR); + $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT); + $remStmt->execute(); + + // a rejected file (we know its a file because it + // has a data_type of boolean) means we have to not only + // remove the row from the updates table, but also + // from the member_files table. + if ($row['data_type'] == 'boolean') { + $delFileNameStmt->bindParam( + ':id', + $row['foreign_key'], + PDO::PARAM_STR + ); + $delFileNameStmt->execute(); + + // Remove the the cards from from the db. + $delStmt->bindParam( + ':id', + $row['foreign_key'], + PDO::PARAM_INT + ); + $delStmt->execute(); + } + } + } + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ updatePackages() + + /** + * Handle updating any approvals or rejections on the member packages + * + * @param array $packages an array of package updates and their update status + * + * @return bool True on success, false on error. + * @access protected + */ + protected function updatePackages($packages) + { + if (empty($packages)) { + return true; + } + try { + $this->dbh->beginTransaction(); + // Stmt to find the newest request in the updates table for + // a specific field. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + + $fetchStmt = $this->dbh->prepare($sql); + // Stmt to update the package + $updateSql = " + UPDATE member_packages + SET %s = :update + WHERE id = :id"; + // Stmt to remove any updates for a package that + // are still in the updates table. + // Remove from updates table. + $sql = " + DELETE FROM {$this->tableName} + WHERE foreign_key = :id + AND field = :field + AND db_table = 'member_packages'"; + + $remStmt = $this->dbh->prepare($sql); + // Loop through all the package field and see if the update was + // accepted or not. If it was accepted, get the update + // row from the updates table and find out if the update + // was to add [update = 1] the card or remove [update = 0]. + // Perform the update, and then remove the requests from the + // updates table. + foreach ($packages as $field => $accepted) { + list($id, $field) = explode('_', $field, 2); + $fetchStmt->bindParam(':id', $id, PDO::PARAM_INT); + $fetchStmt->execute(); + $row = $fetchStmt->fetch(PDO::FETCH_ASSOC); + + if ($accepted == 'yes') { + $updtStmt = $this->dbh->prepare(sprintf($updateSql, $field)); + $update = $this->getSubmitValue("{$id}_{$field}_update"); + if (empty($update)) { + $update = $row['update']; + } + $updtStmt->bindParam(':update', $update, PDO::PARAM_STR); + $updtStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT); + $updtStmt->execute(); + + // Remove field from the member_updates table. + $remStmt->bindParam(':field', $field, PDO::PARAM_STR); + $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT); + $remStmt->execute(); + } else { + // Remove field from the member_updates table. + $remStmt->bindParam(':field', $field, PDO::PARAM_STR); + $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT); + $remStmt->execute(); + } + } + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ updatePhotos() + + /** + * Handle updating any approvals or rejections on the member photos + * + * @param array $photos an array of photo updates and thier update status + * + * @return bool True on success, false on error. + * @access protected + */ + protected function updatePhotos($photos) + { + if (empty($photos)) { + return true; + } + try { + $this->dbh->beginTransaction(); + // Stmt to find the newest request in the updates table for + // a specific field. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + + $fetchStmt = $this->dbh->prepare($sql); + // Stmt to update the photo + $updateSql = " + UPDATE member_photos + SET %s = :update + WHERE id = :id"; + // Stmt to remove photo from member. + $sql = " + DELETE FROM member_photos + WHERE id = :id"; + + $delStmt = $this->dbh->prepare($sql); + // Stmt to remove any caption updates for a photo that + // are still in the updates table. + $sql = " + DELETE FROM {$this->tableName} + WHERE field = 'caption' + AND foreign_key = :id"; + + $delPhotoCaptionStmt = $this->dbh->prepare($sql); + // Remove from updates table. + $sql = " + DELETE FROM {$this->tableName} + WHERE foreign_key = :id + AND field = :field"; + + $remStmt = $this->dbh->prepare($sql); + // Loop through all the photos and see if the update was + // accepted or not. If it was accepted, get the update + // row from the updates table and find out if the update + // was to add [update = 1] the card or remove [update = 0]. + // Perform the update, and then remove the requests from the + // updates table. + foreach ($photos as $field => $accepted) { + list($id, $field) = explode('_', $field, 2); + $fetchStmt->bindParam(':id', $id, PDO::PARAM_INT); + $fetchStmt->execute(); + $row = $fetchStmt->fetch(PDO::FETCH_ASSOC); + + if ($accepted == 'yes') { + $updtStmt = $this->dbh->prepare(sprintf($updateSql, $field)); + // we are dealing w/ the caption + // update the photos caption. + $updtStmt->bindParam(':update', $row['update'], PDO::PARAM_STR); + $updtStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT); + $updtStmt->execute(); + + // Remove field from the member_updates table. + $remStmt->bindParam(':field', $field, PDO::PARAM_STR); + $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT); + $remStmt->execute(); + } else { + // Remove field from the member_updates table. + $remStmt->bindParam(':field', $field, PDO::PARAM_STR); + $remStmt->bindParam(':id', $row['foreign_key'], PDO::PARAM_INT); + $remStmt->execute(); + + // a rejected photo (we know its a photo because it + // has a data_type of boolean) means we have to not only + // remove the row from the updates table, but also + // from the member_photos table. + if ($row['data_type'] == 'boolean') { + $delPhotoCaptionStmt->bindParam( + ':id', + $row['foreign_key'], + PDO::PARAM_STR + ); + $delPhotoCaptionStmt->execute(); + + // Remove the the cards from from the db. + $delStmt->bindParam( + ':id', + $row['foreign_key'], + PDO::PARAM_INT + ); + $delStmt->execute(); + } + } + } + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ validated() + + /** + * Checks if the form is validated + * + * If the form is validated display the success msg. + * If the form is submitted but not validated, display + * the error msg. Other wise display nothing. + * + * This function is called from within the template. + * + * @return string The success or error msg for the user. + * @access protected + */ + public function validated() + { + if ($this->validated) { + return $this->successMsg; + } elseif ($this->isSubmitted()) { + return $this->errorMsg; + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/Auxiliary.php b/Toolkit/Members/Admin/Auxiliary.php new file mode 100644 index 0000000..96b1a6c --- /dev/null +++ b/Toolkit/Members/Admin/Auxiliary.php @@ -0,0 +1,509 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Auxiliary.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Base class used for building forms to accompany the members database + * + * This class handles all common functions that are to be used in + * the auxiliary forms used to assist in the members DB. + * (categories, amenities, regions, etc...). + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_Members, member_admin + */ +abstract class Toolkit_Members_Admin_Auxiliary extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * Primary table used for database calls + * + * @var string + * @access public + */ + public $tableName; + + /** + * Array of primary table meta data + * + * This array will hold the column data types for the fields + * that will be manipulated in the database. + * + * @var array + * @access public + * @see Toolkit_Common::getTableMetaData() + */ + public $tableMetaData; + + /** + * The name of the template used for the form + * + * @var string + * @access protected + */ + protected $formTemplate; + + /** + * The object to use inside the form + * + * This object which is to be populated by the $this object + * is used inside the templates and allows access back into the + * calling class to call publicly available functions + * + * @var string + * @access protected + */ + protected $view; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->registeredRules = array(); + + $this->configureElements(); + $this->configureRules(); + $this->configureFilters(); + $this->configureDefaults(); + + $this->flexyOptions = Toolkit_Members::getFlexyOptions(); + } + + // }}} + + // {{{ baseUrl() + + /** + * Returns the BASE_URL + * + * This function is used inside the Flexy Templated forms + * + * @return string BASE_URL + * @access public + */ + public function baseUrl() + { + return BASE_URL; + } + + // }}} + + // {{{ configureDefaults() + + /** + * Configure the default values for the form + * + * Since each form is different, you will need to redefine this + * method inside of each subclass and create your own rules + * based on your forms elements. + * + * @return void + * @access public + */ + abstract protected function configureDefaults(); + + // }}} + // {{{ configureElements() + + /** + * Configures all form elements + * + * If you are subclassing this base class out, you will need to define + * all your forms elements in your new subclass. + * + * @return void + * @access protected + */ + abstract protected function configureElements(); + + // }}} + // {{{ configureFilters() + + /** + * Defines all filters used on form elements when submitted + * + * Most times this function won't need to be overridden. + * + * @return void + * @access public + */ + protected function configureFilters() + { + $filters[] = array('element' => '__ALL__', 'filter' => 'trim'); + + $this->setupFilters($filters); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up the required / not-required rules for forms + * + * At the bare minimum, the required / not-required rules for form + * needs to be defined. Since these rules are most easily defined + * while creating the element definitions themselves the base function + * is to call the setupRules function that will instantiate these + * rules in the quickform class. + * + * @return void + * @access public + */ + protected function configureRules() + { + $this->setupRules(); + } + + // }}} + + // {{{ getSetParameters() + + /** + * get a string of sql query parameters + * + * @param array $values parameters to include + * + * @return string sql query parameters + * @access protected + */ + protected function getSetParameters($values) + { + $params = array_keys($values); + $length = count($params); + for ($i = 0; $i < $length; ++$i) { + $bindParams .= "{$params[$i]} = :{$params[$i]}"; + if ($i < ($length - 1)) { + $bindParams .= ', '; + } + } + return $bindParams; + } + + // }}} + // {{{ getDataType() + + /** + * gets the datatype of the element + * + * @param string $k name of element + * + * @return string datatype + * @access protected + */ + protected function getDataType($k) + { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + return PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + return PDO::PARAM_BOOL; + } elseif ($metaData == 'double precision') { + return null; + } else { + return PDO::PARAM_STR; + } + } + + // }}} + + // {{{ insertData() + + /** + * insert the data in the DB + * + * @param array $values Submitted form values + * @param string $sql Query to execute to make update + * + * @return void + * @access protected + */ + protected function insertData($values, $sql) + { + try { + $stmt = $this->dbh->prepare($sql); + foreach ($values as $k => $v) { + $dataType = $this->getDataType($k); + $stmt->bindParam(":$k", $values[$k], $dataType); + } + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ isEdit() + + /** + * Determines if we are editing an object or not + * + * If we are ever editing an object, member, category, city, etc... + * There will be the objects DB ID passed along in the url under the + * id key. If we can find this then we know we're editing, if not + * then we are adding. + * + * @return void + * @access public + */ + public function isEdit() + { + return isset($_GET['id']); + } + + // }}} + + // {{{ processData() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return array Return description (if any) ... + * @access protected + */ + protected function processData($values) + { + Toolkit_Common::getTableMetaData(); + + foreach ($values as $k => $v) { + switch ($k) { + case 'uploaded_file_rmv' : + // Don't remove this from the values array. + // we will handle it later. + // we need to have access to this value + // in the insert/update functions. + break; + + case 'MAX_FILE_SIZE' : + unset($values[$k]); + break; + + default : + if (preg_match('/^.+_rmv$/', $k)) { + unset($values[$k]); + } + break; + } + } + + if (isset($_GET['id'])) { + return $this->updateData($values); + } else { + return $this->insertData($values); + } + } + + // }}} + + // {{{ setupElements() + + /** + * Add the form elements defined in your class to a QuickForm + * + * Handles adding singleton elements as well as grouped elements. + * If added elements fail to correctly add to the form, the script + * should die gracefully, telling the user there was a problem. + * + * @param array $elements form element definitions + * + * @throws HTML_QuickForm_Error error raised from QuickForm class. + * @return void + * @access protected + */ + protected function setupElements($elements) + { + $this->formElements = $elements; + foreach ($elements as $e) { + if ($e['type'] != 'group') { + try { + $source =& $this->addElement($e['type'], $e['name'], $e['display'], $e['opts'], $e['att'], $e['val']); + } catch (HTML_QuickForm_Error $e) { + Toolkit_Common::dieGracefully(null, $e); + } + if ($e['type'] == 'advmultiselect') { + $source->setLabel($e['labels']); + } + if ($e['name'] == 'categories') { + $res = $source->loadArray($this->categories); + if (PEAR::isError($res)) { + Toolkit_Common::dieGracefully(null, $res); + } + } + if ($e['type'] == 'header') { + $this->formHeaders[$e['display']] = $e; + } + } elseif (is_array($e['group'])) { + unset($field); + foreach ($e['group'] as $g) { + $field[] =& HTML_QuickForm::createElement($g['type'], $g['name'], $g['display'], $g['opts'], $g['att'], $g['val']); + } + $source =& $this->addGroup($field, $e['name'], $e['label'], $e['seperator'], $e['appendName']); + } + } + } + + // }}} + // {{{ setupRenderers() + + /** + * Sets up the rendering engine for the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $renderer =& new HTML_QuickForm_Renderer_Object(true); + + $this->accept($renderer); + + $this->template =& new HTML_Template_Flexy($this->flexyOptions); + + // Make the view a copy of the $this object + // That way we have access to call functions in + // this class from within the template. + $this->view = $this; + $this->view->form = $renderer->toObject(); + $this->template->compile($this->formTemplate); + } + + // }}} + + // {{{ toHTML() + + /** + * Renders the form for viewing + * + * This function validates the form if needed, and if it successfully + * validates attempts to insert or update the data record. + * If it is unsuccessful, it will return an error to the user + * informing them of what went wrong. + * + * @param string $listPage The page the header should redirect + * to on successful insert or update. + * + * @return string The compiled and filled form template. + * @access public + */ + public function toHTML($listPage = 'index.php') + { + // We need to validate (and freeze if needed) + // before we render the form. That way the + // template knows about any errors on the form. + $this->validated = $this->validate(); + $this->setupRenderers(); + + if ($this->validated) { + $processed = $this->process( + array(&$this, 'processData'), + $this->mergeFiles + ); + if ($processed) { + header("Location: $listPage"); + } else { + $errorMsg = "There was an unexpected error. Please try again later."; + } + } + + return $errorMsg . $this->template->bufferedOutputObject($this->view); + } + + // }}} + + // {{{ updateData() + + /** + * update the data in the DB + * + * @param array $values Submitted form values + * @param string $sql Query to execute to make update + * + * @return boolean result of query + * @access protected + */ + protected function updateData($values, $sql) + { + try { + $stmt = $this->dbh->prepare($sql); + foreach ($values as $k => &$v) { + $dataType = $this->getDataType($k); + $stmt->bindParam(":$k", $v, $dataType); + } + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ validated() + + /** + * Returns form message from validation attempts + * + * @return string validation message + * @access public + */ + public function validated() + { + if ($this->validated) { + return $this->successMsg; + } elseif ($this->isSubmitted()) { + return $this->errorMsg; + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/Controller.php b/Toolkit/Members/Admin/Controller.php new file mode 100755 index 0000000..546681b --- /dev/null +++ b/Toolkit/Members/Admin/Controller.php @@ -0,0 +1,1081 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Controller.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see HTML_Menu + * @see HTML_Menu_DirectRenderer + */ + +require_once 'HTML/Menu.php'; + +/** + * Description for require_once + */ +require_once 'HTML/Menu/DirectRenderer.php'; + +/** + * Description for require_once + */ +require_once 'Members/Admin/Search.php'; + +/** + * Handles calling the appropriate functionality for admin + * + * Controls prepping the functions/classes/objects that will be used + * to populate the page when a user clicks through the nav/subnav structure + * within the members admin area. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_Controller +{ + // {{{ properties + + /** + * Structure of the members main navigation + * @var array + * @access public + */ + public $navStructure = array(); + + /** + * Which module to load into the page + * + * EditMember, EditCity, etc... + * + * @var unknown + * @access public + */ + public $pageModule; + + /** + * How to render the base page layout + * @var string + * @access private + */ + private $_template = 'admin.tpl'; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * Handle some essential setup procedures + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function __construct(PDO $pdo, Config_Container $c) + { + $this->dbh = $pdo; + $this->config = $c; + } + + // }}} + + // {{{ addMember() + + /** + * Call the module to handle adding a new member + * + * @return string New member form + * @access protected + */ + protected function addMember() + { + $member =& new Toolkit_Members(); + return $member->toHtml(); + } + + // }}} + // {{{ amenityScriptsAndStyles() + + /** + * Set the styles and scripts for the amenity pages + * + * @param array &$scripts array for scripts on the page + * @param array &$styles array for styles on the page + * + * @return void + * @access protected + */ + protected function amenityScriptsAndStyles( + array &$scripts, + array &$styles + ) { + switch ($_GET['subCat']) { + case 2 : + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/edit-amenity.js'; + break; + + default : + break; + } + } + + // }}} + // {{{ authorizeNewRequests() + + /** + * Call the module to authorize new member requests submitted from the front end + * + * @return string New member authorization form + * @access protected + */ + protected function authorizeNewRequests() + { + $form = new Toolkit_Members_Admin_AuthorizeNewMemberForm('authorize_form'); + return $form->toHTML(); + } + + // }}} + // {{{ authorizeUpdates() + + /** + * Call the module to authorize any new changes made by members + * + * @return string Authorization form for member updates + * @access protected + */ + protected function authorizeUpdates() + { + $updateForm =& new Toolkit_Members_Admin_AuthorizeUpdates($this->dbh, 'auth_updates'); + $updateForm->setMember($_GET['id']); + $updateForm->configureForm(); + return $updateForm->toHtml(); + } + + // }}} + + // {{{ categoryScriptsAndStyles() + + /** + * Set the styles and scripts for the category pages + * + * @param array &$scripts array for scripts on the page + * @param array &$styles array for styles on the page + * + * @return void + * @access protected + */ + protected function categoryScriptsAndStyles( + array &$scripts, + array &$styles + ) { + switch ($_GET['subCat']) { + // List Categories + case 1 : + default : + $styles[] = GLM_APP_BASE_URL . 'libjs/jsTree/source/tree_component.css'; + $scripts[] = GLM_APP_BASE_URL . 'libjs/jsTree/libjs/css.js'; + $scripts[] = GLM_APP_BASE_URL . 'libjs/jquery.listen.js'; + $scripts[] = GLM_APP_BASE_URL . 'libjs/jsTree/source/tree_component.js'; + $scripts[] = GLM_APP_BASE_URL . 'libjs/jquery.cookie.js'; + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/list-categories.js'; + break; + + // Edit Category + case 2 : + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/edit-category.js'; + break; + } + } + + // }}} + // {{{ cityScriptsAndStyles() + + /** + * Set the styles and scripts for the city pages + * + * @param array &$scripts array for scripts on the page + * @param array &$styles array for styles on the page + * + * @return void + * @access protected + */ + protected function cityScriptsAndStyles( + array &$scripts, + array &$styles + ) { + switch ($_GET['subCat']) { + case 2 : + $scripts[] = BASE_URL . 'fckeditor/fckeditor.js'; + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/edit-city.js'; + break; + + default : + break; + } + } + + // }}} + + // {{{ editAmenity() + + /** + * Call the module to handle editing a members amenities + * + * @return string Amenity editing form + * @access protected + */ + protected function editAmenity() + { + $form = new Toolkit_Members_Admin_EditAmenity($this->dbh, + 'edit_amenity'); + $form->configureForm(); + return $form->toHtml(); + } + + // }}} + // {{{ editCategory() + + /** + * Call the module to handle adding/editing/deleting categories + * + * @return string Category editing form + * @access protected + */ + protected function editCategory() + { + $form = new Toolkit_Members_Admin_EditCategory($this->dbh, + 'edit_category'); + $form->configureForm(); + return $form->toHtml(); + } + + // }}} + // {{{ editCity() + + /** + * Call the module to handle editing the cities allowed for members + * + * @return string City editing form + * @access protected + */ + protected function editCity() + { + $form =& new Toolkit_Members_Admin_EditCity($this->dbh, + 'edit_city'); + $form->setImageServer(new Toolkit_Image_Server()); + $form->configureForm($this->config); + return $form->toHtml(); + } + + // }}} + // {{{ editCounty() + + /** + * Call the module to handle editing the counties allowed for members + * + * @return string County editing form + * @access protected + */ + protected function editCounty() + { + die('not finished'); + $form =& new Toolkit_Members_Admin_EditCounty($this->dbh, + 'edit_city'); + $form->configureForm(); + return $form->toHtml(); + } + + // }}} + // {{{ editHtmlEmail() + + /** + * Call the module to handle editing the counties allowed for members + * + * @return string County editing form + * @access protected + */ + protected function editHtmlEmail() + { + $form =& new Toolkit_Members_Admin_EditHtmlEmail($this->dbh, + 'edit_html_email'); + $form->configureForm(); + return $form->toHtml(); + } + + // }}} + // {{{ editRegion() + + /** + * Call the module to handle editing the regions allowed for members + * + * @return string Region editing form + * @access protected + */ + protected function editRegion() + { + $form =& new Toolkit_Members_Admin_EditRegion($this->dbh, + 'edit_region'); + $form->configureForm(); + return $form->toHtml(); + } + + // }}} + + // {{{ getPageModule() + + /** + * Retrieve the module we are going to need for the page + * + * Page modules are defined in the navigation structure + * + * @return void + * @access public + */ + public function getPageModule() + { + $default = 'homePage'; + $moduleId = $_GET['cat'] . $_GET['subCat']; + /* + if (!is_numeric($moduleId)) { + return false; + } + // Make sure the category id exists. + if (!array_key_exists($_GET['cat'], $this->navStructure)) { + return false; + } + // Make sure the page sub category id exists. + if (is_numeric($_GET['subCat']) && + !array_key_exists($moduleId, $this->navStructure[$_GET['cat']]['sub'])) { + return false; + } + */ + + if (!is_numeric($_GET['subCat'])) { + $function = $this->navStructure[$_GET['cat']]['module']; + } else { + $function = $this->navStructure[$_GET['cat']]['sub'][$moduleId]['module']; + } + + $this->pageModule = isset($function) ? $function : $default; + } + + // }}} + // {{{ _getPageNav() + + /** + * Render the page navigation that is defined in the navStructure + * + * @return string Page navigation structure + * @access private + */ + private function _getPageNav() + { + $menu =& new HTML_Menu($this->navStructure, 'rows'); + + // Default nav index is Home which is at index 1. + $currIndex = 1; + + // If we are on another category id, set that + // category id as the nav index we are on. + if (is_numeric($_GET['cat'])) { + $currIndex = $_GET['cat']; + } + // If we are looking at a subPage, then append + // that subPages id # to the navIndex. + if (is_numeric($_GET['subCat'])) { + $currIndex .= $_GET['subCat']; + } + + // Set which category id we are currently looking at. + $menu->forceCurrentIndex($currIndex); + + $rEngine =& new HTML_Menu_DirectRenderer($tpl); + $rEngine->setEntryTemplate(HTML_MENU_ENTRY_INACTIVE, '
  • {Title}
  • '); + $rEngine->setEntryTemplate(HTML_MENU_ENTRY_ACTIVE, '
  • {Title}
  • '); + $rEngine->setEntryTemplate(HTML_MENU_ENTRY_ACTIVEPATH, '
  • {Title}
  • '); + $rEngine->setMenuTemplate('
    ', '
    '); + $rEngine->setRowTemplate(''); + + $menu->render($rEngine); + return $rEngine->toHtml(); + } + + // }}} + + // {{{ homePage() + + /** + * Call the search box wich is what we will use to populate the home page + * + * @return string Members search box + * @access public + */ + function homePage() + { + $search = new Toolkit_Members_Admin_Search($this->dbh, + 'record_search', + 'get', + BASE_URL . 'admin/members.php?cat=2&subCat=1', + '', + null, + true); + $search->configureForm($this->config); + return $search->toHtml(); + } + + // }}} + + // {{{ initSession() + + /** + * Initializes a session so we can track search results + * + * Allows us to provide links back to search results when a user + * is editing member records + * + * @return void + * @access public + */ + public function initSession() + { + HTTP_Session2::useCookies(false); + HTTP_Session2::start('MemberDB'); + } + + // }}} + + // {{{ listAmenities() + + /** + * Lists all the amenities available to members + * + * @return string list of available amenities + * @access protected + */ + protected function listAmenities() + { + $amenityList = new Toolkit_Members_Admin_ListAmenities($this->dbh); + return $amenityList->renderAmenities(); + } + + // }}} + // {{{ listCategories() + + /** + * Lists all available categories that admin can assign to members + * + * @return string tree structure of member categories in db + * @access protected + */ + protected function listCategories() + { + $categoryList = new Toolkit_Members_Admin_ListCategories($this->dbh); + return $categoryList->renderCategories(); + } + + // }}} + // {{{ listCities() + + /** + * Lists available cities that members can choose from + * + * @return string HTML list of available cities + * @access protected + */ + protected function listCities() + { + $cityList = new Toolkit_Members_Admin_ListCities($this->dbh); + return $cityList->renderCities(); + } + + // }}} + // {{{ listCounties() + + /** + * Lists available counties that members can choose from + * + * @return string HTML list of available counties + * @access protected + */ + protected function listCounties() + { + die('not finished'); + $countyList = new Toolkit_Members_Admin_ListCounties($this->dbh); + return $countyList->renderCounties(); + } + + // }}} + // {{{ listHtmlEmails() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return string Return description (if any) ... + * @access protected + */ + protected function listHtmlEmails() + { + $emailList = new Toolkit_Members_Admin_ListHtmlEmails($this->dbh); + return $emailList->renderHtmlEmails(); + } + + // }}} + // {{{ listMembers() + + /** + * Data Grid of members in the db + * + * @return string Search box for members and datagrid list of members + * @access protected + */ + protected function listMembers() + { + HTTP_Session2::set('newSearch', true); + $search = new Toolkit_Members_Admin_Search($this->dbh, + 'record_search', + 'get', + '', + '', + null, + true); + + $search->configureForm($this->config); + + $membersList = new Toolkit_Members_Admin_ListMembers($this->dbh, 50); + if ($_GET['d'] == 't' && ctype_digit((string) $_GET['id'])) { + $membersList->removeMember($_GET['id']); + } + $membersList->setQuery($this->config); + $membersList->setDefaultSort(array('sort_field' => 'ASC')); + + // rendering engine to use + $rEngine = new Structures_DataGrid_Renderer_Flexy(); + // template options to use for template engine + $tplOpts = Toolkit_Members::getFlexyOptions(); + // templating engine to use + $tEngine = new HTML_Template_Flexy($tplOpts); + $rEngine->setContainer($tEngine); + + return $search->toHtml() . $membersList->toHtml($rEngine); + } + + // }}} + // {{{ listNewMemberRequests() + + /** + * Create a datagrid of new member requests that need to be approved + * + * @return string HTML Datagrid of new member requests + * @access protected + */ + protected function listNewMemberRequests() + { + $nmr = new Toolkit_Members_Admin_ListNewRequests($this->dbh); + $nmr->setQuery(); + $nmr->setDefaultSort(array('member_name' => 'ASC')); + + // rendering engine to use + $rEngine = new Structures_DataGrid_Renderer_Flexy(); + // template options to use for template engine + $tplOpts = Toolkit_Members::getFlexyOptions(); + // templating engine to use + $tEngine = new HTML_Template_Flexy($tplOpts); + $rEngine->setContainer($tEngine); + + return $nmr->toHtml($rEngine); + } + + // }}} + // {{{ listRegions() + + /** + * Render and output the regions + * + * @return string html page of the regions + * @access protected + */ + protected function listRegions() + { + $regionList = new Toolkit_Members_Admin_ListRegions($this->dbh); + return $regionList->renderRegions(); + } + + // }}} + // {{{ listReports() + + /** + * fetch the member reports list + * + * @return string html string of member reports + * @access public + */ + public function listReports() + { + // rendering engine to use + $rEngine = new Structures_DataGrid_Renderer_Flexy(); + // template options to use for flexy template engine + $tplOpts = Toolkit_Members::getFlexyOptions(); + // templating engine to use + $tEngine = new HTML_Template_Flexy($tplOpts); + $rEngine->setContainer($tEngine); + + if (ctype_digit((string) $_REQUEST['member_id'])) { + $detail = new Toolkit_Members_ExposureDetailReports($this->dbh); + $detail->setQuery($_REQUEST['member_id']); + $detail->setDefaultSort(array('month' => 'desc')); + + $out = $detail->toHtml($rEngine); + } + $reports = new Toolkit_Members_ExposureReports($this->dbh); + $reports->setQuery($_REQUEST['reportMonth']); + + $out .= $reports->toHtml($rEngine); + return $out; + } + + // }}} + // {{{ listPendingMembers() + + /** + * Datagrid of pending members with updates + * + * @return HTML Data Grid of members with updates to approve + * @access protected + */ + protected function listPendingMembers() + { + $pml =& new Toolkit_Members_Admin_ListPendingMembers($this->dbh); + $pml->setQuery(); + $pml->setDefaultSort(array('member_name' => 'asc')); + + // rendering engine to use + $rEngine = new Structures_DataGrid_Renderer_Flexy(); + // template options to use for template engine + $tplOpts = Toolkit_Members::getFlexyOptions(); + // templating engine to use + $tEngine = new HTML_Template_Flexy($tplOpts); + $rEngine->setContainer($tEngine); + + return $pml->toHtml($rEngine); + } + + // }}} + + // {{{ memberScriptsAndStyles() + + /** + * Set the styles and scripts for the member pages + * + * @param array &$scripts array for scripts on the page + * @param array &$styles array for styles on the page + * + * @return void + * @access protected + */ + protected function memberScriptsAndStyles( + array &$scripts, + array &$styles + ) { + switch ($_GET['subCat']) { + // List Members + case 1 : + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/member-list.js'; + $styles[] = BASE_URL . 'contactform.css'; + break; + + // Edit Member Record + case 2 : + switch ($_GET['tab']) { + // Member Info + case 1 : + $scripts[] = BASE_URL . 'fckeditor/fckeditor.js'; + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/edit-member.js'; + $scripts[] = GLM_APP_BASE_URL . 'gallery/thickbox-3.1.1.js'; + $scripts[] = GLM_APP_BASE_URL . 'libjs/cluetip/jquery.cluetip.js'; + $scripts[] = GLM_APP_BASE_URL . 'libjs/cluetip/lib/jquery.hoverIntent.js'; + $scripts[] = GLM_APP_BASE_URL . 'libjs/cluetip/lib/jquery.bgiframe.min.js'; + $styles[] = GLM_APP_BASE_URL . 'gallery/thickbox.css'; + $styles[] = GLM_APP_BASE_URL . 'libjs/cluetip/jquery.cluetip.css'; + break; + + // Member Photos + // Member Packages + case 2 : + case 3 : + $scripts[] = GLM_APP_BASE_URL . 'libjs/jqueryui/1.7.1/ui/jquery-ui-1.7.1.custom.js'; + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/edit-member-photos.js'; + break; + + case 4 : + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/edit-member-amenities.js'; + break; + + case 5 : + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/edit-member-files.js'; + break; + + // Contacts + case 6 : + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/edit-member-contacts.js'; + break; + } + break; + + // List Pending Member Records + case 3 : + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/member-pending-list.js'; + if (is_numeric($_GET['id'])) { + $scripts[] = BASE_URL . 'fckeditor/fckeditor.js'; + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/authorizeChanges.js'; + } + break; + + // New Member Requests + case 4 : + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/member-list.js'; + break; + + // Html Emails + case 8 : + break; + + // List Members + default : + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/member-list.js'; + $styles[] = BASE_URL . 'contactform.css'; + break; + } + } + + // }}} + + // {{{ newsletterScriptsAndStyles() + + /** + * Set the styles and scripts for the newsletter + * + * @param array &$scripts array for scripts on the page + * @param array &$styles array for styles on the page + * + * @return void + * @access protected + */ + protected function newsletterScriptsAndStyles( + array &$scripts, + array &$styles + ) { + $styles[] = BASE_URL . 'member-admin.css'; + $styles[] = BASE_URL . 'admin/main.css'; + $styles[] = BASE_URL . 'admin/MContact/banner.css'; + } + + // }}} + // {{{ htmlEmailScriptsAndStyles() + + /** + * Set the styles and scripts for the newsletter + * + * @param array &$scripts array for scripts on the page + * @param array &$styles array for styles on the page + * + * @return void + * @access protected + */ + protected function htmlEmailScriptsAndStyles( + array &$scripts, + array &$styles + ) { + switch ($_GET['subCat']) { + case 2 : + $scripts[] = BASE_URL . 'fckeditor/fckeditor.js'; + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/edit-html-email.js'; + break; + } + } + + // }}} + + // {{{ regionScriptsAndStyles() + + /** + * Set the styles and scripts for the region pages + * + * @param array &$scripts array for scripts on the page + * @param array &$styles array for styles on the page + * + * @return void + * @access protected + */ + protected function regionScriptsAndStyles( + array &$scripts, + array &$styles + ) { + switch ($_GET['subCat']) { + case 2 : + $scripts[] = BASE_URL . 'Toolkit/Members/libjs/edit-region.js'; + break; + + default : + break; + } + } + + // }}} + // {{{ renderPage() + + /** + * Renders the page through flexy rendering engine. + * + * @param HTML_Template_Flexy $tEngine Templating engine to use + * + * @return string HTML page rendered through flexy + * @access public + */ + public function renderPage(HTML_Template_Flexy $tEngine) + { + // get reference to [listing type] section of config file + $config =& $this->config->getItem('section', 'listing type'); + $pluralDirective =& $config->getItem('directive', 'plural'); + $pluralType = $pluralDirective->getContent(); + $pageObject = new stdClass(); + + $pageObject->styles = array( + BASE_URL . 'member-admin.css', + ); + + $pageObject->scripts = array( + GLM_APP_BASE_URL . 'libjs/jquery-1.3.2.min.js', + ); + + if ($_GET['cat'] == 2) { + $this->memberScriptsAndStyles( + $pageObject->scripts, + $pageObject->styles + ); + } elseif ($_GET['cat'] == 3) { + $this->categoryScriptsAndStyles( + $pageObject->scripts, + $pageObject->styles + ); + } elseif ($_GET['cat'] == 4) { + $this->amenityScriptsAndStyles( + $pageObject->scripts, + $pageObject->styles + ); + } elseif ($_GET['cat'] == 5) { + $this->regionScriptsAndStyles( + $pageObject->scripts, + $pageObject->styles + ); + } elseif ($_GET['cat'] == 6) { + $this->cityScriptsAndStyles( + $pageObject->scripts, + $pageObject->styles + ); + } elseif ($_GET['cat'] == 7) { + $this->newsletterScriptsAndStyles( + $pageObject->scripts, + $pageObject->styles + ); + } elseif ($_GET['cat'] == 8) { + $this->htmlEmailScriptsAndStyles( + $pageObject->scripts, + $pageObject->styles + ); + } else { + $pageObject->styles[] = BASE_URL . 'contactform.css'; + } + + + $pageObject->nav = $this->_getPageNav(); + + $function = $this->pageModule; + if (method_exists($this, $function)) { + $pageObject->content = $this->$function(); + } else { + $pageObject->content = $this->homePage(); + } + + if ($_GET['cat'] == 2 && $_GET['subCat'] == 2) { + $pageObject->breadcrumbs = true; + $pageObject->listingType = $pluralType; + $pageObject->searchResults = HTTP_Session2::get('searchResults'); + } + + $tEngine->compile($this->_template); + return $tEngine->bufferedOutputObject($pageObject); + } + + // }}} + + // {{{ setupNavSructure() + + /** + * Sets up a multi dimensional array used for the nav structure + * + * @return mixed false on sql error. otherwise void + * @access public + */ + public function setupNavStructure() + { + // get reference to [listing type] section of config file + $config =& $this->config->getItem('section', 'listing type'); + $singularDirective =& $config->getItem('directive', 'singular'); + $singularType = $singularDirective->getContent(); + $pluralDirective =& $config->getItem('directive', 'plural'); + $pluralType = $pluralDirective->getContent(); + + try { + $sql = " + SELECT count(*) AS total + FROM member_updates"; + + $row = $this->dbh->query($sql)->fetch(); + $pendingClass = $row['total'] ? 'hasPending' : ''; + + $sql = " + SELECT count(*) AS total + FROM member + WHERE new_member"; + + $row = $this->dbh->query($sql)->fetch(); + $newClass = $row['total'] ? 'hasPending' : ''; + + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + $nav = array( + 1 => array('Title' => 'Home', 'url' => BASE_URL . 'admin/members.php', 'desc' => '',), + 2 => array( + 'Title' => $pluralType, + 'url' => BASE_URL . 'admin/members.php?cat=2', + 'desc' => "View and edit $pluralType in the database", + 'module' => 'listMembers', + 'sub' => array( + 21 => array('Title' => "List $pluralType", 'url' => BASE_URL . 'admin/members.php?cat=2&subCat=1', 'desc' => "Show all $pluralType in the database", 'module' => 'listMembers',), + 22 => array('Title' => "Add $singularType Listing", 'url' => BASE_URL . 'admin/members.php?cat=2&subCat=2&tab=1', 'desc' => "Add a $singularType record to the database", 'module' => 'addMember',), + 23 => array('Title' => "Pending $singularType Listing Update", 'url' => BASE_URL . 'admin/members.php?cat=2&subCat=3', 'desc' => "Accept or reject any $singularType record changes", 'module' => ctype_digit((string) $_GET['id']) ? 'authorizeUpdates' : 'listPendingMembers', 'class' => $pendingClass,), + 24 => array('Title' => "New $singularType Requests", 'url' => BASE_URL . 'admin/members.php?cat=2&subCat=4', 'desc' => "Accept or reject any new $singularType requests", 'module' => ctype_digit((string) $_GET['id']) ? 'authorizeNewRequests' : 'listNewMemberRequests', 'class' => $newClass,), + 25 => array('Title' => 'Reports', 'url' => BASE_URL . 'admin/members.php?cat=2&subCat=5', 'desc' => 'View reports on view,detail,or clicks', 'module' => 'listReports'), + ), + ), + 3 => array( + 'Title' => "$singularType Categories", + 'url' => BASE_URL . 'admin/members.php?cat=3', + 'desc' => "View and edit $singularType categories", + 'module' => 'listCategories', + 'sub' => array( + 31 => array('Title' => 'List Categories', 'url' => BASE_URL . 'admin/members.php?cat=3&subCat=1', 'desc' => "Show a list of all $singularType amenities in the databse", 'module' => 'listCategories'), + 32 => array('Title' => 'Add Category', 'url' => BASE_URL . 'admin/members.php?cat=3&subCat=2', 'desc' => "Add a $singularType category to the database", 'module' => 'editCategory'), + ), + ), + 4 => array( + 'Title' => "Amenities", + 'url' => BASE_URL . 'admin/members.php?cat=4', + 'desc' => "View and edit $singularType amenities", + 'module' => 'listAmenities', + 'sub' => array( + 41 => array('Title' => 'List Amenities', 'url' => BASE_URL . 'admin/members.php?cat=4&subCat=1', 'desc' => "Show a list of all $singularType amenities in the database", 'module' => 'listAmenities',), + 42 => array('Title' => 'Add Amenity', 'url' => BASE_URL . 'admin/members.php?cat=4&subCat=2', 'desc' => "Add a $singularType amenity to the database", 'module' => 'editAmenity',), + ), + ), + 5 => array( + 'Title' => "Regions", + 'url' => BASE_URL . 'admin/members.php?cat=5', + 'desc' => "View and edit $singularType regions", + 'module' => 'listRegions', + 'sub' => array( + 51 => array('Title' => 'List Regions', 'url' => BASE_URL . 'admin/members.php?cat=5&subCat=1', 'desc' => "Show a list of all $singularType regions in the database", 'module' => 'listRegions',), + 52 => array('Title' => 'Add Region', 'url' => BASE_URL . 'admin/members.php?cat=5&subCat=2', 'desc' => "Add a $singularType region to the database", 'module' => 'editRegion',), + ), + ), + 6 => array( + 'Title' => "Cities", + 'url' => BASE_URL . 'admin/members.php?cat=6', + 'desc' => "View and edit $singularType cities", + 'module' => 'listCities', + 'sub' => array( + 61 => array('Title' => 'List Cities', 'url' => BASE_URL . 'admin/members.php?cat=6&subCat=1', 'desc' => "Show a list of all $singularType cities in the database", 'module' => 'listCities',), + 62 => array('Title' => 'Add City', 'url' => BASE_URL . 'admin/members.php?cat=6&subCat=2', 'desc' => "Add a $singularType city to the database", 'module' => 'editCity',), + ), + ), + 7 => array( + 'Title' => "Counties", + 'url' => BASE_URL . 'admin/members.php?cat=7', + 'desc' => "View and edit $singularType counties", + 'module' => 'listCounties', + 'sub' => array( + 71 => array('Title' => 'List Counties', 'url' => BASE_URL . 'admin/members.php?cat=7&subCat=1', 'desc' => "Show a list of all $singularType counties in the database", 'module' => 'listCounties',), + 72 => array('Title' => 'Add County', 'url' => BASE_URL . 'admin/members.php?cat=7&subCat=2', 'desc' => "Add a $singularType county to the database", 'module' => 'editCounty',), + ), + ), + 8 => array( + 'Title' => "Newsletter", + 'url' => BASE_URL . 'admin/members.php?cat=8', + 'desc' => "Prepare a $singularType newsletter mailing", + 'module' => 'listHtmlEmails', + 'sub' => array( + 81 => array('Title' => 'HTML Emails', 'url' => BASE_URL . 'admin/members.php?cat=8&subCat=1', 'desc' => 'View and edit HTML email templates to use in the newsletter', 'module' => 'listHtmlEmails',), + 82 => array('Title' => 'Add HTML Email', 'url' => BASE_URL . 'admin/members.php?cat=8&subCat=2', 'desc' => 'View and edit HTML email templates to use in the newsletter', 'module' => 'editHtmlEmail',), + //83 => array('Title' => $singularType . ' Subscriptions', 'url' => BASE_URL . 'admin/members.php?cat=8&subCat=4', 'desc' => '', 'module' => 'memberSubscriptions',), + ), + ), + ); + + // get reference to [conf] section of config file + $config =& $this->config->getItem('section', 'conf'); + + // get region + $directive =& $config->getItem('directive', 'regions'); + if (!$directive->getContent()) { + unset($nav[5]); + } + // get coupons + $directive =& $config->getItem('directive', 'coupons'); + if (!$directive->getContent()) { + unset($nav['Coupons']); + } + // get controlled cities + $directive =& $config->getItem('directive', 'controlledCities'); + if (!$directive->getContent()) { + unset($nav[6]); + } + // get counties + $directive =& $config->getItem('directive', 'counties'); + if (!$directive->getContent()) { + unset($nav[7]); + } + // get amenities + $directive =& $config->getItem('directive', 'amenities'); + if (!$directive->getContent()) { + unset($nav[4]); + } + + // get new member requests + $directive =& $config->getItem('directive', 'newMemberRequests'); + if (!$directive->getContent()) { + unset($nav[2]['sub']['24']); + } + + $this->navStructure = $nav; + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/EditAmenity.php b/Toolkit/Members/Admin/EditAmenity.php new file mode 100644 index 0000000..b8859ae --- /dev/null +++ b/Toolkit/Members/Admin/EditAmenity.php @@ -0,0 +1,350 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditAmenity.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Handles creating / editing amenities that the members will use + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_EditAmenity + extends Toolkit_Members_Auxiliary implements Toolkit_Form +{ + // {{{ properties + + /** + * Description for public + * @var string + * @access public + */ + public $tableName = 'amenity'; + + /** + * Description for protected + * @var string + * @access protected + */ + protected $formTemplate = 'editAmenity.tpl'; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + } + + // }}} + + // {{{ checkAmenityName() + + /** + * Check that the amenity name is not in use already + * + * @param string $name name to check + * + * @return boolean if the name is valid or not + * @access public + */ + public function checkAmenityName($name) + { + try { + // If we're editing a amenity, they + // can save that amenity as its + // own name. so don't include that + // amenity in the check. + if (isset($_GET['id'])) { + $and = "AND amenity_id != :id"; + } + $sql = " + SELECT count(*) AS total + FROM {$this->tableName} + WHERE amenity_name = :name + $and"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':name', $name, PDO::PARAM_STR); + if (isset($_GET['id'])) { + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_STR); + } + $stmt->execute(); + $stmt->bindColumn('total', $total); + $stmt->fetch(); + + return !(bool) $total; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureDefaults() + + /** + * Set up the default values for the form + * + * @return void + * @access public + */ + public function configureDefaults() + { + $d = array(); + + if (isset($_GET['id'])) { + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE amenity_id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $d = $stmt->fetch(); + } catch (PDOException $e) { + $this->handleError($e); + } + } + + $this->setupDefaults($d); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + // All Grouped Elements are created here. + + // All Elements are created here. + // This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'AmenityInfoHdr', + 'display' => 'Member Amenities' + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'display_form', + 'display' => 'Display on Form', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'amenity_name', + 'display' => 'Amenity Name' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureForm() + + /** + * Helper function to configure an entire form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureRules(); + $this->configureDefaults(); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + + $r[] = array( + 'element' => 'amenity_name', + 'message' => 'ERROR: Amenity already exists!', + 'type' => 'callback', + 'format' => array($this, 'checkAmenityName'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ deleteAmenity() + + /** + * Remove a region from the db + * + * @param integer $id region id + * + * @return boolean result of db query + * @access protected + */ + protected function deleteAmenity($id) + { + if (!is_numeric($id)) { + return false; + } + try { + $sql = " + DELETE FROM {$this->tableName} + WHERE amenity_id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + + return $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertData() + + /** + * Create a new amenity + * + * @param array $values Submitted form values + * + * @return boolean Result of insertion into DB + * @access protected + */ + protected function insertData($values) + { + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + try { + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ updateData() + + /** + * Update the data for an amenity + * + * @param array $values submitted form results + * + * @return boolean result of sql update query + * @access protected + */ + protected function updateData($values) + { + // We aren't updating a region, we're deleting it. + if (array_key_exists('delete', $values)) { + return $this->deleteAmenity($_GET['id']); + } + + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('amenity_id = :id') + ); + + $values['id'] = $_GET['id']; + try { + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ toHTML() + + /** + * Renders the form for viewing + * + * This function validates the form if needed, and if it successfully + * validates attempts to insert or update the data record. + * If it is unsuccessful, it will return an error to the user + * informing them of what went wrong. + * + * @return string The compiled and filled form template. + * @access public + */ + public function toHtml() + { + $listPage = BASE_URL . 'admin/members.php?cat=4&subCat=1'; + return parent::toHtml($listPage); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/EditCategory.php b/Toolkit/Members/Admin/EditCategory.php new file mode 100644 index 0000000..863d3b2 --- /dev/null +++ b/Toolkit/Members/Admin/EditCategory.php @@ -0,0 +1,484 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditCategory.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Edit categories used within the member database + * + * Controls all aspects of creating and rendering the form used to manipulate + * the member categories. Handles both adding / editing category + * details, including: + * + * 1. Modules associated with a category. + * 2. Updating sub-categories to mirror parent category module settings. + * 3. Removal of top level categories that contain sub-level categories. + * see (deleteCategory()) + * + * Once categories are added, they are not allow to be moved to another parent. + * This keeps the updating to a minimum and elminates logic that would be + * caused by this move: (maintaining category-module settings after the move). + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_Members, member_admin + */ + +class Toolkit_Members_Admin_EditCategory + extends Toolkit_Members_Auxiliary implements Toolkit_Form +{ + // {{{ properties + + /** + * The table name in the database used to store the data of the categories + * + * @var string + * @access public + */ + public $tableName = 'category'; + + /** + * The template used to render the form + * + * @var string + * @access protected + */ + protected $formTemplate = 'editCategory.tpl'; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + } + + // }}} + + // {{{ configureDefaults() + + /** + * Sets the defaults for elements in the form. + * + * @return void + * @access public + */ + public function configureDefaults() + { + if (isset($_GET['id'])) { + try { + $sql = " + SELECT * + FROM category + WHERE category_id = :cid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':cid', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $category = $stmt->fetch(PDO::FETCH_ASSOC); + $defaults = array( + 'category_id' => $category['category_id'], + 'name' => $category['name'], + //'parent_id' => $category['parent_id'], + 'accommodations' => $category['accommodations'], + 'restaurant' => $category['restaurant'], + 'golf' => $category['golf'], + ); + } catch (PDOException $e) { + $this->handleError($e); + } + } + + $this->setupDefaults($defaults); + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * Categories are populated into the protected class property $categories. + * These categories are used to populate the select list of categories. + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'categoryInfoHdr', + 'display' => 'Member Categories' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'name', + 'display' => 'Category Name' + ); + if (!isset($_GET['id'])) { + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'parent_id', + 'display' => 'Parent', + 'opts' => array(0 => 'No Parent (top level)'), + 'att' => array('id' => 'categories') + ); + } + + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'accommodations', + 'display' => 'Is Accommodation Category', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'restaurant', + 'display' => 'Is Restaurant Category', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'golf', + 'display' => 'Is Golfing Category', + 'val' => array(0, 1) + ); + + $this->setupElements($e); + $this->loadMemberCategories(); + } + + // }}} + // {{{ configureForm() + + /** + * Helper function to configure an entire form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureDefaults(); + $this->configureRules(); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + + $this->setupRules($r); + } + + // }}} + + // {{{ deleteCategory() + + /** + * Removes a category from the database + * + * All first level sub-categories will become main level categories + * and will hold the structure of any sub-categories beneath them. + * + * @param int $id The category_id of the category you wish to remove. + * + * @return bool False on SQL error, otherwise true. + * @access protected + */ + protected function deleteCategory($id) + { + if (!is_numeric($id)) { + return false; + } + + try { + $sql = " + UPDATE {$this->tableName} + SET parent_id = 0 + WHERE parent_id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + + $sql = " + DELETE FROM {$this->tableName} + WHERE category_id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + return $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertData() + + /** + * Create a new category + * + * @param array $values Submitted form values + * + * @return boolean Result of insertion into DB + * @access protected + */ + protected function insertData($values) + { + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + try { + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ loadMemberCategories() + + /** + * Loads member categories into the select list + * + * Gets an array structure of the member categories in a linear tree order + * Then walk through the array and load each category into the select list + * + * @return void + * @access protected + */ + protected function loadMemberCategories() + { + if (!$this->elementExists('parent_id')) { + return; + } + try { + // 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( + 'category', + 'category_id', + 'parent_id' + ); + + // Get all the data about each category + $sql = " + SELECT * + FROM category + WHERE category_id = ?"; + + $stmt = $this->dbh->prepare($sql); + // Get the member categories select list element + $e =& $this->getElement('parent_id'); + foreach ($c as $i => $j) { + $stmt->execute(array($i)); + $row = $stmt->fetch(); + // the class level is always 1 less than what is reported + // from our $c array + $x = $j - 1; + // Add the option data to the select list. + $e->addOption($row['name'], $i, array('class' => "level-$x")); + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. Calls the Auxiliary base class function to handle + * the rendering. + * + * @return string The rendered form + * @access public + */ + public function toHtml() + { + $listPage = BASE_URL . 'admin/members.php?cat=3&subCat=1'; + return parent::toHtml($listPage); + } + + // }}} + + // {{{ updateChildren() + + /** + * Recusively updates all sub-categories to mirror the top category + * + * @param array $values The array of settings to update and the parent + * id so you can find the children. + * + * @return bool false on error, otherwise true. + * @access protected + */ + protected function updateChildren($values) + { + try { + $sql = " + SELECT * + FROM connectby('category', 'category_id', 'parent_id', + 'pos', :cid, 0) + AS t(id text, parent text, level int, pos int)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':cid', $_GET['id'], PDO::PARAM_STR); + $stmt->execute(); + + while ($row = $stmt->fetch()) { + $children[] = $row; + } + // If we actually got some subcategories, + // update their settings and check to see + // if they have any subcategories we can update. + if (is_array($children)) { + $sql = " + UPDATE {$this->tableName} + SET accommodations = :accommodations, + restaurant = :restaurant, + golf = :golf + WHERE category_id = :category_id"; + + $stmt = $this->dbh->prepare($sql); + foreach ($children as $k => &$v) { + $stmt->bindParam('category_id', $v['id'], PDO::PARAM_INT); + $stmt->bindParam( + 'accommodations', + $values['accommodations'], + PDO::PARAM_BOOL + ); + $stmt->bindParam( + 'restaurant', + $values['restaurant'], + PDO::PARAM_BOOL + ); + $stmt->bindParam('golf', $values['golf'], PDO::PARAM_BOOL); + $stmt->execute(); + } + return true; + } else { + // Otherwise we got no subcategories + return true; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ updateData() + + /** + * Update the settings for this category + * + * Any modules that are assigned to this category will be updated. + * And if this category has any sub-categories, those childrens + * module settings will be updated to mirror this categories settings. + * + * @param array $values Values submitted from the form + * + * @return bool false on sql error, otherwise true. + * @access protected + */ + protected function updateData($values) + { + // We aren't updating a region, we're deleting it. + if (array_key_exists('delete', $values)) { + return $this->deleteCategory($_GET['id']); + } + + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('category_id = :id') + ); + + $values['id'] = $_GET['id']; + try { + Toolkit_Common::processQuery($this->dbh, $sql, $values); + return $this->updateChildren($values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/EditCity.php b/Toolkit/Members/Admin/EditCity.php new file mode 100644 index 0000000..6307396 --- /dev/null +++ b/Toolkit/Members/Admin/EditCity.php @@ -0,0 +1,643 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditCity.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Edit cities in the member database + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditCity.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://devsys2.gaslightmedia.com/demo.gaslightmedia.com/admin/members.php?cat=6 + */ +class Toolkit_Members_Admin_EditCity + extends Toolkit_Members_Auxiliary implements Toolkit_Form +{ + // {{{ properties + + /** + * Table name in DB + * @var string + * @access public + */ + public $tableName = 'city'; + + /** + * Form template + * @var string + * @access protected + */ + protected $formTemplate = 'editCity.tpl'; + + /** + * Image Server + * @var object + * @access protected + */ + protected $is; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + } + + // }}} + + // {{{ checkCityName() + + /** + * Check that the city name is not in use already + * + * @param string $name name to check + * + * @return boolean if the name is valid or not + * @access public + */ + public function checkCityName($name) + { + try { + // If we're editing a city, they + // can save that city as its + // own name. so don't include that + // city in the check. + if (isset($_GET['id'])) { + $and = "AND city_id != :id"; + } + $sql = " + SELECT COUNT(*) AS total + FROM {$this->tableName} + WHERE city_name = :name + $and"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':name', $name, PDO::PARAM_STR); + if (isset($_GET['id'])) { + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_STR); + } + $stmt->execute(); + $stmt->bindColumn('total', $total); + $stmt->fetch(); + + return !(bool) $total; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureDefaults() + + /** + * Set up the default values for the form + * + * @return void + * @access public + */ + public function configureDefaults() + { + if (isset($_GET['id'])) { + try { + $sql = " + SELECT * + FROM city + WHERE city_id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $city = $stmt->fetch(PDO::FETCH_ASSOC); + $defaults = array( + 'city_name' => $city['city_name'], + 'region_id' => $city['region_id'], + 'state_id' => $city['state_id'], + 'description' => $city['description'], + 'image_rmv' => "", + 'uploaded_file_rmv' => $city['image'], + ); + + // If the user is editing a city, and no image has been uploaded yet. + // there is no point in showing an empty "current image" field, so remove + // that element from the form. + if (empty($city['image']) && !$this->isSubmitted()) { + $this->removeElement('image_rmv', false); + $this->removeElement('remove_image', false); + } + } catch (PDOException $e) { + $this->handleError($e); + } + } + + $this->setupDefaults($defaults); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function configureElements(Config_Container $c) + { + $e = array(); + // get reference to [listing type] section of config file + $config =& $c->getItem('section', 'conf'); + $regionDirective =& $config->getItem('directive', 'regions'); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'cityInfoHdr', + 'display' => 'Member Cities' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'city_name', + 'display' => 'City' + ); + if ($regionDirective->getContent()) { + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'region_id', + 'display' => 'Region', + 'opts' => $this->getRegions(), + ); + } + $e[] = array( + 'type' => 'select', + 'req' => true, + 'name' => 'state_id', + 'display' => 'State', + 'opts' => array('' => '-- Select --') + Toolkit_Common::getStates($this->dbh), + ); + // If we're editing a city, show the current + // city image in the form. + if ($this->_hasImage()) { + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'remove_image_rmv', + 'display' => 'Remove Image' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'image_rmv', + 'display' => 'Current Image' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'old_image_rmv' + ); + } + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'new_image_rmv', + 'display' => 'New Image', + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'display' => 'Description', + 'opts' => array( + 'id' => 'description', + 'rows' => 7, + 'cols' => 45 + ) + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureForm() + + /** + * Helper function to configure an entire form + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function configureForm(Config_Container $c) + { + $this->configureElements($c); + $this->configureRules(); + $this->configureDefaults(); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + + $mimeTypes = array( + 'image/jpe', + 'image/jpeg', + 'image/jpg', + 'image/jfif', + 'image/pjpeg', + 'image/pjp', + 'image/gif', + 'image/png', + ); + + $r[] = array( + 'element' => 'new_image_rmv', + 'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!', + 'type' => 'mimetype', + 'format' => $mimeTypes, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'city_name', + 'message' => 'ERROR: City already exists!', + 'type' => 'callback', + 'format' => array($this, 'checkCityName'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ deleteCity() + + /** + * Delete city from db + * + * @param integer $id city id + * + * @return boolean result of removing city + * @access protected + */ + protected function deleteCity($id) + { + $city = new Toolkit_Members_City($this->dbh); + return $city->deleteCity($id); + } + + // }}} + + // {{{ getRegions() + + /** + * Get the regions stored in the DB + * + * @return array regions + * @access protected + */ + protected function getRegions() + { + try { + $sql = " + SELECT * + FROM region + ORDER BY region_name"; + foreach ($this->dbh->query($sql) as $row) { + $regions[$row['region_id']] = $row['region_name']; + } + if (!empty($regions)) { + $regions = array('' => '-- Select --') + $regions; + } else { + $regions = array('' => '-- No Regions Created Yet --'); + } + + return $regions; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ _hasImage() + + /** + * Determine if the city record has a image + * + * @return boolean if the record has a image or not + * @access private + */ + private function _hasImage() + { + try { + if (!is_numeric($_GET['id'])) { + return false; + } + + $sql = " + SELECT image + FROM {$this->tableName} + WHERE city_id = :city_id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':city_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(); + + $hasLogo = !is_null($row['image']); + + return $hasLogo; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertData() + + /** + * Create a new city + * + * @param array $values Submitted form values + * + * @return boolean Result of insertion into DB + * @access protected + */ + protected function insertData($values) + { + $city = new Toolkit_Members_City($this->dbh); + $city->setName($values['city_name']); + $city->setState($values['state_id']); + $city->setRegion($values['region_id']); + $city->setImage($values['image']); + $city->setDescription($values['description']); + + return $city->createNewCity(); + } + + // }}} + + // {{{ processData() + + /** + * clean unneeded form elements out of the submitted values array + * + * @param array $values QuickForm submitted elements + * + * @return boolean Result of insert/update functions + * @access public + */ + public function processData($values) + { + $this->processImage(&$values); + + foreach ($values as $k => $v) { + switch ($k) { + case 'MAX_FILE_SIZE' : + unset($values[$k]); + break; + + default : + if (substr($k, -4) == '_rmv') { + unset($values[$k]); + } + break; + } + } + + $function = is_numeric($_GET['id']) ? 'updateData' : 'insertData'; + return $this->$function($values); + } + + // }}} + // {{{ processImage() + + /** + * create or update city images + * + * @param array $values submitted form values + * + * @return object Return description (if any) ... + * @access protected + */ + protected function processImage($values) + { + // Keep a tidy house. + // There are 2 scenarios to deal w/ images: + // 1. Removing image: + // Delete the image from the image server + // and set the values['image'] to null. + // 2. New image: + // Check to see if old_image_rmv holds a value, + // if it does then remove that image + // Upload the image and put new filename + // into values['image'] variable. + $imgServer = new Toolkit_Image_Server(); + + if ($values['remove_image_rmv'] == 1) { + $imgServer->imageDelete($values['old_image_rmv']); + $values['image'] = null; + } + + // If a new image is uploaded, have the image server + // process that image and give us back the file name on + // the server. + if ($values['new_image_rmv']['size'] > 0) { + $imgName = $imgServer->imageUpload('new_image_rmv'); + $values['image'] = $imgName; + $img = ''. $imgName . ''; + + // If the old_image_rmv key is set and not empty + // then we are replacing an existing image and did not + // check the remove image checkbox. + // remove this old image just for good house keeping. + if (isset($values['old_image_rmv']) && !empty($values['old_image_rmv'])) { + $imgServer->imageDelete($values['old_image_rmv']); + // update the elements on the form if we are replacing an existing image. + if ($this->elementExists('old_image_rmv')) { + $e =& $this->getElement('old_image_rmv'); + $e->setValue($imgName); + } + if ($this->elementExists('image_rmv')) { + $e =& $this->getElement('image_rmv'); + $e->setValue($img); + } + } else { + $source =& $this->createElement( + 'checkbox', + 'remove_image_rmv', + 'Remove Logo' + ); + $this->insertElementBefore($source, 'new_image_rmv'); + + $source =& $this->addElement('hidden', 'old_image_rmv'); + $source->setValue($imgName); + + $source =& $this->createElement( + 'static', + 'image_rmv', + 'Current Logo' + ); + $source->setValue($img); + $element = $this->insertElementBefore($source, 'new_image_rmv'); + + if (PEAR::isError($element)) { + die ('there was an error uploading your file!'); + } else { + // I don't know why, but the insertElementBefore + // function was erasing the value we set earlier. + // so just reset it to make double sure its there. + $element->setValue($img); + } + } + } + + // We clicked to remove the image and did not upload a new one. + if ($values['remove_image_rmv'] == 1 && $values['new_image_rmv']['size'] == 0) { + if ($this->elementExists('remove_image_rmv')) { + $this->removeElement('remove_image_rmv', false); + } + if ($this->elementExists('image_rmv')) { + $this->removeElement('image_rmv', false); + } + if ($this->elementExists('old_image_rmv')) { + $this->removeElement('old_image_rmv', false); + } + } + } + + // }}} + + // {{{ setImageServer() + + /** + * Set the image server object to use + * + * @param Toolkit_Image_Server $is Image Server Object + * + * @return void + * @access public + */ + public function setImageServer(Toolkit_Image_Server $is) + { + $this->is = $is; + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form for viewing + * + * This function validates the form if needed, and if it successfully + * validates attempts to insert or update the data record. + * If it is unsuccessful, it will return an error to the user + * informing them of what went wrong. + * + * @return string The compiled and filled form template. + * @access public + */ + public function toHtml() + { + $listPage = BASE_URL . 'admin/members.php?cat=6&subCat=1'; + return parent::toHtml($listPage); + } + + // }}} + + // {{{ updateData() + + /** + * Update the data for a region + * + * @param array $values submitted form results + * + * @return boolean result of sql update query + * @access protected + */ + protected function updateData($values) + { + // We aren't updating a region, we're deleting it. + if (array_key_exists('delete', $values)) { + return $this->deleteCity($_GET['id']); + } + + $city = new Toolkit_Members_City($this->dbh); + $city->setName($values['city_name']); + $city->setState($values['state_id']); + $city->setRegion($values['region_id']); + $city->setImage($values['image']); + $city->setDescription($values['description']); + + return $city->updateCity($_GET['id']); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/EditHtmlEmail.php b/Toolkit/Members/Admin/EditHtmlEmail.php new file mode 100644 index 0000000..cf9dfa4 --- /dev/null +++ b/Toolkit/Members/Admin/EditHtmlEmail.php @@ -0,0 +1,356 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditHtmlEmail.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Handles creating / editing amenities that the members will use + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_EditHtmlEmail + extends Toolkit_Members_Auxiliary implements Toolkit_Form +{ + // {{{ properties + + /** + * Description for public + * @var string + * @access public + */ + public $tableName = 'news_response'; + + /** + * Description for protected + * @var string + * @access protected + */ + protected $formTemplate = 'editHtmlEmail.tpl'; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + } + + // }}} + + // {{{ checkAmenityName() + + /** + * Check that the amenity name is not in use already + * + * @param string $name name to check + * + * @return boolean if the name is valid or not + * @access public + */ + public function checkSubjectName($name) + { + try { + // If we're editing a amenity, they + // can save that amenity as its + // own name. so don't include that + // amenity in the check. + if (isset($_GET['id'])) { + $and = "AND id != :id"; + } + $sql = " + SELECT count(*) AS total + FROM {$this->tableName} + WHERE subject = :name + $and"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':name', $name, PDO::PARAM_STR); + if (isset($_GET['id'])) { + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_STR); + } + $stmt->execute(); + $stmt->bindColumn('total', $total); + $stmt->fetch(); + + return !(bool) $total; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureDefaults() + + /** + * Set up the default values for the form + * + * @return void + * @access public + */ + public function configureDefaults() + { + $d = array(); + + if (isset($_GET['id'])) { + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $d = $stmt->fetch(); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + $this->setupDefaults($d); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + // All Grouped Elements are created here. + + // All Elements are created here. + // This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'HtmlEmailInfoHdr', + 'display' => 'Html Newsletters' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'subject', + 'display' => 'Email Subject' + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'response', + 'display' => 'Email Body', + 'opts' => array( + 'id' => 'response', + 'rows' => 7, + 'cols' => 45 + ) + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureForm() + + /** + * Helper function to configure an entire form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureRules(); + $this->configureDefaults(); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + + $r[] = array( + 'element' => 'subject', + 'message' => 'ERROR: Amenity already exists!', + 'type' => 'callback', + 'format' => array($this, 'checkSubjectName'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ deleteAmenity() + + /** + * Remove a region from the db + * + * @param integer $id region id + * + * @return boolean result of db query + * @access protected + */ + protected function deleteHtmlEmail($id) + { + if (!is_numeric($id)) { + return false; + } + try { + $sql = " + DELETE FROM {$this->tableName} + WHERE id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + + return $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertData() + + /** + * Create a new amenity + * + * @param array $values Submitted form values + * + * @return boolean Result of insertion into DB + * @access protected + */ + protected function insertData($values) + { + $values['last_update'] = date('m/d/Y'); + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + try { + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ updateData() + + /** + * Update the data for an amenity + * + * @param array $values submitted form results + * + * @return boolean result of sql update query + * @access protected + */ + protected function updateData($values) + { + $values['last_update'] = date('m/d/Y'); + // We aren't updating a region, we're deleting it. + if (array_key_exists('delete', $values)) { + return $this->deleteHtmlEmail($_GET['id']); + } + + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('id = :id') + ); + + $values['id'] = $_GET['id']; + try { + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ toHTML() + + /** + * Renders the form for viewing + * + * This function validates the form if needed, and if it successfully + * validates attempts to insert or update the data record. + * If it is unsuccessful, it will return an error to the user + * informing them of what went wrong. + * + * @return string The compiled and filled form template. + * @access public + */ + public function toHtml() + { + $listPage = BASE_URL . 'admin/members.php?cat=8&subCat=1'; + return parent::toHtml($listPage); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/EditPackages.php b/Toolkit/Members/Admin/EditPackages.php new file mode 100644 index 0000000..0e9b4d4 --- /dev/null +++ b/Toolkit/Members/Admin/EditPackages.php @@ -0,0 +1,1523 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditPackages.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see Toolkit/Image/Server.php + */ + + +/** + * The image server processing class + */ +require_once BASE . 'Toolkit/Image/Server.php'; + +/** + * Constructor class to setup the page layout + * + * this class determines if the user can upload any more packages to their + * account and if so renders the add package form. It also controls + * rending the individual forms for each previously uploaded package. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_EditPackages +{ + // {{{ properties + + /** + * The table name in the database used to store the data + * @var string + * @access public + */ + public $tableName = 'member_packages'; + + /** + * Template used to layout form when editing a package + * @var string + * @access protected + */ + protected $pageTemplate = 'editPackages.tpl'; + + /** + * Sets the max number of packages allowed for each listing + * @var integer + * @access protected + */ + protected $maxPackages = 2; + + /** + * What is the maximum caption length for packages + * + * @var array + * @access public + * @static + */ + static public $maxTitleLength = 60; + + /** + * Objects that will go into the page (add form, edit package forms) + * @var object + * @access protected + */ + protected $page; + + /** + * Description for protected + * @var unknown + * @access protected + */ + protected $dbh; + + // }}} + + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param HTML_Template_Flexy $tEngine Templating Engine + * + * @return void + * @access public + */ + public function __construct(PDO $pdo, HTML_Template_Flexy $tEngine) + { + $this->dbh = $pdo; + $this->tEngine = $tEngine; + } + + // }}} + + // {{{ canAddPackages() + + /** + * Determine if this member can have more packages added to their profile + * + * Load the entire package gallery into member via a linked list. + * Then return if the # of linked list nodes is smaller than + * the maximum limit of packages. + * + * @access protected + * @return boolean If the linked list is smaller than max packages allowed + */ + protected function canAddPackages() + { + $ll = new Toolkit_Members_Packages(null, $_GET['id']); + $ll->setDbh($this->dbh); + $ll->createMemberList(); + return ($ll->getListSize() < $this->maxPackages); + } + + // }}} + + // {{{ displayPage() + + /** + * Displays the page to the screen + * + * @param Toolkit_Members_RecordNavigation $nav Record subnav object + * + * @return void + * @access public + */ + public function displayPage(Toolkit_Members_RecordNavigation $nav) + { + echo $this->getPage($nav); + } + + // }}} + + // {{{ getPage() + + /** + * Sets up the flexy template and returns the rendered page + * + * @param Toolkit_Members_RecordNavigation $nav record subnav object + * + * @return object rendered page + * @access public + */ + public function getPage(Toolkit_Members_RecordNavigation $nav) + { + $this->page->nav = $nav->getPageNav(); + $this->tEngine->compile($this->pageTemplate); + return $this->tEngine->bufferedOutputObject($this->page); + } + + // }}} + + // {{{ getUploadedPackages() + + /** + * Get an array of package ids from the DB that have been uploaded for this member + * + * - Create a linked list of all the members packages + * - Walk through the linked list extracting the id from each node into an array + * + * @access protected + * @return array Ids of all uploaded packages for this member + */ + protected function getUploadedPackages() + { + $packages = new Toolkit_Members_Packages(null, $_GET['id']); + $packages->setDbh($this->dbh); + $packages->createMemberList(); + $packages->rewind(); + + $ids = array(); + foreach ($packages as $i) { + // Don't show the pending packages here. + if (!$i->getPending()) { + $ids[] = $i->getId(); + } + } + + return $ids; + } + + // }}} + + // {{{ setUpPage() + + /** + * Sets up the page to manipulate packages for a member + * + * Checks if all the packages uploaded for a member (pending & non-pending) + * exceed or match the maximum # of packages allowed for each member to + * upload to their account. + * + * For every package that is already uploaded, create an edit-package form that + * will allow the user to update the caption or delete the package. + * + * @return void + * @access public + */ + public function setUpPage() + { + $this->page = new StdClass; + + // Find out if we can still add packages to the record. + // If we can, then add the upload form to the page for the member to see. + if ($this->canAddPackages()) { + $addForm = new AddAdminPackage($this->dbh, + 'new_member_package', + 'post', + '', + '', + null, + true); + + $addForm->configureForm(); + $this->page->uploadForm = $addForm->toHtml($this->tEngine); + } + + // Find out if we have any packages already uploaded. + // If we do, then add the edit package form to the page for each package + // so the member can edit/delete their packages. + if ($packages = $this->getUploadedPackages()) { + $this->page->editForm = array(); + while (list($i, $j) = each($packages)) { + $editForm = new EditAdminPackage($this->dbh, + "edit_member_package_$j", + 'post', + '', + '', + array('id' => $j), + true); + + $editForm->configureForm(); + $this->page->editForm[] = $editForm->toHtml($this->tEngine); + } + } + } + + // }}} +} + +/** + * Form to handle creating a new package in the members only area + * + * Handles inserting new package into db as a pending package and creating a + * tuple in the member_updates table which will allow the admin to + * approve/deny the new package request. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class AddAdminPackage extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * The table name in the database used to store the data + * + * @var string + * @access public + */ + public $tableName = 'member_packages'; + + /** + * The template used to render the form + * + * @var string + * @access protected + */ + protected $formTemplate = 'addPackage.tpl'; + + /** + * Description for protected + * @var array + * @access protected + */ + protected $registeredRules = array(); + + /** + * Description for protected + * @var string + * @access protected + */ + protected $successMsg + = '
    + You successfully uploaded your package. +
    '; + + /** + * Description for protected + * @var array + * @access protected + */ + protected $mimeTypes = array( + 'image/jpe', + 'image/jpeg', + 'image/jpg', + 'image/jfif', + 'image/pjpeg', + 'image/pjp', + 'image/gif', + 'image/png', + ); + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional) Form's method defaults to 'POST' + * @param string $action (optional) Form's action. + * @param string $target (optional) Form's target defaults to '_self' + * @param mixed $attributes (optional) Extra attributes for tag. + * @param bool $trackSubmit (optional) Whether to track if the form was + * submitted by adding a special hidden + * field. + * + * @access public + * @see Toolkit_Members_Admin_EditPackages + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->dbh = $pdo; + } + + // }}} + + // {{{ configureForm() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'title', + 'display' => 'Package Title', + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'display' => 'Package Description', + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'sdate', + 'display' => 'Start Date', + 'opts' => array( + 'format' => 'm / d / Y', + 'minYear' => date('Y'), + 'maxYear' => date('Y') + 10, + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy', + ), + ) + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'edate', + 'display' => 'End Date', + 'opts' => array( + 'format' => 'm / d / Y', + 'minYear' => date('Y'), + 'maxYear' => date('Y') + 10, + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy', + ), + ) + ); + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'remove_img_rmv', + 'display' => 'Remove Image', + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'curr_image', + 'display' => 'Current Image', + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'curr_image_rmv', + ); + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'image', + 'display' => 'Upload a Package Photo / Image', + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'add_rmv', + 'display' => 'Upload new package', + 'opts' => array('class' => 'submit') + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureRules() + + /** + * Configure rules for form + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + + $checkDate = create_function('$d', '$d = implode("-", $d); return Validate::date($d, array("format" => "%n-%j-%Y"));'); + $r[] = array( + 'element' => 'sdate', + 'message' => 'ERROR: Invalid Date!', + 'type' => 'callback', + 'format' => $checkDate, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'edate', + 'message' => 'ERROR: Invalid Date!', + 'type' => 'callback', + 'format' => $checkDate, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'image', + 'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!', + 'type' => 'mimetype', + 'format' => $this->mimeTypes, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + // {{{ configureConstants() + + /** + * Configure constants for form + * + * @return void + * @access public + */ + public function configureConstants() + { + $c = array( + 'remove_img_rmv' => false + ); + + $this->setupConstants($c); + } + + // }}} + // {{{ configureFilters() + + /** + * Configure filters for form + * + * @return void + * @access public + */ + public function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + + // {{{ deleteImage() + + /** + * Remove an image record + * + * @param Toolkit_Image_Server $is Image Server Object + * @param string $img image name + * + * @return object Return description (if any) ... + * @access protected + */ + protected function deleteImage(Toolkit_Image_Server $is, $img) + { + return $is->imageDelete($img); + } + + // }}} + + // {{{ insertData() + + /** + * Create a new package in the db + * + * @param array &$values Form submitted values + * + * @return object db result of adding package + * @access protected + */ + protected function insertData(&$values) + { + try { + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ processData() + + /** + * Handles setting up the from processing and which function to get it done + * + * @param array $values Submitted values from the form. + * + * @return void + * @access protected + */ + protected function processData($values) + { + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member_Profile-{$_GET['id']}", 'Dynamic'); + + $e =& $this->getElement('curr_image_rmv'); + + $packages = new Toolkit_Members_Packages(null, $_GET['id']); + $packages->setDbh($this->dbh); + $packages->createMemberList(); + $values['pos'] = $packages->getListSize() + 1; + $values['image'] = $e->getValue('curr_image_rmv'); + $values['member_id'] = $_GET['id']; + $values['pending'] = 0; + $values['sdate'] = implode('-', $values['sdate']); + $values['edate'] = implode('-', $values['edate']); + unset($values['MAX_FILE_SIZE'], + $values['curr_image_rmv'], + $values['remove_img_rmv'], + $values['add_rmv']); + + Toolkit_Common::getTableMetaData(); + $this->insertData($values); + + $listPage = BASE_URL . + "admin/members.php?cat=2&subCat=2&tab=3&id={$_GET['id']}"; + header("Location: $listPage"); + } + + // }}} + + // {{{ setupRenderers() + + /** + * Set up the rendering engine we are going to use to display this form + * + * @param HTML_Template_Flexy &$tEngine Templating Engine + * + * @return void + * @access protected + */ + protected function setupRenderers(HTML_Template_Flexy &$tEngine) + { + $renderer =& new HTML_QuickForm_Renderer_ObjectFlexy($tEngine); + + $this->accept($renderer); + $this->view = new stdClass(); + $this->view->showCurrImg = $this->showCurrImg; + $this->view->form = $renderer->toObject(); + $tEngine->compile($this->formTemplate); + } + + // }}} + + // {{{ validNewImg() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $newImg Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + function validNewImg(array $newImg) + { + return (is_numeric($newImg['size']) && + $newImg['size'] > 0 && + in_array($newImg['type'], $this->mimeTypes)); + } + + // }}} + // {{{ removeOldImage() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $is Parameter description (if any) ... + * @param unknown $oldImg Parameter description (if any) ... + * + * @return void + * @access public + */ + function removeOldImage(Toolkit_Image_Server $is, $oldImg) + { + $this->deleteImage($is, $oldImg); + if ($this->elementExists('curr_image_rmv')) { + $e =& $this->getElement('curr_image_rmv'); + $e->setValue(null); + $this->_submitValues['curr_image_rmv'] = null; + } + } + + // }}} + // {{{ syncCurrImage() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function syncCurrImage() + { + $is = new Toolkit_Image_Server(); + + $delImg = $this->getSubmitValue('remove_img_rmv'); + $oldImg = $this->getSubmitValue('curr_image_rmv'); + $newImg = $this->getSubmitValue('image'); + + if ($delImg && $oldImg) { + $this->removeOldImage($is, $oldImg); + unset($oldImg); + } elseif ($oldImg && $this->validNewImg($newImg)) { + $this->removeOldImage($is, $oldImg); + unset($oldImg); + } + + if ($this->validNewImg($newImg)) { + $image = $this->uploadImage($is, 'image'); + } else { + $image = $oldImg; + } + + if ($image) { + $this->updatePhotoElements($is, $image); + $this->showCurrImg = true; + } + } + + // }}} + // {{{ toHtml() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @param HTML_Template_Flexy $tEngine Templating Engine + * + * @return string The rendered form + * @access public + */ + public function toHtml(HTML_Template_Flexy $tEngine) + { + // We need to validate (and freeze if needed) + // before we render the form. That way the + // template knows about any errors on the form. + $this->validated = $this->validate(); + + // If they have submitted the form and uploaded a proper image + // but some other element had an error, then we need to show + // their uploaded image in the form + if ($this->isSubmitted()) { + $this->syncCurrImage(); + } + + $this->setupRenderers($tEngine); + + if ($this->validated) { + $processed = $this->process( + array(&$this, 'processData'), + $this->mergeFiles + ); + } + + return $tEngine->bufferedOutputObject($this->view); + } + + // }}} + + // {{{ updatePhotoElements() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $is Parameter description (if any) ... + * @param string $image Parameter description (if any) ... + * + * @return void + * @access public + */ + public function updatePhotoElements(Toolkit_Image_Server $is, $image) + { + // Get the dimensions of the image + $dimensions = $is->getImageSize(MEMBER_PHOTOS . $image); + if (PEAR::isError($dimensions)) { + Toolkit_Common::handleError($dimensions); + } + list($w, $h) = $dimensions; + $s = MEMBER_PHOTOS . $image; + + // Set the image to show in the element + $e =& $this->getElement('curr_image'); + $e->setText(''); + + // updated the hidden elements value to make sure it + // holds the most up-to-date image name + $e =& $this->getElement('curr_image_rmv'); + $e->setValue($image); + } + + // }}} + // {{{ uploadImage() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $is Parameter description (if any) ... + * @param unknown $field Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access protected + */ + protected function uploadImage(Toolkit_Image_Server $is, $field) + { + return $is->imageUpload($field); + } + + // }}} +} + +/** + * Form to handle editing/deleting existing packages in members only area + * + * Handles updating caption requests for a member or to remove a + * package from thier profile + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class EditAdminPackage extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * The table name in the database used to store the data + * + * @var string + * @access public + */ + public $tableName = 'member_packages'; + + /** + * The template used to render the form + * + * @var string + * @access protected + */ + protected $formTemplate = 'editPackage.tpl'; + + /** + * Id of package in db + * @var integer + * @access protected + */ + protected $packageId; + + /** + * Description for protected + * @var string + * @access protected + */ + protected $successMsg + = '
    + You successfully updated your package. +
    '; + + /** + * Any rules we want to register for this form + * @var array + * @access protected + */ + protected $registeredRules = array(); + + /** + * Description for protected + * @var array + * @access protected + */ + protected $mimeTypes = array( + 'image/jpe', + 'image/jpeg', + 'image/jpg', + 'image/jfif', + 'image/pjpeg', + 'image/pjp', + 'image/gif', + 'image/png', + ); + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional) Form's method defaults to 'POST' + * @param string $action (optional) Form's action. + * @param string $target (optional) Form's target defaults to '_self' + * @param mixed $attributes (optional) Extra attributes for tag. + * @param bool $trackSubmit (optional) Whether to track if the form was + * submitted by adding a special hidden + * field. + * + * @access public + * @see Toolkit_Members_Admin_EditPackages + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->packageId = $attributes['id']; + $this->packages = new Toolkit_Members_Packages(null, $_GET['id']); + $this->packages->setDbh($pdo); + $this->packages->createMemberList(); + $this->dbh = $pdo; + } + + // }}} + + // {{{ configureForm() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureDefaults(); + $this->configureFilters(); + $this->configureRules(); + } + + // }}} + // {{{ configureDefaults() + + /** + * Setup the element default values for form + * + * @access public + * @see Toolkit_FormBuilder::setupDefaults() + * @return void + */ + public function configureDefaults() + { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = {$this->packageId}"; + + $defaults = $this->dbh->query($sql)->fetch(PDO::FETCH_ASSOC); + $defaults['curr_image_rmv'] = $defaults['image']; + $img = ''; + $defaults['curr_image'] = sprintf($img, MEMBER_PHOTOS . $defaults['image']); + $this->showCurrImg = $defaults['image']; + $this->setupDefaults($defaults); + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @access public + * @see Toolkit_FormBuilder::setupElements() + * @return void + */ + public function configureElements() + { + $e = array(); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'title', + 'display' => 'Package Title', + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'display' => 'Package Description', + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'sdate', + 'display' => 'Start Date', + 'opts' => array( + 'format' => 'm / d / Y', + 'minYear' => date('Y'), + 'maxYear' => date('Y') + 10, + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy', + ), + ) + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'edate', + 'display' => 'End Date', + 'opts' => array( + 'format' => 'm / d / Y', + 'minYear' => date('Y'), + 'maxYear' => date('Y') + 10, + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy', + ), + ) + ); + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'remove_img_rmv', + 'display' => 'Remove Image', + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'curr_image', + 'display' => 'Current Image', + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'curr_image_rmv', + ); + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'image', + 'display' => 'Upload a Package Photo / Image', + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'add_rmv', + 'display' => 'Update Package', + 'opts' => array('class' => 'submit') + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'remove_rmv', + 'display' => 'Remove Package', + 'opts' => array('class' => 'submit') + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureRules() + + /** + * Configure rules for form + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + + $checkDate = create_function('$d', '$d = implode("-", $d); return Validate::date($d, array("format" => "%n-%j-%Y"));'); + $r[] = array( + 'element' => 'sdate', + 'message' => 'ERROR: Invalid Date!', + 'type' => 'callback', + 'format' => $checkDate, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'edate', + 'message' => 'ERROR: Invalid Date!', + 'type' => 'callback', + 'format' => $checkDate, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'image', + 'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!', + 'type' => 'mimetype', + 'format' => $this->mimeTypes, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + // {{{ configureConstants() + + /** + * Configure constants for form + * + * @return void + * @access public + */ + public function configureConstants() + { + $c = array( + 'remove_img_rmv' => false + ); + + $this->setupConstants($c); + } + + // }}} + // {{{ configureFilters() + + /** + * Configure filters for form + * + * @return void + * @access public + */ + public function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + + // {{{ deleteImage() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $is Parameter description (if any) ... + * @param unknown $img Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access protected + */ + protected function deleteImage(Toolkit_Image_Server $is, $img) + { + return $is->imageDelete($img); + } + + // }}} + + // {{{ processData() + + /** + * Handles setting up the from processing and which function to get it done + * + * @param array $values Submitted values from the form. + * + * @return void + * @access protected + */ + protected function processData($values) + { + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member_Profile-{$_GET['id']}", 'Dynamic'); + + $e =& $this->getElement('curr_image_rmv'); + + $values['image'] = $e->getValue('curr_image_rmv'); + $values['sdate'] = implode('-', $values['sdate']); + $values['edate'] = implode('-', $values['edate']); + unset($values['MAX_FILE_SIZE'], + $values['curr_image_rmv'], + $values['remove_img_rmv'], + $values['add_rmv']); + + Toolkit_Common::getTableMetaData(); + $this->updateData($values); + + $listPage = BASE_URL . + "admin/members.php?cat=2&subCat=2&tab=3&id={$_GET['id']}"; + header("Location: $listPage"); + } + + // }}} + + // {{{ setupRenderers() + + /** + * Set up the rendering engine we are going to use to display this form + * + * @param HTML_Template_Flexy &$tEngine Templating Engine + * + * @return void + * @access protected + */ + protected function setupRenderers(HTML_Template_Flexy &$tEngine) + { + $renderer =& new HTML_QuickForm_Renderer_ObjectFlexy($tEngine); + + $this->accept($renderer); + $this->view = new stdClass(); + $this->view->showCurrImg = $this->showCurrImg; + $this->view->form = $renderer->toObject(); + $tEngine->compile($this->formTemplate); + } + + // }}} + + // {{{ validNewImg() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $newImg Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + function validNewImg(array $newImg) + { + return (is_numeric($newImg['size']) && + $newImg['size'] > 0 && + in_array($newImg['type'], $this->mimeTypes)); + } + + // }}} + // {{{ removeOldImage() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $is Parameter description (if any) ... + * @param unknown $oldImg Parameter description (if any) ... + * + * @return void + * @access public + */ + function removeOldImage(Toolkit_Image_Server $is, $oldImg) + { + $this->deleteImage($is, $oldImg); + if ($this->elementExists('curr_image_rmv')) { + $e =& $this->getElement('curr_image_rmv'); + $e->setValue(null); + $this->_submitValues['curr_image_rmv'] = null; + } + } + + // }}} + // {{{ syncCurrImage() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function syncCurrImage() + { + $is = new Toolkit_Image_Server(); + + $delImg = $this->getSubmitValue('remove_img_rmv'); + $oldImg = $this->getSubmitValue('curr_image_rmv'); + $newImg = $this->getSubmitValue('image'); + + if ($delImg && $oldImg) { + $this->removeOldImage($is, $oldImg); + unset($oldImg); + } elseif ($oldImg && $this->validNewImg($newImg)) { + $this->removeOldImage($is, $oldImg); + unset($oldImg); + } + + if ($this->validNewImg($newImg)) { + $image = $this->uploadImage($is, 'image'); + } else { + $image = $oldImg; + } + + if ($image) { + $this->updatePhotoElements($is, $image); + $this->showCurrImg = true; + } + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @param HTML_Template_Flexy $tEngine Templating Engine + * + * @return string The rendered form + * @access public + */ + public function toHtml(HTML_Template_Flexy $tEngine) + { + // We need to validate (and freeze if needed) + // before we render the form. That way the + // template knows about any errors on the form. + $this->validated = $this->validate(); + + // If they have submitted the form and uploaded a proper image + // but some other element had an error, then we need to show + // their uploaded image in the form + if ($this->isSubmitted()) { + $this->syncCurrImage(); + } + + $this->setupRenderers($tEngine); + + if ($this->validated) { + $processed = $this->process( + array(&$this, 'processData'), + $this->mergeFiles + ); + } + + return $tEngine->bufferedOutputObject($this->view); + } + + // }}} + + // {{{ removePackage() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $id Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access protected + */ + protected function removePackage($id) + { + try { + // need to delete the image associated w/ this package here. + $sql = " + DELETE FROM {$this->tableName} + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ updateData() + + /** + * Update the package caption + * + * @param array $values Submitted form values + * + * @return boolean Result of updating the caption in the db + * @access public + */ + protected function updateData($values) + { + try { + if (array_key_exists('remove_rmv', $values)) { + return $this->removePackage($this->packageId); + } + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('id = :id') + ); + + $values['id'] = $this->packageId; + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ updatePhotoElements() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $is Parameter description (if any) ... + * @param string $image Parameter description (if any) ... + * + * @return void + * @access public + */ + public function updatePhotoElements(Toolkit_Image_Server $is, $image) + { + // Get the dimensions of the image + $dimensions = $is->getImageSize(MEMBER_PHOTOS . $image); + if (PEAR::isError($dimensions)) { + Toolkit_Common::handleError($dimensions); + } + list($w, $h) = $dimensions; + $s = MEMBER_PHOTOS . $image; + + // Set the image to show in the element + $e =& $this->getElement('curr_image'); + $e->setText(''); + + // updated the hidden elements value to make sure it + // holds the most up-to-date image name + $e =& $this->getElement('curr_image_rmv'); + $e->setValue($image); + } + + // }}} + // {{{ uploadImage() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $is Parameter description (if any) ... + * @param unknown $field Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access protected + */ + protected function uploadImage(Toolkit_Image_Server $is, $field) + { + return $is->imageUpload($field); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/EditPhoto.php b/Toolkit/Members/Admin/EditPhoto.php new file mode 100644 index 0000000..869c910 --- /dev/null +++ b/Toolkit/Members/Admin/EditPhoto.php @@ -0,0 +1,377 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditPhoto.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see Toolkit/Image/Server.php + */ + + +/** + * The image server processing class + */ +require_once BASE . 'Toolkit/Image/Server.php'; + +/** + * Form to handle editing/deleting existing photos in members only area + * + * Handles updating caption requests for a member or to remove a + * photo from thier profile + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_EditPhoto extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * The table name in the database used to store the data + * + * @var string + * @access public + */ + public $tableName = 'member_photos'; + + /** + * The template used to render the form + * + * @var string + * @access protected + */ + protected $formTemplate = 'editPhoto.tpl'; + + /** + * Id of photo in db + * @var integer + * @access protected + */ + protected $photoId; + + /** + * Success message when a photo gets successfully updated + * @var string + * @access protected + */ + protected $successMsg = ' +
    + You successfully updated your photo. +
    '; + + /** + * Any rules we want to register for this form + * @var array + * @access protected + */ + protected $registeredRules = array(); + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object + * @param Toolkit_Members_Photos $ll Linked List of member photos + * @param string $formName Form's name. + * @param string $method (optional) Form's method + * @param string $action (optional) Form's action. + * @param string $target (optional) Form's target + * @param mixed $attributes (optional) Extra attributes + * @param bool $trackSubmit (optional) Whether to track + * if the form was submitted by + * adding a special hidden field. + * + * @access public + * @see Toolkit_Members_Admin_EditPhotos + */ + public function __construct( + PDO $pdo, + Toolkit_Members_Photos $ll, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + $this->photoId = $attributes['id']; + $this->photos = $ll; + } + + // }}} + + // {{{ configureDefaults() + + /** + * Sets the defaults for elements in the form. + * + * @return void + * @access public + */ + public function configureDefaults() + { + $photo = $this->photos->findNode($this->photoId); + $defaults = array( + 'caption' => $photo->getCaption(), + 'pos' => $photo->getPosition(), + 'pid' => $photo->getId(), + ); + $this->setupDefaults($defaults); + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @param Config_Container $c application configuration + * + * @return void + * @access public + */ + public function configureElements(Config_Container $c) + { + $positions = range(1, $this->photos->getListSize(true)); + $options = array_combine($positions, $positions); + + $config =& $c->getItem('section', 'photos'); + $maxLength =& $config->getItem('directive', 'maxCaptionLength'); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $cur = $this->photos->findNode($this->photoId); + + $elements[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'pid' + ); + $elements[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'caption', + 'display' => 'Image Caption', + 'opts' => array( + 'class' => 'text', + 'maxlength' => $maxLength->getContent(), + ), + 'noCharLimit' => true + ); + $elements[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'pos', + 'display' => 'Position', + 'opts' => $options, + 'att' => array('id' => "pos{$cur->getPosition()}") + ); + $elements[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'update', + 'display' => 'Update Photo', + 'opts' => array('class' => 'submit') + ); + $elements[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'delete', + 'display' => 'Delete Photo', + 'opts' => array('class' => 'photoDelete') + ); + + $this->setupElements($elements); + } + + // }}} + // {{{ configureForm() + + /** + * helper function to set up entire form definition + * + * @param Config_Container $c application configuration + * + * @return void + * @access public + */ + public function configureForm(Config_Container $c) + { + $this->configureElements($c); + $this->configureDefaults(); + $this->configureRules($c); + } + + // }}} + // {{{ configureRules() + + /** + * Configures any rules we want to use on the form + * + * @param Config_Container $c application configuration + * + * @access public + * @return void + */ + public function configureRules(Config_Container $c) + { + $r = array(); + + $config =& $c->getItem('section', 'photos'); + $maxLength =& $config->getItem('directive', 'maxCaptionLength'); + + $r[] = array( + 'element' => 'caption', + 'message' => "ERROR: Please limit caption to {$maxLength->getContent()} characters!", + 'type' => 'maxlength', + 'format' => $maxLength->getContent(), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $this->setupRules($r); + } + + // }}} + + // {{{ processData() + + /** + * Handles setting up the from processing and which function to get it done + * + * @param array $values submitted values from the form + * + * @return array Submitted values from the form. + * @access protected + */ + protected function processData($values) + { + if (!$this->getSubmitValue('delete')) { + unset($values['update']); + $photo = $this->photos->findNode($values['pid']); + try { + // This value might be removed by JS so make sure + // its in place before you try to update the positions + // + // This is taken out in JS instead of just hiding it + // b/c if the image gets dragged and repositioned, + // and then the caption is updated, the old positions + // in the hidden select list will override all the + // newly positioned photos. + // This value might be removed by JS so make sure + // its in place before you try to update the positions + $this->dbh->beginTransaction(); + if (isset($values['pos']) && $values['pos'] != $photo->getPosition()) { + $this->photos->moveNode($photo->getId(), $values['pos']); + } + $curCaption = $photo->getCaption(); + if ($curCaption != $values['caption']) { + $photo->setCaption($values['caption']); + } + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollback(); + return Toolkit_Common::handleError($e); + } + } + + header('Location:' . $this->getAttribute('action')); + } + + // }}} + + // {{{ setupRenderers() + + /** + * Set up the rendering engine we are going to use to display this form + * + * @param HTML_Template_Flexy $tEngine Templating Engine + * + * @return void + * @access protected + */ + protected function setupRenderers(HTML_Template_Flexy $tEngine) + { + $renderer =& new HTML_QuickForm_Renderer_ObjectFlexy($tEngine); + + $this->accept($renderer); + $this->view = new stdClass(); + $this->view->photoId = $this->photoId; + $this->view->form = $renderer->toObject(); + $photo = $this->photos->findNode($this->photoId); + $this->view->pending = $photo->getPending(); + $this->view->img_alt = $photo->getCaption(); + $this->view->img_src = MEMBER_PHOTOS . $photo->getImage(); + $tEngine->compile($this->formTemplate); + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @param HTML_Template_Flexy $tEngine Templating Engine + * @param Cache_Lite $cache Caching Engine + * @param Toolkit_Image_Server $is Image Server + * @param Config_Container $c Application configuration + * + * @return string The rendered form + * @access public + */ + public function toHtml( + HTML_Template_Flexy $tEngine, + Cache_Lite $cache, + Toolkit_Image_Server $is, + Config_Container $c + ) { + if ($this->validate()) { + $res = $cache->remove("Member-{$_GET['id']}", 'Profile'); + + if ($this->getSubmitValue('delete')) { + $this->photos->removeNode($is, $c, $this->getSubmitValue('pid')); + } + + $this->process(array(&$this, 'processData'), $this->mergeFiles); + } + + $this->setupRenderers($tEngine); + + return $tEngine->bufferedOutputObject($this->view); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/EditRegion.php b/Toolkit/Members/Admin/EditRegion.php new file mode 100644 index 0000000..76d4171 --- /dev/null +++ b/Toolkit/Members/Admin/EditRegion.php @@ -0,0 +1,345 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditRegion.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Edit Member Regions + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_EditRegion + extends Toolkit_Members_Auxiliary implements Toolkit_Form +{ + // {{{ properties + + /** + * Description for public + * @var string + * @access public + */ + public $tableName = 'region'; + + /** + * Description for protected + * @var string + * @access protected + */ + protected $formTemplate = 'editRegion.tpl'; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + } + + // }}} + + // {{{ checkRegionName() + + /** + * Check that the region name is not in use already + * + * @param string $name name to check + * + * @return boolean if the name is valid or not + * @access public + */ + public function checkRegionName($name) + { + try { + // If we're editing a region, they + // can save that region as its + // own name. so don't include that region + // in the check. + if (isset($_GET['id'])) { + $and = "AND region_id != :rid"; + } + $sql = " + SELECT COUNT(*) AS total + FROM {$this->tableName} + WHERE region_name = :name + $and"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':name', $name, PDO::PARAM_STR); + if (isset($_GET['id'])) { + $stmt->bindParam(':rid', $_GET['id'], PDO::PARAM_STR); + } + $stmt->execute(); + $stmt->bindColumn('total', $total); + $stmt->fetch(); + + return !(bool) $total; + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureDefaults() + + /** + * Set up the default values for the form + * + * @return void + * @access public + */ + public function configureDefaults() + { + $d = array(); + + if (isset($_GET['id'])) { + try { + $sql = " + SELECT * + FROM region + WHERE region_id = :cid"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':cid', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $region = $stmt->fetch(PDO::FETCH_ASSOC); + $d = array( + 'region_name' => $region['region_name'], + ); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + $this->setupDefaults($d); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'regionInfoHdr', + 'display' => 'Member Regions' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'region_name', + 'display' => 'Region Name' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureForm() + + /** + * Helper function to configure an entire form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureRules(); + $this->configureDefaults(); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + + $r[] = array( + 'element' => 'region_name', + 'message' => 'ERROR: Region already exists!', + 'type' => 'callback', + 'format' => array($this, 'checkRegionName'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ deleteRegion() + + /** + * Remove a region from the db + * + * @param integer $id region id + * + * @return boolean result of db query + * @access protected + */ + protected function deleteRegion($id) + { + if (!is_numeric($id)) { + return false; + } + try { + $sql = " + DELETE FROM {$this->tableName} + WHERE region_id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + + return $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertData() + + /** + * Create a new region + * + * @param array $values Submitted form values + * + * @return boolean Result of insertion into DB + * @access protected + */ + protected function insertData($values) + { + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + try { + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form for viewing + * + * This function validates the form if needed, and if it successfully + * validates attempts to insert or update the data record. + * If it is unsuccessful, it will return an error to the user + * informing them of what went wrong. + * + * @return string The compiled and filled form template. + * @access public + */ + public function toHtml() + { + $listPage = BASE_URL . 'admin/members.php?cat=5&subCat=1'; + return parent::toHtml($listPage); + } + + // }}} + + // {{{ updateData() + + /** + * Update the data for a region + * + * @param array $values submitted form results + * + * @return boolean result of sql update query + * @access protected + */ + protected function updateData($values) + { + // We aren't updating a region, we're deleting it. + if (array_key_exists('delete', $values)) { + return $this->deleteRegion($_GET['id']); + } + + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('region_id = :id') + ); + + $values['id'] = $_GET['id']; + try { + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/ListAmenities.php b/Toolkit/Members/Admin/ListAmenities.php new file mode 100644 index 0000000..c781900 --- /dev/null +++ b/Toolkit/Members/Admin/ListAmenities.php @@ -0,0 +1,133 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ListAmenities.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * List the amenities available for members + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_ListAmenities +{ + // {{{ properties + + /** + * Database Handler + * + * @var object + * @access protected + */ + protected $dbh; + + /** + * The Table name used to store the data of the member record in the database. + * + * @var string + * @access public + */ + public $tableName = 'amenity'; + + /** + * Flexy options used in the renderer + * + * @var array + * @access protected + */ + protected $flexyOptions; + + /** + * The flexy template object which holds the rendered object + * + * @var object + * @access private + */ + private $_template = 'listAmenities.tpl'; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object + * + * @access public + */ + public function __construct(PDO $pdo) + { + $this->dbh = $pdo; + + $this->flexyOptions = Toolkit_Members::getFlexyOptions(); + } + + // }}} + + // {{{ _getAmenities() + + /** + * Get the amenities + * + * @return array regions stored in the db + * @access private + */ + private function _getAmenities() + { + try { + $amenities = array(); + $sql = " + SELECT * + FROM {$this->tableName} + ORDER BY amenity_name"; + + foreach ($this->dbh->query($sql) as $row) { + $amenities[$row['amenity_id']] = $row['amenity_name']; + } + + return $amenities; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ renderAmenities() + + /** + * Render the output + * + * @return html page + * @access public + */ + public function renderAmenities() + { + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + + $page->amenities = $this->_getAmenities(); + + $template->compile($this->_template); + return $template->bufferedOutputObject($page); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/ListCategories.php b/Toolkit/Members/Admin/ListCategories.php new file mode 100644 index 0000000..5b1bb2e --- /dev/null +++ b/Toolkit/Members/Admin/ListCategories.php @@ -0,0 +1,230 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ListCategories.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * List the categories available for members + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_ListCategories +{ + // {{{ properties + + /** + * Database Handler + * + * @var object + * @access public + */ + public $dbh; + + /** + * The Table name used to store the data of the member record in the database. + * + * @var string + * @access public + */ + public $tableName = 'category'; + + /** + * Flexy options used in the renderer + * + * @var array + * @access protected + */ + protected $flexyOptions; + + /** + * The flexy template object which holds the rendered object + * + * @var object + * @access private + */ + private $_template = 'listCategories.tpl'; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object + * + * @access public + */ + public function __construct(PDO $pdo) + { + $this->dbh = $pdo; + + $this->flexyOptions = Toolkit_Members::getFlexyOptions(); + } + + // }}} + + // {{{ _getCategoryList() + + /** + * Gets a list of all the available categories + * + * @return string html list of categories + * @access private + */ + private function _getCategoryList() + { + $tree = Toolkit_Common::gethierarchicalTreeStructure( + 'category', + 'category_id', + 'parent_id', + 'name' + ); + + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE category_id = :catid"; + + $stmt = $this->dbh->prepare($sql); + + reset($tree); + $prevLevel = 1; + while (list($catid, $level) = each($tree)) { + $stmt->bindParam(':catid', $catid, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(); + + if ($level == $prevLevel) { + $list .= $this->_createNode($row, $list); + } elseif ($level > $prevLevel) { + $list .= $this->_createNewLvlNode($row); + } elseif ($level < $prevLevel) { + $list .= $this->_createLastLvlNode($row); + } + + $prevLevel = $level; + } + + return "
      $list
    "; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ _createNode() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $cat Parameter description (if any) ... + * @param unknown $list Parameter description (if any) ... + * + * @return string Return description (if any) ... + * @access private + */ + private function _createNode(array $cat, $list) + { + // check for closing node. + if (strlen($list) > 0) { + if (substr_compare($list, '', -5, 4) == 0) { + $node = "

  • \n"; + } + } + $url = BASE_URL . "admin/members.php?cat=3&subCat=2&id={$cat['category_id']}"; + $node .= "
  • \n"; + $node .= "{$cat['name']}\n"; + + return $node; + } + + // }}} + // {{{ _createNextLvlNode() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $cat Parameter description (if any) ... + * + * @return string Return description (if any) ... + * @access private + */ + private function _createNewLvlNode(array $cat) + { + $node = "
      \n"; + $node .= $this->_createNode($cat, $node); + + return $node; + } + + // }}} + // {{{ _createLastLvlNode() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $cat Parameter description (if any) ... + * + * @return string Return description (if any) ... + * @access private + */ + private function _createLastLvlNode(array $cat) + { + $node = "\n
    \n
  • \n"; + $node .= $this->_createNode($cat, $node); + + return $node; + } + + // }}} + // {{{ renderCategories() + + /** + * Render the output + * + * @return html page + * @access public + */ + public function renderCategories() + { + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + + $page->baseUrl = BASE_URL; + $page->tree = $this->_getCategoryList(); + + $template->compile($this->_template); + return $template->bufferedOutputObject($page); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/ListCities.php b/Toolkit/Members/Admin/ListCities.php new file mode 100644 index 0000000..53f2114 --- /dev/null +++ b/Toolkit/Members/Admin/ListCities.php @@ -0,0 +1,136 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ListCities.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * List the cities available for members + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_ListCities +{ + // {{{ properties + + /** + * Database Handler + * + * @var object + * @access protected + */ + public $dbh; + + /** + * The Table name used to store the data of the member record in the database. + * + * @var string + * @access public + */ + public $tableName = 'city'; + + /** + * Flexy options used in the renderer + * + * @var array + * @access protected + */ + protected $flexyOptions; + + /** + * The flexy template object which holds the rendered object + * + * @var object + * @access private + */ + private $_template = 'listCities.tpl'; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object + * + * @access public + */ + public function __construct(PDO $pdo) + { + $this->dbh = $pdo; + + $this->flexyOptions = Toolkit_Members::getFlexyOptions(); + } + + // }}} + + // {{{ _getCities() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return array Return description (if any) ... + * @access private + */ + private function _getCities() + { + try { + $cities = array(); + $sql = " + SELECT * + FROM {$this->tableName} + ORDER BY city_name"; + + foreach ($this->dbh->query($sql) as $row) { + $cities[$row['city_id']] = $row['city_name']; + } + + return $cities; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ renderCities() + + /** + * Render the output + * + * @return html page + * @access public + */ + public function renderCities() + { + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + + $page->cities = $this->_getCities(); + + $template->compile($this->_template); + return $template->bufferedOutputObject($page); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/ListHtmlEmails.php b/Toolkit/Members/Admin/ListHtmlEmails.php new file mode 100644 index 0000000..1090bfa --- /dev/null +++ b/Toolkit/Members/Admin/ListHtmlEmails.php @@ -0,0 +1,137 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ListHtmlEmails.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * List the amenities available for members + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_ListHtmlEmails +{ + // {{{ properties + + /** + * Database Handler + * + * @var object + * @access protected + */ + protected $dbh; + + /** + * The Table name used to store the data of the member record in the database. + * + * @var string + * @access public + */ + public $tableName = 'news_response'; + + /** + * Flexy options used in the renderer + * + * @var array + * @access protected + */ + protected $flexyOptions; + + /** + * The flexy template object which holds the rendered object + * + * @var object + * @access private + */ + private $_template = 'listHtmlEmails.tpl'; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object + * + * @access public + */ + public function __construct(PDO $pdo) + { + $this->dbh = $pdo; + + $this->flexyOptions = Toolkit_Members::getFlexyOptions(); + } + + // }}} + + // {{{ _getAmenities() + + /** + * Get the amenities + * + * @return array regions stored in the db + * @access private + */ + private function _getAmenities() + { + try { + $amenities = array(); + $sql = " + SELECT * + FROM {$this->tableName} + ORDER BY id"; + + foreach ($this->dbh->query($sql) as $row) { + $amenities[] = array( + 'id' => $row['id'], + 'subject' => $row['subject'], + 'last_update' => $row['last_update'] + ); + } + + return $amenities; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ renderAmenities() + + /** + * Render the output + * + * @return html page + * @access public + */ + public function renderHtmlEmails() + { + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + + $page->amenities = $this->_getAmenities(); + + $template->compile($this->_template); + return $template->bufferedOutputObject($page); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/ListMembers.php b/Toolkit/Members/Admin/ListMembers.php new file mode 100644 index 0000000..710f97f --- /dev/null +++ b/Toolkit/Members/Admin/ListMembers.php @@ -0,0 +1,301 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @release CVS: $Id: ListMembers.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * List the members in the database in a datagrid + * + * Handles listing of the members in the memberDB, pagnation, and sorting. + * Also controls the resulting number of members that are rendered on the page. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://devsys2.gaslightmedia.com/demo.gaslightmedia.com/admin/members/index.php?nav_id=2 + */ +class Toolkit_Members_Admin_ListMembers extends Toolkit_FlexyDataGridBuilder +{ + // {{{ properties + + /** + * Name of the table which holds the members + * + * @var string + * @access protected + */ + protected $tableName = 'member'; + + /** + * The name of the template that renders this datagrid + * + * @var string + * @access protected + */ + protected $template = 'listMembers.tpl'; + + // }}} + + // {{{ configureColumns() + + /** + * Configures the columns (fields) that will be used in our datagrid renderer. + * + * @return void + * @access public + */ + protected function configureColumns() + { + $url =& new Structures_DataGrid_Column('Created', + 'member_id', + 'member_id', + null, + null, + array(&$this, 'url')); + $this->addColumn($url); + + $delUrl =& new Structures_DataGrid_Column('Delete', + 'del_url', + 'del_url', + null, + null, + array(&$this, 'delUrl')); + $this->addColumn($delUrl); + + $name =& new Structures_DataGrid_Column('Member Name', + 'member_name', + 'member_name'); + $this->addColumn($name); + + $phone =& new Structures_DataGrid_Column('Member Phone', + 'phone', + 'phone'); + $this->addColumn($phone); + + $email =& new Structures_DataGrid_Column('Contact Email', + 'member_contact_email', + 'member_contact_email'); + $this->addColumn($email); + } + + // }}} + + // {{{ delUrl() + + /** + * Returns the url to delete a member. + * + * Used when configuring the columns for the data grid. This + * function generates the url to get to delete the member + * + * @param array $data The row from the db record + * + * @return string The url to the edit member page. + * @access public + */ + public function delUrl($data) + { + $target = $data['record']['member_id']; + return BASE_URL . "admin/members.php?cat=2&subCat=1&d=t&id=$target"; + } + + // }}} + + // {{{ removeMember() + + /** + * Remove a member from the list / database + * + * @param integer $mid Member id to remove + * + * @return void + * @access public + */ + public function removeMember($mid) + { + try { + $sql = " + DELETE FROM {$this->tableName} + WHERE member_id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $mid, PDO::PARAM_INT); + $stmt->execute(); + header('location: ' . BASE_URL . 'admin/members.php?cat=2&subCat=1'); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ setControlObject() + + /** + * set the control object to use with the datagrid + * + * @return void + * @access protected + */ + protected function setControlObject() + { + try { + $letters = array(); + + $sql = " + SELECT substr(upper(member_name), 1, 1) AS letter + FROM member + GROUP BY letter + ORDER BY letter"; + + foreach ($this->dbh->query($sql) as $row) { + $letters[$row['letter']] = $row['letter']; + } + + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + + // We only need to show the links of alphabet if we have more than + // one letter to display. + if (count($letters) > 1) { + foreach ($_GET as $k => $v) { + if ($k != 'alpha') { + if (is_array($v)) { + foreach ($v as $i => $j) { + $queryString .= $k . '[' . $i . ']=' . $j . '&'; + } + } else { + $queryString .= "$k=$v&"; + } + } + } + $links['All']['url'] = BASE_URL . "admin/members.php?{$queryString}"; + $links['All']['class'] = empty($_GET['alpha']) ? 'curr' : null; + foreach ($letters as $v) { + $links[$v]['url'] = BASE_URL . "admin/members.php?{$queryString}alpha=$v"; + if ($_GET['alpha'] == $v) { + $links[$v]['class'] = 'curr'; + } + } + $this->ctrlObj['letters'] = $links; + } + + } + + // }}} + // {{{ setQuery() + + /** + * Sets the query to use to fetch the datagrid results + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function setQuery(Config_Container $c) + { + // get reference to [conf] section of config file + $config =& $c->getItem('section', 'conf'); + // get controlled cities + $citiesDirective =& $config->getItem('directive', 'controlledCities'); + + $sql = " + SELECT *, LOWER(member_name) AS sort_field + FROM {$this->tableName}"; + + $params = array("new_member != 'true'"); + + + // Limit to members whose first letter starts with the letter + // a user clicked in the sort alphabetically list. + if (!empty($_GET['alpha'])) { + $params[] = "upper(substr(member_name, 1, 1)) = upper('{$_GET['alpha']}')"; + } + + if (ctype_digit($_GET['category'])) { + $tree = Toolkit_Common::getHierarchicalTreeStructure( + 'category', + 'category_id', + 'parent_id', + 'pos', + $_GET['category'], + 0, + false + ); + + $params[] = " + member_id in ( + SELECT member_id + FROM member_category + WHERE category_id in (" . implode(', ', array_keys($tree)) . "))"; + } + if (!empty($_GET['name'])) { + $params[] = "lower(member_name) LIKE '%" . strtolower(urldecode($_GET['name'])) . "%'"; + } + if (!empty($_GET['email'])) { + $params[] = "member_contact_email LIKE '%" . $_GET['email'] . "%'"; + } + if ($citiesDirective->getContent()) { + if (ctype_digit($_GET['city_id'])) { + $params[] = "city_id = {$_GET['city_id']}"; + } + } else { + if (!empty($_GET['city'])) { + $params[] = "lower(city) LIKE '%{$_GET['city']}%'"; + } + } + if (ctype_digit($_GET['state'])) { + $params[] = "state_id = {$_GET['state']}"; + } + if (!empty($_GET['zip'])) { + $params[] = "zip = CAST({$_GET['zip']} AS TEXT)"; + } + + if (isset($_GET['_qf__record_search']) && !empty($params)) { + $params = implode(' AND ', $params); + $sql = "{$sql} WHERE $params"; + } elseif (!isset($_GET['_qf__record_search'])) { + $sql .= ' WHERE ' . implode(' AND ', $params); + } + + parent::setQuery($sql); + } + + // }}} + + // {{{ url() + + /** + * Returns the url to edit a member. + * + * Used when configuring the columns for the data grid. This + * function generates the url to get to the members edit page. + * + * @param array $data The row from the db record + * + * @return string The url to the edit member page. + * @access public + */ + public function url($data) + { + $target = $data['record']['member_id']; + return BASE_URL . "admin/members.php?cat=2&subCat=2&tab=1&id=$target"; + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/ListNewRequests.php b/Toolkit/Members/Admin/ListNewRequests.php new file mode 100755 index 0000000..f6a10cf --- /dev/null +++ b/Toolkit/Members/Admin/ListNewRequests.php @@ -0,0 +1,145 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ListNewRequests.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link <> + */ + +/** + * List the new member requests in the database in a datagrid + * + * Handles listing of the new member requests in the memberDB, pagnation, and sorting. + * Also controls the resulting number of members that are rendered on the page. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://devsys2.gaslightmedia.com/demo.gaslightmedia.com/admin/members/index.php?nav_id=2 + */ +class Toolkit_Members_Admin_ListNewRequests + extends Toolkit_FlexyDataGridBuilder +{ + // {{{ properties + + /** + * Name of the table which holds the members + * + * @var string + * @access protected + */ + protected $tableName = 'member'; + + /** + * The name of the template that renders this datagrid + * + * @var string + * @access protected + */ + protected $template = 'listNewMembers.tpl'; + + // }}} + + // {{{ configureColumns() + + /** + * Configures the columns (fields) that will be used in our datagrid renderer. + * + * @return void + * @access public + */ + protected function configureColumns() + { + $url =& new Structures_DataGrid_Column('Created', + 'member_id', + 'member_id', + null, + null, + array(&$this, 'url')); + $this->addColumn($url); + + $name =& new Structures_DataGrid_Column('Member Name', + 'member_name', + 'member_name'); + $this->addColumn($name); + + $phone =& new Structures_DataGrid_Column('Member Phone', + 'phone', + 'phone'); + $this->addColumn($phone); + + $email =& new Structures_DataGrid_Column('Contact Email', + 'member_contact_email', + 'member_contact_email'); + $this->addColumn($email); + } + + // }}} + + // {{{ setControlObject() + + /** + * Sets any control object variables that are going to be used in the template + * + * @return void + * @access public + */ + protected function setControlObject() + { + $this->ctrlObj['baseUrl'] = BASE_URL; + $this->ctrlObj['glmAppBaseUrl'] = GLM_APP_BASE_URL; + } + + // }}} + // {{{ setQuery() + + /** + * Sets the query to use to fetch the datagrid results + * + * @return void + * @access public + */ + public function setQuery() + { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE new_member = true"; + + parent::setQuery($sql); + } + + // }}} + + // {{{ url() + + /** + * Returns the url to edit a member. + * + * Used when configuring the columns for the data grid. This + * function generates the url to get to the members edit page. + * + * @param array $data The row from the db record + * + * @return string The url to the edit member page. + * @access public + */ + public function url($data) + { + $target = $data['record']['member_id']; + return BASE_URL . "admin/members.php?cat=2&subCat=4&id=$target"; + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/ListPendingMembers.php b/Toolkit/Members/Admin/ListPendingMembers.php new file mode 100755 index 0000000..3550b17 --- /dev/null +++ b/Toolkit/Members/Admin/ListPendingMembers.php @@ -0,0 +1,120 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ListPendingMembers.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link <> + */ + +/** + * List the pending members in the database in a datagrid + * + * Handles listing of the pending members in the memberDB, pagnation, + * and sorting. Also controls the resulting number of members that are + * rendered on the page. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://devsys2.gaslightmedia.com/demo.gaslightmedia.com/admin/members/index.php?nav_id=2 + */ +class Toolkit_Members_Admin_ListPendingMembers + extends Toolkit_Members_Admin_ListMembers +{ + // {{{ properties + + /** + * The name of the template that renders this datagrid + * + * @var string + * @access protected + */ + protected $template = 'listPendingMembers.tpl'; + + // }}} + + // {{{ configureColumns() + + /** + * Configures the columns (fields) that will be used in our datagrid renderer + * + * @return void + * @access public + */ + protected function configureColumns() + { + $url =& new Structures_DataGrid_Column('Created', + 'member_id', + 'member_id', + null, + null, + array(&$this, 'url')); + $this->addColumn($url); + + $name =& new Structures_DataGrid_Column('Member Name', + 'member_name', + 'member_name'); + $this->addColumn($name); + + $email =& new Structures_DataGrid_Column('Contact Email', + 'member_contact_email', + 'member_contact_email'); + $this->addColumn($email); + } + + // }}} + + // {{{ setQuery() + + /** + * Sets the query to use to fetch the datagrid results + * + * @return void + * @access public + */ + public function setQuery() + { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE member_id IN ( + SELECT DISTINCT member_id + FROM member_updates)"; + + Toolkit_DataGridBuilder::setQuery($sql); + } + + // }}} + + // {{{ url() + + /** + * Returns the url to edit a member + * + * Used when configuring the columns for the data grid. This + * function generates the url to get to the members edit page. + * + * @param array $data The row from the db record + * + * @return string The url to the edit member page. + * @access public + */ + public function url($data) + { + $target = $data['record']['member_id']; + return BASE_URL . "admin/members.php?cat=2&subCat=3&id=$target"; + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/ListRegions.php b/Toolkit/Members/Admin/ListRegions.php new file mode 100644 index 0000000..1d536d0 --- /dev/null +++ b/Toolkit/Members/Admin/ListRegions.php @@ -0,0 +1,133 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ListRegions.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * List the regions available for members + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_ListRegions +{ + // {{{ properties + + /** + * Database Handler + * + * @var object + * @access protected + */ + protected $dbh; + + /** + * The Table name used to store the data of the member record in the database. + * + * @var string + * @access public + */ + public $tableName = 'region'; + + /** + * Flexy options used in the renderer + * + * @var array + * @access protected + */ + protected $flexyOptions; + + /** + * The flexy template object which holds the rendered object + * + * @var object + * @access private + */ + private $_template = 'listRegions.tpl'; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object + * + * @access public + */ + public function __construct(PDO $pdo) + { + $this->dbh = $pdo; + + $this->flexyOptions = Toolkit_Members::getFlexyOptions(); + } + + // }}} + + // {{{ _getRegions() + + /** + * Get the regions + * + * @return array regions stored in the db + * @access private + */ + private function _getRegions() + { + try { + $amenities = array(); + $sql = " + SELECT * + FROM {$this->tableName} + ORDER BY region_name"; + + foreach ($this->dbh->query($sql) as $row) { + $regions[$row['region_id']] = $row['region_name']; + } + + return $regions; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ renderRegions() + + /** + * Render the output + * + * @return html page + * @access public + */ + public function renderRegions() + { + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + + $page->regions = $this->_getRegions(); + + $template->compile($this->_template); + return $template->bufferedOutputObject($page); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/Newsletters.php b/Toolkit/Members/Admin/Newsletters.php new file mode 100644 index 0000000..39f7f03 --- /dev/null +++ b/Toolkit/Members/Admin/Newsletters.php @@ -0,0 +1,333 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: Newsletters.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + + +/** + * Toolkit_Members_Admin_Newsletters + * + * Search for Members to send out E-Blast + * + * @category MembersDB + * @package Toolkit_Members + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_Newsletters extends Toolkit_FlexyDataGridBuilder +{ + // {{{ Properties + + protected $noRecMessage = 'No Data Found'; + /** + * Table name for tracking + * @var string + * @access protected + */ + protected $tableName = 'member'; + + /** + * Description for protected + * @var array + * @access protected + */ + protected $queryParams = array(); + + /** + * Template File + * @var string + * @access protected + */ + protected $template = 'memberContactsList.tpl'; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * define where templates for the data grid are at, + * then call the parent constructor which will handle + * finishing the settings for the datagrid. + * + * After all settings are finished you can call the toHTML() + * function on this object and the datagrid + * will be rendered and returned as a string. + * Optionally you could call show() and the datagrid would + * be rendered and output immediatley to the screen. + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $limit The number of records to display per page. + * @param int $page The current page viewed. + * In most cases, this is useless. + * Note: if you specify this, the "page" GET + * variable will be ignored. + * @param string $rendererType The type of renderer to use. + * You may prefer to use the $type argument + * of {@link render}, {@link fill} or + * {@link getOutput} + * + * @access public + */ + public function __construct( + PDO $pdo, + $limit = null, + $page = null, + $rendererType = null + ) { + $this->pagerOptions['containerClass'] = 'pages'; + parent::__construct($pdo, $limit, $page, $rendererType); + } + + // }}} + + // {{{ configureColumns() + + /** + * Configures the columns (fields) that will be used in our datagrid renderer. + * + * @return void + * @access public + */ + protected function configureColumns() + { + $directUrl =& new Structures_DataGrid_Column( + 'DirectURL', + 'directUrl', + 'directUrl', + null, + null, + array(&$this, 'recordUrl') + ); + $this->addColumn($directUrl); + + $memberName =& new Structures_DataGrid_Column( + 'Member Name', + 'member_name', + 'member_name' + ); + $this->addColumn($memberName); + + $fname =& new Structures_DataGrid_Column( + 'First Name', + 'fname', + 'fname' + ); + $this->addColumn($fname); + + $lname =& new Structures_DataGrid_Column( + 'Last Name', + 'lname', + 'lname' + ); + $this->addColumn($lname); + } + + // }}} + + // {{{ getMemberCats() + + /** + * getMemberCats + * + * @return array + * @access protected + */ + protected function getMemberCats() + { + $sql = " + SELECT * + FROM category + WHERE parent_id = 0 + ORDER BY parent_id, name"; + try { + $stmt = $this->dbh->query($sql); + //$categories[] = ''; + while ($row = $stmt->fetch()) { + unset($subs); + $sql = " + SELECT * + FROM category + WHERE parent_id = :id + ORDER BY parent_id, name"; + try { + $stmt2 = $this->dbh->prepare($sql); + $stmt2->bindParam(":id", $row['category_id'], PDO::PARAM_INT); + $stmt2->execute(); + while ($row2 = $stmt2->fetch()) { + $subs[$row2['category_id']] = $row2['name']; + } + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + if ($subs) { + $categories[$row['name']] = $subs; + } + } + if (is_array($categories)) { + $select = ''; + } + return $select; + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getNewsletters() + + /** + * getNewsletters + * + * @return array + * @access public + */ + protected function getNewsletters() + { + $sql = " + SELECT id, subject + FROM news_response + ORDER BY subject"; + try { + $stmt = $this->dbh->query($sql); + while ($row = $stmt->fetch()) { + $newsletters[$row['id']] = $row['subject']; + } + return $newsletters; + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ recordUrl() + + /** + * Returns the url for a member. + * + * Used when configuring the columns for the data grid. This + * function generates the url to get to the member detail page + * + * @param array $data Structure_DataGrid + * + * @return string + * @access public + */ + public function recordUrl($data) + { + return "members.php?". + "id={$data['record']['member_id']}". + "&cat=2". + "&subCat=2"; + } + + // }}} + + // {{{ setQuery() + + /** + * Sets the query to use to fetch the datagrid results + * + * @return void + * @access public + */ + public function setQuery() + { + $sql = " + SELECT mc.member_id, m.member_name, mc.fname, mc.lname + FROM member m LEFT OUTER JOIN member_contacts mc USING (member_id)"; + if ($_REQUEST['Categories']) { + $where[] = " + m.member_id IN + (SELECT member_id + FROM member_category + WHERE category_id IN (".implode(",", $_REQUEST['Categories'])."))"; + } + if ($_REQUEST['Search']) { + $where[] = " + m.member_name ilike '%{$_REQUEST['Search']}%'"; + } + if (is_array($where)) { + $sql .= " WHERE ".implode(" AND ", $where); + } + + parent::setQuery($sql); + } + + // }}} + // {{{ setControlObject() + + /** + * Sets any control object variables that are going to be used in the template + * + * @return void + * @access public + */ + protected function setControlObject() + { + $form = new HTML_QuickForm('ReportsListForm', 'get'); + $form->addElement('hidden', 'cat', $_REQUEST['cat']); + $form->addElement('hidden', 'subCat', $_REQUEST['subCat']); + $form->addElement('text', 'Search', 'Search', $_REQUEST['Search']); + $form->addElement('static', 'Categories', 'Categories', $this->getMemberCats()); + $form->addElement( + 'select', + 'Output', + 'Output', + array( + 'HTML'=>'HTML', + 'FILE'=>'FILE' + ) + ); + $form->addElement('submit', 'reportSubmit', 'Search Contacts'); + if ($_REQUEST['reportMonth']) { + $form->setDefaults( + array( + 'reportMonth' => $_REQUEST['reportMonth'] + ) + ); + } else { + $form->setDefaults( + array( + 'reportMonth' => date('n').'|'.date('Y') + ) + ); + } + $this->ctrlObj['memberContactSearchForm'] = $form->toHTML(); + // second form will send the list out to either + // a file download page + // or mailout page + $form2 = new HTML_QuickForm('memberSendForm', 'get'); + $form2->addElement('select', 'newsletter', 'Newsletter', $this->getNewsletters()); + $form2->addElement('submit', 'sendSubmit', 'Send Newsletter'); + $this->ctrlObj['memberSendForm'] = $form2->toHTML(); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Admin/Search.php b/Toolkit/Members/Admin/Search.php new file mode 100644 index 0000000..00b737f --- /dev/null +++ b/Toolkit/Members/Admin/Search.php @@ -0,0 +1,457 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Search.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Description for require_once + */ +require_once 'FormBuilder.php'; + +/** + * Form to search the members database + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Admin_Search + extends Toolkit_FormBuilder implements Toolkit_Form +{ + // {{{ properties + + /** + * The default rules to register for validating + * + * We have to register these rules, or any others we want, before + * we are able to use them in our forms. + * + * @var string + * @access protected + */ + protected $registeredRules = array('zip'); + + // }}} + + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @see HTML_QuickForm + * @access public + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + $this->template = BASE . 'Toolkit/Members/templates/currentTables/'; + } + + // }}} + + // {{{ configureConstants() + + /** + * Form constant definitions + * + * @return void + * @access public + */ + public function configureConstants() + { + $c = array( + 'cat' => 2, + 'subCat' => 1, + ); + + $this->setupConstants($c); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function configureElements(Config_Container $c) + { + $e = array(); + + // get reference to [listing type] section of config file + $config =& $c->getItem('section', 'listing type'); + // get coupon + $singularDirective =& $config->getItem('directive', 'singular'); + $singularType = $singularDirective->getContent(); + $pluralDirective =& $config->getItem('directive', 'plural'); + $pluralType = $pluralDirective->getContent(); + + // get reference to [conf] section of config file + $config =& $c->getItem('section', 'conf'); + // get controlled cities + $ctrlCtyDirective =& $config->getItem('directive', 'controlledCities'); + + $categories = $this->_getCategories(); + $states = $this->_getStates(); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'cat' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'subCat' + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'categoryInfoHdr', + 'display' => 'Search by Category' + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'category', + 'display' => 'Category', + 'opts' => $categories + ); + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'recordInfoHdr', + 'display' => "Find $pluralType", + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'name', + 'display' => "$singularType Name" + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'email', + 'display' => "$singularType Email" + ); + if ($ctrlCtyDirective->getContent()) { + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'city_id', + 'display' => 'City', + 'opts' => $this->getCities(), + ); + } else { + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'city', + 'display' => 'City', + ); + } + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'state', + 'display' => 'State', + 'opts' => $states + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'zip', + 'display' => 'Zip' + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit', + 'display' => 'Search' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureFilters() + + /** + * Form filter definitions + * + * @return void + * @access public + */ + public function configureFilters() + { + $f = array(); + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Helper function to configure an entire form + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function configureForm(Config_Container $c) + { + $this->configureElements($c); + $this->configureRules(); + $this->configureFilters(); + $this->configureConstants(); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + $r[] = array( + 'element' => 'member_contact_email', + 'message' => 'ERROR: Invalid Email Address!', + 'type' => 'email', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'category', + 'message' => 'ERROR: Invalid Category!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'state_id', + 'message' => 'ERROR: Invalid State!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'zip', + 'message' => 'ERROR: Invalid Zip!', + 'type' => 'zip', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ _getCategories() + + /** + * get all the categories available in alpha order + * + * @return array alpha order of categories available in the DB + * @access private + */ + private function _getCategories() + { + try { + $sql = " + SELECT * + FROM category + ORDER BY name"; + + $stmt = $this->dbh->prepare($sql); + $stmt->execute(); + $stmt->bindColumn('category_id', $cid); + $stmt->bindColumn('name', $name); + + $categories = array('' => '-- Select --'); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $categories[$cid] = $name; + } + + return $categories; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getCities() + + /** + * Configure the cities for member stored in the database into an array + * + * @return array the cities + * @access protected + */ + protected function getCities() + { + try { + $sql = " + SELECT * + FROM city + ORDER BY city_name"; + foreach ($this->dbh->query($sql) as $row) { + $cities[$row['city_id']] = $row['city_name']; + } + if (!empty($cities)) { + $cities = array('' => '-- Choose City --') + $cities; + } else { + $cities = array('' => '-- No Cities Created Yet -- '); + } + return $cities; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ _getStates() + + /** + * get all the statis available in alpha order + * + * @return array alpha order of states available in the DB + * @access private + */ + private function _getStates() + { + try { + $sql = " + SELECT * + FROM state + ORDER BY state_name"; + + $stmt = $this->dbh->prepare($sql); + $stmt->execute(); + $stmt->bindColumn('state_id', $cid); + $stmt->bindColumn('state_name', $name); + + $states = array('' => '-- Select --'); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $states[$cid] = $name; + } + + return $states; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ setupRenderers() + // @codeCoverageIgnoreStart + + /** + * Custom rendering templates for special fields on the form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + $renderer =& $this->defaultRenderer(); + $tpl = '{element}'; + $renderer->setElementTemplate($tpl, 'submit'); + } + + // @codeCoverageIgnoreEnd + // }}} + + // {{{ toHtml() + + /** + * Call the rendering function to get the form in a string + * + * @access protected + * @return string $output The Form to be rendered or success msg. + */ + public function toHtml() + { + $this->setupRenderers(); + if ($this->validate()) { + $output = parent::toHTML(); + } elseif ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHTML(); + } else { + $output = parent::toHTML(); + } + return $output; + } + + // }}} +} +?> diff --git a/Toolkit/Members/Auth.php b/Toolkit/Members/Auth.php new file mode 100644 index 0000000..639b495 --- /dev/null +++ b/Toolkit/Members/Auth.php @@ -0,0 +1,802 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Auth.php,v 1.2 2009/12/15 20:18:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + * @see Toolkit_Members_Auth-LoginForm, Toolkit_Members_Auth-PasswordForm + */ + +require_once 'Auth.php'; + +/** + * Methods for the memberdb authentication system + * + * Handles Cookie and session generation, id challenges and security for + * the memberdb application + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_Members_Auth-LoginForm, Toolkit_Members_Auth-PasswordForm + */ +class Toolkit_Members_Auth extends Auth +{ + // {{{ properties + + /** + * Maximum idle time + * + * If more seconds pass before a new page request, then the user + * will have to re-authenticate back into the application. + * 1800 = 30 min + * 3600 = 1 hr + * + * @var integer + * @access protected + */ + protected $idleTime = 1800; + + /** + * Authentication options for storage driver + * + * This is setup here, so it can be overridden in subclasses and merged + * into existing authentication options. + * + * @var array + * @access protected + */ + protected $classOptions = array(); + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * Sets up the storage driver + * + * @param Config_Container $c Configuration object + * @param string $storageDriver (optional)Type of the storage + * driver + * @param array $options (optional)Additional options + * for the storage driver + * @param string $loginFunction (optional)Name of the function + * that creates the login form + * @param boolean $showLogin (optional)Should the login form + * be displayed if neccessary? + * + * @return void + * @access public + */ + public function __construct( + Config_Container $c, + $storageDriver = 'DB', + array $options = array(), + $loginFunction = '', + $showLogin = true + ) { + $this->config = $c; + // These are the default options, they are defined here b/c + // constants cannot be defined in the properites. + // subclasses that define any of the same authOptions will overwrite + // these when the options are merged. ALSO, options passed in + // via parameters will supercede/overwrite any of these authOptions + // or subclass authOptions. + $defaultOptions = array( + 'dsn' => DSN, + 'table' => 'member', + 'usernamecol' => 'member_login', + 'passwordcol' => 'member_passwd', + 'db_fields' => array('member_id', 'member_name'), + 'cryptType' => 'none', + 'db_where' => 'new_member != true', + ); + + $authOptions = array_merge( + $defaultOptions, + $this->classOptions, + $options + ); + + parent::Auth($storageDriver, $authOptions, $loginFunction, $showLogin); + } + + // }}} + + // {{{ loginForm() + + /** + * Function to set up the regular login form + * + * @param unknown $uname Last attempted username + * @param unknown $status The authorization status + * @param unknown &$auth The authentication object + * + * @return void + * @access public + */ + protected function loginForm($uname = null, $status = null, &$auth = null) + { + $login =& new LoginForm('member_login', + 'post', + BASE_URL . 'memberdb/index.php'); + $login->setDbh(Toolkit_Database::getInstance()); + $login->configureForm($auth->config); + echo $login->toHtml(); + } + + // }}} + + // {{{ passwordForm() + + /** + * Function to set up the forgot password form + * + * @return void + * @access public + */ + protected function passwordForm() + { + $pword =& new PasswordForm('member_password'); + $pword->setDbh(Toolkit_Database::getInstance()); + $pword->configureForm(); + echo $pword->toHtml(); + } + + // }}} + + // {{{ setIdle() + + /** + * Set the maximum idle time + * + * @param integer $time time in seconds + * @param boolean $add (optional)add time to current maximum idle time or not + * + * @return void + * @access public + */ + public function setIdle($time = null, $add = false) + { + $time = is_null($time) ? $this->idleTime : $time; + parent::setIdle($time, $add); + } + + // }}} +} + +/** + * Handles rendering and validating the member login form + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_FormBuilder + */ +class LoginForm extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * Custom rules to check for when validating the form + * + * @var array + * @access protected + */ + protected $registeredRules = array(); + + /** + * Where to perform validation + * + * @var string + * @access protected + */ + protected $validationType = 'client'; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param string $formName Form's name + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target + * @param mixed $attributes (optional)Extra attributes for the tag + * @param boolean $trackSubmit (optional)Whether to track if the form + * was submitted by adding a special hidden field + * + * @return void + * @access public + */ + public function __construct( + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->template = dirname(__FILE__) . '/templates/currentTables/'; + } + + // }}} + + // {{{ configureElements() + + /** + * Sets up the elements to be configured for use with the form + * + * @param Config_Container $c Configuration object + * + * @return void + * @access protected + */ + protected function configureElements(Config_Container $c) + { + $e = array(); + + // get reference to [listing type] section of config file + $config =& $c->getItem('section', 'listing type'); + $singularDirective =& $config->getItem('directive', 'singular'); + $singularType = $singularDirective->getContent(); + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'formHdr', + 'display' => "$singularType Login" + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'username', + 'display' => 'Username' + ); + $e[] = array( + 'type' => 'password', + 'req' => true, + 'name' => 'password', + 'display' => 'Password' + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'doLogin', + 'display' => 'Login now', + 'opts' => array('id' => 'doLogin') + ); + $e[] = array( + 'type' => 'link', + 'req' => false, + 'name' => 'forgot', + 'display' => 'Forgot your password? Click', + 'opts' => BASE_URL . 'index.php?catid='.MEMBERS_CATEGORY.'&forgot=', + 'att' => 'here' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureFilters() + + /** + * Sets up the filters to be used with the form when submitted + * + * @return void + * @access protected + */ + protected function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Helper method to setup form + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function configureForm(Config_Container $c) + { + $this->configureElements($c); + $this->configureFilters(); + $this->configureRules(); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up required rules and extra defined rules for the form + * + * @return void + * @access protected + */ + protected function configureRules() + { + $this->setupRules($r); + } + + // }}} + + // {{{ setDbh() + + /** + * set the pdo to use for db calls + * + * @param PDO $pdo PHP Data Object to use + * + * @return void + * @access public + */ + public function setDbh(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + // {{{ setupRenderers() + + /** + * Inject custom renderers into the forms elements for custom display + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + + $renderer =& $this->defaultRenderer(); + $required = '*'; + $error = '
    {error}
    '; + + $renderer->setElementTemplate('{label} {element}', 'forgot'); + $renderer->setElementTemplate('{element}', 'doLogin'); + } + + // }}} + + // {{{ toHtml() + + /** + * Returns an HTML version of the form + * + * @return string HTML version of the form + * @access public + */ + public function toHtml() + { + $this->setupRenderers(); + if ($this->validate()) { + header('Location: ' . BASE_URL . 'memberdb/index.php'); + } elseif ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHtml(); + } else { + if ($_GET['status']) { + switch ($_GET['status']) { + case -1 : + $error = 'Your session has exceeded the maximum idle time'; + break; + + case -2 : + $error = 'Your session has expired.'; + break; + + case -3 : + $error = 'Invalid username or password.'; + break; + + case -4 : + // This is primarily used for Development. + // Users should never be presented with this error. + $error = 'Invalid Container'; + break; + + case -5 : + // This is only thrown if the advanced security system + // has detected a breach into the system. + $error = 'The system has encountered an error. Reference code: -5'; + break; + } + $output = "
    $error
    "; + } + $output .= parent::toHtml(); + } + + return $output; + } + + // }}} +} + +/** + * Handles rendering and validating the member password form + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_FormBuilder + */ +class PasswordForm extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * Table to query when gathering information + * + * @var string + * @access public + */ + public $tableName = 'member'; + + /** + * Custom defined rules to validate against when the form is submitted + * + * @var array + * @access protected + */ + protected $registeredRules = array(); + + /** + * Where to perform validation + * + * @var string + * @access protected + */ + protected $validationType = 'client'; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param string $formName Form's name + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target + * @param mixed $attributes (optional)Extra attributes for the tag + * @param boolean $trackSubmit (optional)Whether to track if the form + * was submitted by adding a special hidden field + * + * @return void + * @access public + */ + public function __construct( + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->template = dirname(__FILE__) . '/templates/currentTables/'; + } + + // }}} + + // {{{ checkAddressExists() + + /** + * Checks to see if the email address exists before allowing an email to go out + * + * @param string $value submitted email address + * + * @return boolean If the email address exists or not + * @access public + */ + public function checkAddressExists($value) + { + try { + $sql = " + SELECT count(*) AS total + FROM {$this->tableName} + WHERE member_contact_email = :mce"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mce', $value, PDO::PARAM_STR); + $stmt->execute(); + $stmt->bindColumn('total', $exists); + $stmt->fetch(); + + return (bool) $exists; + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureElements() + + /** + * Sets up the elements to be configured for use with the form + * + * @return void + * @access protected + */ + protected function configureElements() + { + $e = array(); + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'formHdr', + 'display' => 'Email Reminder' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Your Member Contact Email Address' + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit', + 'display' => 'Send' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureFilters() + + /** + * Sets up the filters to be used with the form when submitted + * + * @return void + * @access protected + */ + protected function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Helper method to setup form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up required rules and extra defined rules for the form + * + * @return void + * @access protected + */ + protected function configureRules() + { + $r = array(); + + $r[] = array( + 'element' => 'email', + 'message' => 'ERROR: Invalid Email Format!', + 'type' => 'email', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'email', + 'message' => 'ERROR: Cannot locate email address!', + 'type' => 'callback', + 'format' => array(&$this, + 'checkAddressExists'), + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ setDbh() + + /** + * set the pdo to use for db calls + * + * @param PDO $pdo PHP Data Object to use + * + * @return void + * @access public + */ + public function setDbh(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + // {{{ setupRenderers() + + /** + * Inject custom renderers into the forms elements for custom display + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + + $renderer =& $this->defaultRenderer(); + $required = '*'; + $error = '
    {error}
    '; + + $renderer->setElementTemplate('{element}', 'submit'); + } + + // }}} + + // {{{ processData() + + /** + * Processes the data submitted by the form + * + * Gets the login credentials for the matching email address and mails + * them to that email address + * + * @param array $values submitted form values + * + * @return boolean Result of mail + * @access protected + */ + protected function processData($values) + { + try { + $sql = " + SELECT member_login, member_passwd + FROM {$this->tableName} + WHERE member_contact_email = :mce"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mce', $values['email'], PDO::PARAM_STR); + $stmt->execute(); + $row = $stmt->fetch(); + + $htmlMsg + = "Here is your " . SITENAME . " password:

    " . + "Login: {$row['member_login']}
    " . + "Email: {$values['email']}
    " . + "Password: {$row['member_passwd']}

    "; + + $msg + = "Here is your " . SITENAME . " password:\n\n" . + "Login: {$row['member_login']}\n" . + "Email: {$values['email']}\n" . + "Password: {$row['member_passwd']}"; + + $crlf = "\n"; + $mimeMail = new Mail_mime($crlf); + $mimeMail->setFrom(SITENAME . ' <' . OWNER_EMAIL . '>'); + $mimeMail->setSubject('Your ' . SITENAME . ' Password'); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $mail =& Mail::factory('mail'); + $body = $mimeMail->get(); + $headers = $mimeMail->headers($hdrs); + + $res = $mail->send($values['email'], $headers, $body); + + return PEAR::isError($res) ? + Toolkit_Common::handleError($res) : + $res; + } catch (PDOException $e) { + Toolkit_Common::handlError($e); + } + } + + // }}} + + // {{{ toHtml() + + /** + * Returns an HTML version of the form + * + * @return string HTML version of the form + * @access public + */ + public function toHtml() + { + $this->setupRenderers(); + if ($this->validate()) { + if ($this->process(array(&$this, 'processData'))) { + $url = BASE_URL . 'index.php?catid=' . MEMBERS_CATEGORY; + $e =& $this->getElement('email'); + $email = $e->getValue(); + $output + = "

    Your Login Information has been sent to $email

    " . + "

    Continue to Member Login

    "; + } else { + $output = '

    Email address not found.

    '; + } + } elseif ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHtml(); + } else { + $output .= parent::toHtml(); + } + + return $output; + } + + // }}} +} +?> diff --git a/Toolkit/Members/Auxiliary.php b/Toolkit/Members/Auxiliary.php new file mode 100644 index 0000000..8e7fc50 --- /dev/null +++ b/Toolkit/Members/Auxiliary.php @@ -0,0 +1,405 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Auxiliary.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Base class used for building forms to accompany the members database + * + * This class handles all common functions that are to be used in + * the auxiliary forms used to assist in the members DB. + * (categories, amenities, regions, etc...). + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Auxiliary.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://devsys2.gaslightmedia.com/demo.gaslightmedia.com/admin/members/ + * @see Toolkit_Members, member_admin + */ +abstract class Toolkit_Members_Auxiliary + extends Toolkit_FormBuilder implements Toolkit_Form +{ + // {{{ properties + + /** + * Primary table used for database calls + * + * @var String + * @access Public + */ + public $tableName; + + /** + * Array of primary table meta data + * + * This array will hold the column data types for the fields + * that will be manipulated in the database. + * + * @var Array + * @access Public + */ + public $tableMetaData; + + /** + * The name of the template used for the form + * + * @var String + * @access Protected + */ + protected $formTemplate; + + /** + * The object to use inside the form + * + * This object which is to be populated by the $this object + * is used inside the templates and allows access back into the + * calling class to call publicly available functions + * + * @var String + * @access Protected + */ + protected $view; + + /** + * rules to use with the form + * @var array + * @access protected + */ + protected $registeredRules = array(); + + /** + * Setup options to use for rendering the template engine + * @var array + * @access protected + */ + protected $flexyOptions = array(); + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->flexyOptions = Toolkit_Members::getFlexyOptions(); + } + + // }}} + + // {{{ configureDefaults() + + /** + * Configure the default values for the form + * + * Since each form is different, you will need to redefine this + * method inside of each subclass and create your own rules + * based on your forms elements. + * + * @return void + * @access public + */ + abstract protected function configureDefaults(); + + // }}} + // {{{ configureFilters() + + /** + * Defines all filters used on form elements when submitted + * + * Most times this function won't need to be overridden. + * + * @return void + * @access public + */ + protected function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + + // {{{ getSetParameters() + + /** + * get a string of sql query parameters + * + * @param array $values parameters to include + * + * @return string sql query parameters + * @access protected + */ + protected function getSetParameters($values) + { + $params = array_keys($values); + $length = count($params); + for ($i = 0; $i < $length; ++$i) { + $bindParams .= "{$params[$i]} = :{$params[$i]}"; + if ($i < ($length - 1)) { + $bindParams .= ', '; + } + } + return $bindParams; + } + + // }}} + // {{{ getDataType() + + /** + * Get the data type of the element + * + * @param string $k element name + * + * @return element type in the DB + * @access protected + */ + protected function getDataType($k) + { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + return PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + return PDO::PARAM_BOOL; + } elseif ($metaData == 'double precision') { + return null; + } else { + return PDO::PARAM_STR; + } + } + + // }}} + + // {{{ isEdit() + + /** + * Determines if we are editing an object or not + * + * If we are ever editing an object, member, category, etc... + * There will be the objects DB ID passed along in the url under the + * id key. If we can find this then we know we're editing, if not + * then we are adding. + * + * @return boolean if the key id is set in the $_GET array + * @access public + */ + public function isEdit() + { + return isset($_GET['id']); + } + + // }}} + + // {{{ processData() + + /** + * clean unneeded form elements out of the submitted values array + * + * @param array $values QuickForm submitted elements + * + * @return boolean Result of insert/update functions + * @access public + */ + public function processData($values) + { + foreach ($values as $k => $v) { + switch ($k) { + case 'MAX_FILE_SIZE' : + unset($values[$k]); + break; + + default : + if (substr($k, -4) == '_rmv') { + unset($values[$k]); + } + break; + } + } + + $function = is_numeric($_GET['id']) ? 'updateData' : 'insertData'; + return $this->$function($values); + } + + // }}} + + // {{{ setupElements() + + /** + * Add the form elements defined in your class to a QuickForm + * + * Handles adding singleton elements as well as grouped elements. + * If added elements fail to correctly add to the form, the script + * should die gracefully, telling the user there was a problem. + * + * @param array $elements element definitions to setup + * + * @return void + * @throws HTML_QuickForm_Error error raised from QuickForm class. + * @access protected + */ + protected function setupElements($elements) + { + $this->formElements = $elements; + foreach ($elements as $e) { + if ($e['type'] != 'group') { + try { + $source =& $this->addElement($e['type'], $e['name'], $e['display'], $e['opts'], $e['att'], $e['val']); + } catch (HTML_QuickForm_Error $e) { + Toolkit_Common::dieGracefully(null, $e); + } + if ($e['type'] == 'advmultiselect') { + $source->setLabel($e['labels']); + } + if ($e['name'] == 'categories') { + $res = $source->loadArray($this->categories); + if (PEAR::isError($res)) { + Toolkit_Common::dieGracefully(null, $res); + } + } + if ($e['type'] == 'header') { + $this->formHeaders[$e['display']] = $e; + } + } elseif (is_array($e['group'])) { + unset($field); + foreach ($e['group'] as $g) { + $field[] =& HTML_QuickForm::createElement($g['type'], $g['name'], $g['display'], $g['opts'], $g['att'], $g['val']); + } + $source =& $this->addGroup($field, $e['name'], $e['label'], $e['seperator'], $e['appendName']); + } + } + } + + // }}} + // {{{ setupRenderers() + + /** + * Set up the rendering engine templates + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $renderer =& new HTML_QuickForm_Renderer_Object(true); + + $this->accept($renderer); + + $this->template =& new HTML_Template_Flexy($this->flexyOptions); + + // Make the view a copy of the $this object + // That way we have access to call functions in + // this class from within the template. + $this->view = $this; + $this->view->form = $renderer->toObject(); + $this->template->compile($this->formTemplate); + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form for viewing + * + * This function validates the form if needed, and if it successfully + * validates attempts to insert or update the data record. + * If it is unsuccessful, it will return an error to the user + * informing them of what went wrong. + * + * @param string $listPage The page the header should redirect + * to on successful insert or update. + * + * @return string The compiled and filled form template. + * @access public + */ + public function toHtml($listPage = 'index.php') + { + // We need to validate (and freeze if needed) + // before we render the form. That way the + // template knows about any errors on the form. + $this->validated = $this->validate(); + $this->setupRenderers(); + + if ($this->validated) { + $processed = $this->process( + array(&$this, 'processData'), + $this->mergeFiles + ); + if ($processed) { + header("Location: $listPage"); + } else { + $this->validated = false; + $errorMsg = "There was an unexpected error. Please try again later."; + } + } + + return $errorMsg . $this->template->bufferedOutputObject($this->view); + } + + // }}} + + // {{{ validated() + + /** + * Returns form message from validation attempts + * + * @return void + * @access public + */ + public function validated() + { + if ($this->validated) { + return $this->successMsg; + } elseif ($this->isSubmitted()) { + return $this->errorMsg; + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/CategoryTree.php b/Toolkit/Members/CategoryTree.php new file mode 100644 index 0000000..4af2366 --- /dev/null +++ b/Toolkit/Members/CategoryTree.php @@ -0,0 +1,77 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: CategoryTree.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + + +/** + * Description for require_once + */ +require_once 'Tree.php'; + +/** + * Short description for class + * + * Long description (if any) ... + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_CategoryTree extends Toolkit_Tree +{ + // {{{ addChildren() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function addChildren() + { + try { + $sql = " + SELECT * + FROM category + WHERE parent_id = :parent + ORDER BY name"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':parent', $this->catid, PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $this->children[] = new Toolkit_Members_CategoryTree($row['category_id'], + $row['name'], + $this->dbh, + $row['parent_id']); + } + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/City.php b/Toolkit/Members/City.php new file mode 100644 index 0000000..08ca33c --- /dev/null +++ b/Toolkit/Members/City.php @@ -0,0 +1,412 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: City.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Handle City functionality + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: City.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://devsys2.gaslightmedia.com/demo.gaslightmedia.com/admin/members.php?cat=6 + */ +class Toolkit_Members_City +{ + // {{{ properties + + protected $name; + protected $region; + protected $state; + protected $image; + protected $description; + + /** + * Table name in DB + * @var string + * @access public + */ + public $tableName = 'city'; + + /** + * Image Server + * @var object + * @access protected + */ + protected $is; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object + * + * @access public + */ + public function __construct(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + + // {{{ createNewCity() + + /** + * Creates a new city in the DB + * + * @return void + * @access public + */ + public function createNewCity() + { + // Minimum required fields to have an array + if (!is_numeric($this->state) || empty($this->name)) { + return false; + } + + if ($this->_isDuplicate()) { + return PEAR::raiseError('This city already exists'); + } + + $values = array( + 'city_name' => $this->name, + 'state_id' => $this->state, + 'region_id' => $this->region, + 'description' => $this->description, + 'image' => $this->image, + ); + + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + + try { + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ deleteCity() + + /** + * delete a city from the DB + * + * @param integer $id city record to delete + * + * @return void + * @access public + */ + public function deleteCity($id) + { + if (!is_numeric($id)) { + return false; + } + + $sql = " + DELETE FROM {$this->tableName} + WHERE city_id = :id"; + + try { + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ getName() + + /** + * get the name of the city + * + * @return void + * @access public + */ + public function getName() + { + return $this->name; + } + + // }}} + // {{{ getState() + + /** + * get the state the city belongs in + * + * @return void + * @access public + */ + public function getState() + { + return $this->state; + } + + // }}} + // {{{ getRegion() + + /** + * get the Region the city belongs in + * + * @return void + * @access public + */ + public function getRegion() + { + return $this->region; + } + + // }}} + // {{{ getImage() + + /** + * get the city image + * + * @param string $uri URI location to find the image at + * + * @return string file name of image, or html img tag of image + * @access public + */ + public function getImage($uri = null) + { + if (is_null($uri)) { + return $this->image; + } else { + $path = $uri . $this->image; + $imageSize = $this->is->getImageSize($path); + $img = ""; + return $img; + } + } + + // }}} + // {{{ getDesc() + + /** + * get the description of the city + * + * @return string city description + * @access public + */ + public function getDescription() + { + return $this->description; + } + + // }}} + + // {{{ _isDuplicate() + + /** + * get the description of the city + * + * @param integer $ignore city records to not include in count + * + * @return string city description + * @access private + */ + private function _isDuplicate($ignore = null) + { + $sql = " + SELECT count(*) AS total + FROM {$this->tableName} + WHERE city_name = :name + AND state_id = :state"; + + if (is_numeric($ignore)) { + $sql .= " AND city_id != $ignore"; + } + + try { + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':name', $this->name, PDO::PARAM_STR); + $stmt->bindParam(':state', $this->state, PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('total', $total); + $stmt->fetch(); + + return (bool) $total; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ setName() + + /** + * set the name of the city + * + * @param string $name City Name + * + * @return void + * @access public + */ + public function setName($name) + { + $this->name = $name; + } + + // }}} + // {{{ setState() + + /** + * set the state the city belongs in + * + * @param integer $state state id from db + * + * @return void + * @access public + * @throws PEAR_Error + */ + public function setState($state) + { + if (!is_numeric($state)) { + return PEAR::raiseError('Invalid state id'); + } + + $this->state = $state; + } + + // }}} + // {{{ setRegion() + + /** + * set the Region the city belongs in + * + * @param integer $region region id from db + * + * @return void + * @access public + * @throws PEAR_Error + */ + public function setRegion($region) + { + if (!is_numeric($region)) { + return PEAR::raiseError('Invalid region id'); + } + $this->region = $region; + } + + // }}} + // {{{ setImage() + + /** + * set the city image + * + * @param string $image the city image + * + * @return void + * @access public + */ + public function setImage($image) + { + $this->image = $image; + } + + // }}} + // {{{ setImageServer() + + /** + * set the image server to use + * + * @param Toolkit_Image_Server $is Image Server Instance + * + * @return void + * @access public + */ + public function setImageServer(Toolkit_Image_Server $is) + { + $this->is = $is; + } + + // }}} + // {{{ setDesc() + + /** + * set the description of the city + * + * @param string $desc City Description + * + * @return void + * @access public + */ + public function setDescription($desc) + { + $this->description = $desc; + } + + // }}} + + // {{{ updateCity() + + /** + * update a city in the DB + * + * @param integer $id record id to update + * + * @return void + * @access public + */ + public function updateCity($id) + { + // Minimum required fields to have an array + if (!is_numeric($this->state) || empty($this->name)) { + return false; + } + + if ($this->_isDuplicate($id)) { + return PEAR::raiseError('This city already exists'); + } + + $values = array( + 'city_name' => $this->name, + 'state_id' => $this->state, + 'region_id' => $this->region, + 'description' => $this->description, + 'image' => $this->image, + ); + + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('city_id = :city_id') + ); + + $values['city_id'] = $id; + + try { + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/Display.php b/Toolkit/Members/Display.php new file mode 100644 index 0000000..1428160 --- /dev/null +++ b/Toolkit/Members/Display.php @@ -0,0 +1,187 @@ + + * @copyright 2008 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Display.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ +require_once 'HTML/Select.php'; +require_once 'HTML/Template/Flexy.php'; +require_once 'Members/SearchList.php'; +require_once 'Members/UserSearchForm.php'; + +/** + * Handles Displaying member lists and profile pages + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Display +{ + // {{{ properties + + /** + * The Database Handler + * + * @var object + * @access protected + */ + public $dbh; + + /** + * Search radius distance + * @var integer + * @access protected + */ + protected $radius = 35; + + /** + * Page catid + * + * @var integer + * @access private + */ + private $_catid; + + /** + * Number of records to show per page + * + * Set to NULL to show all records on one page. + * + * @var integer + * @access protected + */ + protected $limit = 10; + + /** + * The list of members + * + * @var string + * @access protected + */ + protected $membersList; + + /** + * Whether to randomize the list of members or not + * + * @var bool + * @access protected + */ + protected $randomize = false; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * + * @return void + * @access public + */ + public function __construct(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + + // {{{ hideUserSearchForm() + + /** + * Get the status of displaying the search form for a page + * + * @return bool true if yes, false otherwise. + * @access public + */ + public function hideUserSearchForm() + { + try { + $sql = " + SELECT CASE + WHEN no_search_form THEN 1 ELSE 0 + END as no_search_form + FROM bus_category + WHERE id = :catid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':catid', $this->_catid, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(); + return $row['no_search_form']; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ setCatId() + + /** + * Set the catid for the page + * + * @param integer $catid page id from db + * + * @return void + * @access public + * @throws PEAR Error on invalid member id + */ + public function setCatId($catid) + { + if (is_numeric($catid) && ctype_digit((string) $catid)) { + $this->_catid = $catid; + } else { + $this->_catid = null; + throw new PEAR_Exception('Invalid catid'); + } + } + + // }}} + // {{{ setMemberSections() + + /** + * Sets an array with all the member category types assigned to a page + * + * Collects all member categories assigned to a page from the + * admin Toolbox. + * + * @return void + * @access public + */ + public function setMemberSections() + { + try { + $sql = " + SELECT count(*) AS total, bc.category + FROM bus_cat_member bcm, bus_category bc + WHERE bcm.catid = :catid + AND bcm.catid = bc.id + GROUP BY bc.category"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':catid', $this->_catid, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(); + if ($row['total']) { + $this->memberSections[$this->_catid] = $row['category']; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/EditMemberAmenities.php b/Toolkit/Members/EditMemberAmenities.php new file mode 100644 index 0000000..e2ca8ea --- /dev/null +++ b/Toolkit/Members/EditMemberAmenities.php @@ -0,0 +1,301 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditMemberAmenities.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Short description for class + * + * Long description (if any) ... + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_EditMemberAmenities + extends Toolkit_Members_EditMemberInfo implements Toolkit_Form +{ + // {{{ properties + + /** + * The Table name used to store the data of the member record in the database. + * + * @var string + * @access public + */ + public $tableName = 'member_amenity'; + + /** + * The name of the template used to render the business info form. + * + * @var string + * @access protected + */ + protected $formTemplate = 'editAmenities.tpl'; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + * @see Toolkit_Members_EditMemberInfo + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $pdo, + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + } + + // }}} + + // {{{ configureDefaults() + + /** + * Sets the defaults for elements in the form. + * + * @return array form element default values + * @access public + */ + public function configureDefaults() + { + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE member_id = :id "; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $defaults[$row['amenity_id']] = true; + } + $this->setupDefaults($defaults); + return $defaults; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureElements() + + /** + * Setup the element definitions to use on the form. + * + * @return void + * @access public + */ + public function configureElements() + { + // Element definitions + $e = array(); + $amenities = $this->getAmenities(); + $half = floor(count($amenities) / 2); + $i = 0; + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'row1' + ); + while ($i < $half) { + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => $amenities[$i]['amenity_id'], + 'display' => $amenities[$i++]['amenity_name'] + ); + } + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'row2' + ); + while ($i < count($amenities)) { + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => $amenities[$i]['amenity_id'], + 'display' => $amenities[$i++]['amenity_name'] + ); + } + + $this->setupElements($e); + } + + // }}} + // {{{ configureForm() + + /** + * Wrapper function to handle setting up the form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureRules(); + $this->configureDefaults(); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up all the rules to be used when the form is validated. + * + * @return void + * @access public + */ + public function configureRules() + { + $this->setupRules(); + } + + // }}} + + // {{{ getAmenities() + + /** + * Gets all the amentities + * + * @return $a array The array of amenities from the DB. + * @access protected + */ + protected function getAmenities() + { + $a = array(); + try { + $sql = " + SELECT * + FROM amenity + ORDER BY amenity_name"; + foreach ($this->dbh->query($sql) as $row) { + $a[] = $row; + } + } catch (PDOException $e) { + $this->handleError($e); + } + return $a; + } + + // }}} + + // {{{ insertData() + + /** + * Create a new record in the database from the data on the form + * + * @param array $values Form values + * + * @return boolean False on error, True otherwise. + * @access public + */ + public function insertData($values) + { + try { + $sql = " + DELETE FROM {$this->tableName} + WHERE member_id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + $params = implode(', ', array_keys($values)); + $bindParams = ':' . implode(', :', array_keys($values)); + $sql = " + INSERT INTO {$this->tableName} (member_id, amenity_id) + VALUES (:member_id, :aid)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + foreach ($values as $k => $v) { + $stmt->bindParam(':aid', $k, PDO::PARAM_INT); + $stmt->execute(); + } + + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member_Profile-{$_GET['id']}", 'Dynamic'); + + return true; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ processData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return array Return description (if any) ... + * @access public + */ + public function processData($values) + { + Toolkit_Common::getTableMetaData(); + + foreach ($values as $k => $v) { + switch ($k) { + default : + if (preg_match('/^.+_rmv$/', $k)) { + unset($values[$k]); + } + break; + } + } + + return $this->insertData($values); + } + + // }}} +} +?> diff --git a/Toolkit/Members/EditMemberContacts.php b/Toolkit/Members/EditMemberContacts.php new file mode 100644 index 0000000..225e798 --- /dev/null +++ b/Toolkit/Members/EditMemberContacts.php @@ -0,0 +1,728 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditMemberContacts.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Handle associating contacts along with member records + * + * Controls all aspects of creating and rendering the form used to manipulate + * the business contacts. Form is not rendered until the user is added into + * the Database. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_Members + */ +class Toolkit_Members_EditMemberContacts + extends Toolkit_Members_EditMemberInfo implements Toolkit_Form +{ + // {{{ properties + + /** + * The table name in the database used to store the data of the files + * + * @var string + * @access public + */ + public $tableName = 'member_contacts'; + + /** + * The template used to render the form + * + * @var string + * @access protected + */ + protected $formTemplate = 'editContacts.tpl'; + + /** + * Message to return if the form successfully submits + * + * @var string + * @access protected + */ + protected $successMsg = ' +
    + You successfully updated your contact. +
    '; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + * @see Toolkit_Members_EditMemberInfo + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $pdo, + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + } + + // }}} + + // {{{ configureDefaults() + + /** + * Sets the defaults for elements in the form. + * + * @return void + * @access public + */ + public function configureDefaults() + { + try { + if (isset($_GET['cid'])) { + $sql = " + select * from {$this->tableName} where id = :cid"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':cid', $_GET['cid'], PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $defaults['id'] = $row['id']; + $defaults['title'] = $row['title']; + $defaults['fname'] = $row['fname']; + $defaults['lname'] = $row['lname']; + $defaults['email'] = $row['email']; + $defaults['phone'] = $row['phone']; + $defaults['send_mail'] = $row['send_mail']; + } + $sql = " + SELECT *, fname || ' ' || lname AS name, + CASE send_mail + WHEN 'true' THEN 'Can Mail' + ELSE 'No Mail' + END AS send_mail + FROM {$this->tableName} + WHERE member_id = :id + ORDER BY id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + $i = 0; + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $defaults["cid$i"] = $row['id']; + $defaults["title$i"] = $row['title']; + $defaults["name$i"] = $row['name']; + $defaults["email$i"] = $row['email']; + $defaults["phone$i"] = $row['phone']; + $defaults["send_mail$i"] = $row['send_mail']; + ++$i; + } + $this->setupDefaults($defaults); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + $contacts = $this->getMemberContacts(); + // All Grouped Elements are created here. + $submitText = (isset($_GET['cid'])) ? 'Update' : 'Submit'; + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'fileHdr', + 'display' => 'Contacts' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'id' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'title', + 'display' => 'Title', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'fname', + 'display' => 'First Name', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'lname', + 'display' => 'Last Name', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'email', + 'display' => 'Email', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Phone', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'send_mail', + 'display' => 'Receive Mail', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit', + 'display' => $submitText, + 'opts' => array('class' => 'submit') + ); + if (is_array($contacts)) { + foreach ($contacts as $k => $v) { + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => "fileHdr$k" + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "cid$k" + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "name$k", + 'display' => 'Name' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "title$k" + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "email$k", + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "phone$k", + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "send_mail$k", + 'display' => 'Receive Mail' + ); + } + } + + $this->setupElements($e); + } + + // }}} + // {{{ configureForm() + + /** + * Wrapper function to handle setting up the form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureRules(); + $this->configureDefaults(); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up all the rules to be used when the form is validated. + * + * @return void + * @access public + */ + public function configureRules() + { + // form rules + $r = array(); + $this->registeredRules = array('phone', 'email'); + $r[] = array( + 'element' => 'email', + 'message' => 'ERROR: Invalid Email Address!', + 'type' => 'email', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + /* + $r[] = array( + 'element' => 'phone', + 'message' => 'ERROR: Invalid Phone Number!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + */ + $this->setupRules($r); + } + + // }}} + + // {{{ getDelUrl() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $sec Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function getDelUrl($sec) + { + return $_SERVER['REQUEST_URI'] . "&d=t&cid={$sec->elements[0]->html}"; + } + + // }}} + // {{{ getEditUrl() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $sec Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function getEditUrl($sec) + { + return $_SERVER['REQUEST_URI'] . "&cid={$sec->elements[0]->html}"; + } + + // }}} + // {{{ getImgUrl() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $type Parameter description (if any) ... + * + * @return string Return description (if any) ... + * @access public + */ + public function getImgUrl($type) + { + return BASE_URL . "assets/$type"; + } + + // }}} + // {{{ getMailIcon() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $sec Parameter description (if any) ... + * + * @return string Return description (if any) ... + * @access public + */ + public function getMailIcon($sec) + { + $status = $sec->elements[5]->html; + $icon = ($status == 'No Mail') ? '-Not-Ok' : '-Ok'; + return 'mail'; + } + + // }}} + // {{{ getMemberContacts() + + /** + * Get all the contacts data uploaded to a member into an array + * + * @return array member contacts + * @access protected + */ + protected function getMemberContacts() + { + $c = array(); + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE member_id = :id + ORDER BY id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch()) { + $c[] = $row; + } + return $c; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access public + */ + public function insertData($values) + { + unset( + $values['id'], + $values['target'], + $values['submit'] + ); + $values['member_id'] = $_GET['id']; + try { + $params = implode(', ', array_keys($values)); + $bindParams = ':' . implode(', :', array_keys($values)); + $sql = " + INSERT INTO {$this->tableName} ($params) + VALUES ($bindParams)"; + $stmt = $this->dbh->prepare($sql); + foreach ($values as $k => $v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } elseif ($metaData == 'double precision') { + $dataType = null; + } else { + $dataType = PDO::PARAM_STR; + } + $stmt->bindParam(":$k", $values[$k], $dataType); + } + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ isForm() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $sec Parameter description (if any) ... + * + * @return unknown Return description (if any) ... + * @access public + */ + public function isForm($sec) + { + return !$sec; + } + + // }}} + // {{{ isName() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $name Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function isName($name) + { + return (substr($name, 0, 4) == 'name') ? true : false; + } + + // }}} + // {{{ isPhone() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $name Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function isPhone($name) + { + return (substr($name, 0, 5) == 'phone') ? true : false; + } + + // }}} + // {{{ isEmail() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $name Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function isEmail($name) + { + return (substr($name, 0, 5) == 'email') ? true : false; + } + + // }}} + // {{{ isTitle() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $name Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function isTitle($name) + { + return (substr($name, 0, 5) == 'title') ? true : false; + } + + // }}} + + // {{{ processData() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return void + * @access public + */ + public function processData($values) + { + Toolkit_Common::getTableMetaData(); + if (empty($values['id'])) { + $this->insertData($values); + } else { + $this->updateData($values); + } + $listPage = BASE_URL . + "admin/members.php?cat=2&subCat=2&tab=6&id={$_GET['id']}"; + header("Location: $listPage"); + } + + // }}} + + // {{{ removeContact() + + /** + * Remove a contact from a member record + * + * @param integer $cid contact id + * @param integer $mid member id + * + * @return void + * @access public + */ + public function removeContact($cid, $mid) + { + try { + $sql = " + DELETE FROM {$this->tableName} + WHERE id = :cid + AND member_id = :mid"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':cid', $cid, PDO::PARAM_INT); + $stmt->bindParam(':mid', $mid, PDO::PARAM_INT); + $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ show() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + public function show() + { + if (isset($_GET['d'])) { + $this->removeContact($_GET['cid']); + $target = BASE_URL . 'admin/members.php?cat=2&subCat=2&tab=6&id='; + $target .= $_GET['id']; + header("Location: $target"); + } + Toolkit_Common::show(); + } + + // }}} + + // {{{ updateData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return boolean Return description (if any) ... + * @access public + */ + public function updateData($values) + { + if (array_key_exists('delete', $values)) { + $this->deleteFile($values); + } + + unset( + $values['target'], + $values['submit'] + ); + + try { + $params = array_keys($values); + $length = count($params); + for ($i = 0; $i < $length; ++$i) { + $bindParams .= "{$params[$i]} = :{$params[$i]}"; + if ($i < ($length - 1)) { + $bindParams .= ', '; + } + } + $sql = " + UPDATE {$this->tableName} + SET $bindParams + WHERE id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $pid, PDO::PARAM_INT); + foreach ($values as $k => $v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + $stmt->bindParam(":$k", $values[$k], $dataType); + } + $stmt->execute(); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + return false; + } + return true; + } + + // }}} +} +?> diff --git a/Toolkit/Members/EditMemberFile.php b/Toolkit/Members/EditMemberFile.php new file mode 100644 index 0000000..24e10a0 --- /dev/null +++ b/Toolkit/Members/EditMemberFile.php @@ -0,0 +1,549 @@ + + * @author Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditMemberFile.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Controls for uploading / editing files for a business record + * + * Controls all aspects of creating and rendering the form used to manipulate + * the business files. Form is not rendered until the user is added into the Database. + * + * @category MembersDB + * @package Toolkit_Members + * @author Steve Sutton + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_EditMemberFile + extends Toolkit_Members_EditMemberInfo implements Toolkit_Form +{ + // {{{ properties + + /** + * The table name in the database used to store the data of the files + * + * @var string + * @access public + */ + public $tableName = 'member_files'; + + /** + * The template used to render the form + * + * @var string + * @access protected + */ + protected $formTemplate = 'editFile.tpl'; + + /** + * Where the uploaded files are stored. + * + * @var string + * @access protected + */ + protected $uploadDir = 'uploads/member_files/'; + + /** + * Message to return if the form successfully submits + * + * @var string + * @access protected + */ + protected $successMsg = ' +
    + You successfully updated your file. +
    '; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + * @see Toolkit_Members_EditMemberInfo + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $pdo, + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + // Make sure we have the upload directory actually created so we can store our uploaded files. + if (!is_dir(BASE . $this->uploadDir)) { + $oldUmask = umask(0); + mkdir(BASE . $this->uploadDir, 0770); + umask($oldUmask); + } + } + + // }}} + + // {{{ configureDefaults() + + /** + * Sets the defaults for elements in the form. + * + * @return void + * @access public + */ + public function configureDefaults() + { + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE member_id = :id + ORDER BY id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + $i = 0; + $imgTag = 'pdf Image '; + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $defaults["file$i"] = $row['id']; + $defaults["file_name$i"] = (empty($row['file_name'])) ? + $row['original_name'] : $row['file_name']; + + $oname = (empty($row['file_name'])) ? + $row['original_name'] : $row['file_name']; + $defaults["original_name$i"] = '
    ' . + $imgTag . $oname . '
    '; + ++$i; + } + $this->setupDefaults($defaults); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @return void + * @access public + */ + public function configureElements() + { + $files = $this->getMemberFiles(); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $elements[] = array('type' => 'header', 'req' => false, 'name' => 'fileHdr', 'display' => 'Files'); + if (isset($_POST['uploaded_file_rmv'])) { + $elements[] = array('type' => 'hidden', 'req' => false, 'name' => 'uploaded_file_rmv'); + } + $elements[] = array('type' => 'text', 'req' => false, 'name' => 'file_name', 'display' => 'File Name'); + $elements[] = array('type' => 'file', 'req' => false, 'name' => 'file_rmv', 'display' => 'Upload a File', 'opts' => array('class' => 'submit')); + $elements[] = array('type' => 'submit', 'req' => false, 'name' => 'submitNewFile', 'display' => 'Upload new file', 'opts' => array('class' => 'submit')); + + if (is_array($files)) { + foreach ($files as $k => $v) { + $elements[] = array('type' => 'header', 'req' => false, 'name' => "fileHdr$k"); + $elements[] = array('type' => 'hidden', 'req' => false, 'name' => "file$k"); + $elements[] = array('type' => 'static', 'req' => false, 'name' => "original_name$k"); + $elements[] = array('type' => 'text', 'req' => false, 'name' => "file_name$k", 'display' => 'File Name', 'opts' => array('class' => 'text')); + $elements[] = array('type' => 'submit', 'req' => false, 'name' => 'update', 'display' => 'Update File Name', 'opts' => array('class' => 'submit')); + $elements[] = array('type' => 'submit', 'req' => false, 'name' => 'delete', 'display' => 'Delete File', 'opts' => array('class' => 'photoDelete fileDelete')); + } + } + + $this->setupElements($elements); + } + + // }}} + // {{{ configureForm() + + /** + * Wrapper function to handle setting up the form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureRules(); + $this->configureDefaults(); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up all the rules to be used when the form is validated. + * + * @return void + * @access public + */ + public function configureRules() + { + $this->registeredRules = array('memberfile'); + $mimeTypes = array( + 'application/pdf', + 'application/msword', + ); + + $r = array(); + + if (!empty($_FILES['file_rmv']['tmp_name'])) { + $r[] = array( + 'element' => 'file_rmv', + 'message' => 'ERROR: Incorrect File Type (.pdf, .doc) only!', + 'type' => 'mimetype', + 'format' => $mimeTypes, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + } + $r[] = array( + 'element' => 'file_rmv', + 'message' => 'ERROR: Invalid File!', + 'type' => 'memberfile', + 'format' => array($this, false), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $this->setupRules($r); + } + + // }}} + + // {{{ deleteFile() + + /** + * Remove the file from the disk and delet from the database + * + * @param string $values Form values + * + * @return boolean + * @access protected + */ + protected function deleteFile($values) + { + try { + $fid = $values["file{$values['target']}"]; + $this->dbh->beginTransaction(); + // Get the file name so we know what to look for when we try to + // delete the file from the disk. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $fid, PDO::PARAM_INT); + $stmt->execute(); + $file = $stmt->fetch(PDO::FETCH_ASSOC); + // Make sure the file actually exists, then try to remove it. + if (file_exists(BASE . $this->uploadDir . $file['name_on_disk'])) { + unlink(BASE . $this->uploadDir . $file['name_on_disk']); + } + + // Remove the photo from the updates table if one is present. + $sql = " + DELETE FROM {$this->pendingTable} + WHERE db_table = '{$this->tableName}' + AND member_id = :member_id + AND foreign_key = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->bindParam(':id', $fid, PDO::PARAM_INT); + $stmt->execute(); + + // Remove the file from the member. + $sql = " + DELETE FROM {$this->tableName} + WHERE id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $fid, PDO::PARAM_INT); + $stmt->execute(); + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ findTargetFile() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return integer Return description (if any) ... + * @access protected + */ + protected function findTargetFile($values) + { + foreach ($values as $k => $v) { + if (preg_match('/^file_name.+$/', $k, $matches)) { + return substr($k, 9); + } + } + } + + // }}} + + // {{{ getMemberFiles() + + /** + * Get all the file data uploaded to a member into an array + * + * @return array member files + * @access protected + * @see Toolkit_FormBuilder::setupDefaults() + */ + protected function getMemberFiles() + { + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE member_id = :id + ORDER BY id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $files[] = $row; + } + return $files; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * @param boolean $pending Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access public + */ + public function insertData($values, $pending = false) + { + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member_Profile-{$_GET['id']}", 'Dynamic'); + + $insertData['name_on_disk'] = $values['uploaded_file_rmv']; + $insertData['member_id'] = $_GET['id']; + $insertData['size'] = $values['file_rmv']['size']; + $insertData['original_name'] = $values['file_rmv']['name']; + $insertData['file_name'] = $values['file_name']; + $insertData['pending'] = $pending; + try { + $params = implode(', ', array_keys($insertData)); + $bindParams = ':' . implode(', :', array_keys($insertData)); + $sql = " + INSERT INTO {$this->tableName} ($params) + VALUES ($bindParams)"; + $stmt = $this->dbh->prepare($sql); + foreach ($insertData as $k => &$v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + $stmt->bindParam(":$k", $v, $dataType); + } + + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ processData() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return void + * @access public + */ + public function processData($values) + { + Toolkit_Common::getTableMetaData(); + $values['target'] = $this->findTargetFile($values); + + if (array_key_exists('submitNewFile', $values)) { + $this->insertData($values); + } else { + $this->updateData($values); + } + $listPage = BASE_URL . + "admin/members.php?cat=2&subCat=2&tab=5&id={$_REQUEST['id']}"; + header("Location: $listPage"); + } + + // }}} + + // {{{ showFile() + + /** + * Used in the template to determine when to show the File + * + * Since the file tag falls outside of the normal flow of the section loop + * we need to determine early if we should display the file or not. Since + * the file is the only element that uses a "static" quickform element, + * check to see if the first element type in a section is a static element + * and if so output the element (file). + * + * @param array $data The array of element objec + * + * @return boolean Whether an element is of type static or not. + * @access public + */ + public function showFile($data) + { + return ($data->type == 'static'); + } + + // }}} + + // {{{ updateData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function updateData($values) + { + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member_Profile-{$_GET['id']}", 'Dynamic'); + + if (array_key_exists('delete', $values)) { + return $this->deleteFile($values); + } + $target = $values['target']; + foreach ($values as $k => $v) { + switch ($k) { + case "file_name$target" : + $values['file_name'] = $v; + unset($values[$k]); + break; + + case "file$target" : + $pid = $v; + unset($values[$k]); + break; + + default : + unset($values[$k]); + break; + } + } + + try { + $params = array_keys($values); + $length = count($params); + for ($i = 0; $i < $length; ++$i) { + $bindParams .= "{$params[$i]} = :{$params[$i]}"; + if ($i < ($length - 1)) { + $bindParams .= ', '; + } + } + $sql = " + UPDATE {$this->tableName} + SET $bindParams + WHERE id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $pid, PDO::PARAM_INT); + foreach ($values as $k => $v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + $stmt->bindParam(":$k", $values[$k], $dataType); + } + $stmt->execute(); + + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + return false; + } + return true; + } + + // }}} +} +?> diff --git a/Toolkit/Members/EditMemberInfo.php b/Toolkit/Members/EditMemberInfo.php new file mode 100644 index 0000000..3e67a47 --- /dev/null +++ b/Toolkit/Members/EditMemberInfo.php @@ -0,0 +1,3109 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditMemberInfo.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +require_once BASE . 'Toolkit/Image/Server.php'; + +/** + * Edit member info stored in the database + * + * Controls all aspects of creating and rendering the form used to manipulate + * the member data. Handles adding / editing module details, including: + * 1. Restaurants + * 2. Accommodations + * 3. Golfing + * + * Controls the addition of categories to a member record. Categories have + * dynamic settings which allow users to dynamically set which categories are + * associated to which modules (golf, accommodations, restaurant, etc...). + * Depending on which category is selected and assigned to a member record + * controls which modules are displayed on the form. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com/admin/members.php?cat=2&subCat=2 + * @see Toolkit_Members, member_admin + */ +class Toolkit_Members_EditMemberInfo + extends Toolkit_FormBuilder implements Toolkit_Form +{ + // {{{ properties + + /** + * The Table name used to store the data of the member record in the database. + * + * @var string + * @access public + */ + public $tableName = 'member'; + + /** + * Array of data that holds the meta data info on the table + * + * Contains information on the type of fields in the database. + * That way when we run our automated SQL queries with our PDO + * we can properly bind data to our SQL queries. This will + * allow for one more layer of protection against any sql + * injection attempts. + * + * @var string + * @access public + * @see Toolkit_Common::processData() + */ + public $tableMetaData; + + /** + * Determines if member updates have to be approved if changed + * + * If set to true, all module info must be approved by admin before it + * will be displayed on the front end to visitors. This also includes + * ccard information. + * + * Since all member forms will be spawned from this class, if we put + * this value here we can set once / change once and affect the entire + * app if we need to alter this. We can also set this up in any child + * class and override on individual classes if need be. + * + * @var string + * @access protected + */ + protected $strictPending = true; + + /** + * The table used to store the data of the member record in the database. + * + * @var string + * @access public + */ + public $pendingTable = 'member_updates'; + + /** + * Determines if a member is in the pending state or not + * + * When the member has rows of data in the member_updates table in the DB + * they are considered "pending updates" until those changes are accepted + * or rejected by an admin user. + * + * @var string + * @access public + */ + public $pending = false; + + /** + * holds all the fields that are currently pending + * + * used in conjunction with the template, all fields that are in this + * list, will have a pending class for the row, so they can easily + * be identified. + * + * @var string + * @access public + */ + public $pendingFields = array(); + + // What are the modules associated with this form. + // New members won't have access to these right away. + // This boolean settings will be overridden inside the class. + + /** + * The status of accommodation related categories associated w/ the member + * + * If the member has any categories that are assigned to the accommodations + * module, then this setting will become true and the form will show + * the accommodation module. + * + * @var bool + * @access protected + */ + protected $accommodations = false; + + /** + * The status of restaurant related categories associated w/ the member + * + * If the member has any categories that are assigned to the restaurant + * module, then this setting will become true and the form will show + * the restaurant module. + * + * @var bool + * @access protected + */ + protected $restaurant = false; + + /** + * The status of golf related categories associated w/ the member + * + * If the member has any categories that are assigned to the golf + * module, then this setting will become true and the form will show + * the golf module. + * + * @var bool + * @access protected + */ + protected $golf = false; + + /** + * States array for select list + * + * @var array + * @access protected + */ + protected $states; + + /** + * Category record objects + * + * Used when creating the category select list. + * + * @var array + * @access protected + */ + protected $records = array(); + + /** + * The categories the member has associated with it + * + * @var array + * @access protected + */ + protected $memberCategories = null; + + /** + * Primary email address to send notification a record has been updated + * + * Set this value to false and it will turn off the email + * update notifications. + * + * @var string + * @access protected + */ + protected $primaryAdvisee; + + /** + * Email address of people that might also want to be advised of updates + * + * A list of all email address that might also want to be advised + * updates have been made on a business record. You can add as many + * as you would like and they will be CC in the email. + * + * N.B. You cannot make this array bigger than 5 people or you will need to + * rewrite the function to handle the server spam issue. + * @var array + * @access private + */ + protected $secondaryAdvisees = array(); + + /** + * Flexy options used in the renderer + * + * @var array + * @access protected + */ + protected $flexyOptions; + + /** + * The name of the template used to render the business info form + * + * @var string + * @access protected + */ + protected $formTemplate = 'editMember.tpl'; + + /** + * The name of the template used to email the owner for any updates + * + * When a member makes an update to thier record, this is the template + * we will use to send out the email notification to the site owner. + * + * @var string + * @access protected + */ + protected $emailTemplate = 'emailOwner.tpl'; + + /** + * Message to return if the form successfully submits + * + * @var string + * @access protected + */ + protected $successMsg = ' +
    + The information below has been successfully submitted. +
    '; + + /** + * The flexy template object which holds the rendered object + * + * @var object + * @access protected + */ + protected $template; + + /** + * Form access from inside the template + * + * @var object + * @access protected + */ + protected $view; + + /** + * Extra rules we need to register so we can fully validate form elements + * + * @var array + * @access protected + */ + protected $registeredRules = array( + 'zip', + 'phone', + array( + 'checkEmail', + 'callback', + 'email', + 'Validate' + ), + array( + 'checkURI', + 'callback', + 'uri', + 'Validate' + ) + ); + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + * @see Toolkit_FormBuilder, HTML_QuickForm + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + // if this value is set to false, then no emails will be sent out + // upon update of a record. + if ($this->primaryAdvisee !== false) { + if (!defined('MEMBER_RECORD_UPDATES_ADVISOR')) { + // Please see property definition above for explanation. + echo 'in file: [' . __FILE__ . ' ] on line: [' . __LINE__ . ']
    '; + echo ' +

    + Please define the + MEMBER_RECORD_UPDATES_ADVISOR constant + in the setup file first.

    This Constant should hold + the email address of the person you would like notified + when a member submits an update.
    Set to false if you do + not want an email to be sent. +

    '; + die; + } + $this->primaryAdvisee = MEMBER_RECORD_UPDATES_ADVISOR; + } + // If you want to add secondary advisors that will also receive + // an email when a record is updated, update the property here. + // If you use associative key values then they will be appended + // to the email string. i.e. + // Jamie Kahgee + // Other wise the address will just be added. + $this->secondaryAdvisees = array( + //'Jamie Kahgee' => 'jamie.kahgee+secondaryAdvisorTest1@gmail.com', + //'Jodie Bissonette' => 'jodie@gaslightmedia.com', + ); + + $this->dbh = $pdo; + + $this->flexyOptions = Toolkit_Members::getFlexyOptions(); + } + + // }}} + + // {{{ addInfoElement() + + /** + * Determines if the element is supposed to display additional info + * + * @param string $element name of element + * + * @return boolean True if supposed to display additional info. + * false otherwise + * @access public + */ + function addInfoElement($element) + { + switch ($element) { + case 'street' : + case 'member_contact_email' : + return true; + break; + + default : + return false; + break; + } + } + + // }}} + + // {{{ checkMemberName() + + /** + * Checks if the member name already exists in the database + * + * @param array $data The name of the member to check for. + * + * @return bool False on SQL Query error, otherwise true. + * @access protected + */ + public function checkMemberName($data) + { + try { + // If we're editing a member, they + // can save that member as its + // own name. so don't include that + // member in the check. + if (is_numeric($_GET['id'])) { + $and = "AND member_id != :id"; + } + $sql = " + SELECT count(*) AS total + FROM member + WHERE member_name = :name + $and"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':name', $data, PDO::PARAM_STR); + if (is_numeric($_GET['id'])) { + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_STR); + } + $stmt->execute(); + $stmt->bindColumn('total', $valid); + $stmt->fetch(); + + return !(bool) $valid; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ checkUName() + + /** + * Checks if the login name already exists in the database + * + * @param array $data The name of the member to check for. + * + * @return boolean False on SQL Query error, otherwise true. + * @access protected + */ + public function checkUName($data) + { + try { + // If we're editing a member, they + // can save that member as its + // own name. so don't include that + // member in the check. + if (is_numeric($_GET['id'])) { + $and = "AND member_id != :id"; + } + $sql = " + SELECT count(*) AS total + FROM {$this->tableName} + WHERE member_login = :name + $and"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':name', $data, PDO::PARAM_STR); + if (is_numeric($_GET['id'])) { + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_STR); + } + $stmt->execute(); + $stmt->bindColumn('total', $valid); + $stmt->fetch(); + + return !(bool) $valid; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ checkDate() + + /** + * Validate date input + * + * allows for empty dates to be valid + * + * @param array $date date group from form + * + * @return boolean true if valid, false if not + * @access public + */ + public function checkDate($date) + { + $validate = false; + foreach ($date as $i) { + if (is_numeric($i)) { + $validate = true; + break; + } + } + + if ($validate) { + // at least one date list had a number in it. + $d = implode('-', $date); + return Validate::date($d, array('format' => '%n-%j-%Y')); + } else { + // no date numbers were selected + return true; + } + } + + // }}} + // {{{ clearModule() + + /** + * Removes a module from a member + * + * When updating a member this function is called for every module. + * Then if the member still has that module category assigned to them + * the data will be re-inserted back into the db. Otherwise it will + * removed and not associated with that member anymore. + * + * @param string $tableName The name of the table / module to clear + * + * @return Boolean False on SQL Query error, otherwise true. + * @access protected + */ + protected function clearModule($tableName) + { + try { + $sql = " + DELETE FROM $tableName + WHERE member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ createCategories() + + /** + * Creates an array from the array of category tree objects + * + * @param array $tree linear tree array of member categories + * @param integer $depth what level we are on + * + * @return array The array list of categories that + * that can be loaded into a select element + * @access protected + */ + protected function createCategories($tree, $depth = 0) + { + $this->records[] = $tree->category; + if ($depth == 0) { + $this->categories[$tree->catid] = "{$tree->category}"; + } else { + $this->categories[$tree->catid] = $tree->category; + } + if (empty($tree->children)) { + return; + } else { + ++$depth; + foreach ($tree->children as $miniTrees) { + $this->createCategories($miniTrees, $depth); + } + } + } + + // }}} + // {{{ configureConstants() + + /** + * Sets the constants for the form + * + * The member category select list must always default + * to the -- Choose Category -- option + * + * @return void + * @access public + */ + public function configureConstants() + { + $c = array(); + + // set the remove_logo_rmv element to 0 so + // if a logo is uploaded and then the remove + // checkbox is checked and the form is submitted + // it won't retain its checked status. + $c = array( + 'member_cats[]' => '', + 'remove_logo_rmv' => 0, + ); + + $this->setupConstants($c); + } + + // }}} + // {{{ configureDefaults() + + /** + * Sets the defaults for the an existing member + * + * Populates data for the main member form. Also grabs + * data to populate the modules on the form if needed. + * + * @return array $defaults Returns the array of defaults + * so children who call this function + * can obtain a copy of these values. + * @access public + */ + public function configureDefaults() + { + $existingMember = (is_numeric($_GET['id'])); + if ($existingMember) { + try { + $member_id = $_GET['id']; + // Get the data for the main form items + $sql = " + SELECT * + FROM {$this->tableName} + WHERE member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + foreach ($row as $k => $v) { + if ($k == 'logo') { + $defaults['old_logo_rmv'] = $v; + $k = 'image_rmv'; + $v = ''.$v.''; + } + $defaults[$k] = $v; + } + } + + // Set the defaults for the credit cards. + $sql = " + SELECT cct.*, mcct.* + FROM ccard_type cct, member_ccard_type mcct + WHERE cct.ccard_type_id = mcct.ccard_type_id + AND mcct.member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT); + $stmt->execute(); + while ($member = $stmt->fetch(PDO::FETCH_ASSOC)) { + $defaults["creditCards[{$member['ccard_type_name']}]"] = true; + } + + $moduleTables = array( + 'member_accommodations', + 'member_golf', + 'member_restaurants', + ); + foreach ($moduleTables as $table) { + $sql = " + SELECT * + FROM $table + WHERE member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + foreach ($row as $k => $v) { + $defaults[$k] = $v; + } + } + } + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } else { + $defaults = array( + 'member_cats[]' => '', + 'state_id' => '', + 'country' => '', + ); + } + + $this->setupDefaults($defaults); + return $defaults; + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * Categories are populated into the protected class property $categories. + * These categories are used to populate the select list of categories. + * Modules are configured before any elements are setup, that way we will + * know if we need to include them in the rendering of the form. + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + + // get reference to [listing type] section of config file + $config =& $this->config->getItem('section', 'listing type'); + // get coupon + $singularDirective =& $config->getItem('directive', 'singular'); + $singularType = $singularDirective->getContent(); + $pluralDirective =& $config->getItem('directive', 'plural'); + $pluralType = $pluralDirective->getContent(); + + // get reference to [conf] section of config file + $config =& $this->config->getItem('section', 'conf'); + // get controlled cities + $ctrlCtyDirective =& $config->getItem('directive', 'controlledCities'); + // get region + $rgnDirective =& $config->getItem('directive', 'regions'); + + $this->setupFormCategories(); + $this->configureModules(); + + $this->getCategories(); + + // All Grouped Elements are created here. + // All Elements are created here. This includes group element definitions. + + // {{{ Member Information + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'memberInfoHdr', + 'display' => "$singularType Information", + 'col1' => true + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => true, + 'name' => 'active', + 'display' => 'Status', + 'opts' => 'Active', + 'val' => array(0, 1), + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'member_name', + 'display' => "$singularType Name", + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'primary_contact_fname', + 'display' => 'Primary Contact First Name', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'primary_contact_lname', + 'display' => 'Primary Contact Last Name', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'process_email', + 'display' => 'Primary Contact Email', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'select3', + 'req' => false, + 'name' => 'member_cats[]', + 'display' => "$singular Category", + 'opts' => $this->categories, + 'att' => array('id' => 'categories') + ); + $e[] = array( + 'type' => 'date', + 'req' => false, + 'name' => 'join_date', + 'display' => "$singularType Since", + 'opts' => array( + 'format' => 'm / d / Y', + 'minYear' => 2009, + 'maxYear' => date('Y'), + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy', + ) + ) + ); + if ($rgnDirective->getContent()) { + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'region', + 'display' => 'Region', + 'opts' => $this->getRegions() + ); + } + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Primary Phone', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'toll_free', + 'display' => 'Toll Free Phone', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fax', + 'display' => 'Fax Number', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'member_contact_email', + 'display' => 'Email on Website', + 'opts' => array('class' => 'text') + ); + /* + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'country', + 'display' => 'Country', + 'opts' => array( + '' => '-- Select Country --', + 'USA' => 'USA', + 'Canada' => 'Canada' + ) + ); + */ + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'url', + 'display' => 'Website Address', + 'opts' => array('class' => 'text') + ); + + // }}} + // {{{ Physical Address + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'physicalAddressHdr', + 'display' => 'Street Address', + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'street', + 'display' => 'Street Address', + 'opts' => array('class' => 'text') + ); + if ($ctrlCtyDirective->getContent()) { + $e[] = array( + 'type' => 'select', + 'req' => true, + 'name' => 'city_id', + 'display' => 'City', + 'opts' => $this->getCities(), + ); + } else { + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'city', + 'display' => 'City', + 'opts' => array('class' => 'text') + ); + } + $e[] = array( + 'type' => 'select', + 'req' => true, + 'name' => 'state_id', + 'display' => 'State / Province', + 'opts' => $this->states + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'zip', + 'display' => 'Zip / Postal Code', + 'opts' => array('class' => 'text') + ); + + // }}} + // {{{ Mailing Address + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'MailingAddressHdrRmv', + 'display' => 'Mailing Address (if different than physical address)', + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'mailing_address', + 'display' => 'Mailing Address', + 'opts' => array('class' => 'text') + ); + if ($ctrlCtyDirective->getContent()) { + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'mailing_city_id', + 'display' => 'City', + 'opts' => $this->getCities(), + ); + } else { + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'mailing_city', + 'display' => 'City', + 'opts' => array('class' => 'text') + ); + } + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'mailing_state_id', + 'display' => 'State / Province', + 'opts' => $this->states + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'mailing_zip', + 'display' => 'Zip / Postal Code', + 'opts' => array('class' => 'text') + ); + + // }}} + // {{{ Member Description + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'memberDescHdr', + 'display' => "$singular Description", + 'col1' => true + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'display' => null, + 'opts' => array( + 'id' => 'description', + 'rows' => 8, + 'cols' => 43 + ) + ); + + // }}} + // {{{ Account Info + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'accountInfoHdr', + 'display' => 'Account Info', + 'col2' => true + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'member_login', + 'display' => 'Username', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'member_passwd', + 'display' => 'Password', + 'opts' => array('class' => 'text') + ); + + // }}} + // {{{ Member Logo + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'logoHdr', + 'display' => "$singular Logo", + 'col2' => true + ); + if ($this->hasLogo()) { + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'remove_logo_rmv', + 'display' => 'Remove Logo' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'image_rmv', + 'display' => 'Current Logo' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'old_logo_rmv' + ); + } + + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'new_logo_rmv', + 'display' => 'New Logo', + 'opts' => array('class' => 'file') + ); + + // }}} + // {{{ Payment Type Accepted + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'CreditCardsHdr', + 'display' => 'Payment Type Accepted', + 'col2' => true + ); + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'creditCards[American Express]', + 'display' => 'American Express' + ); + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'creditCards[Discover]', + 'display' => 'Discover' + ); + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'creditCards[Master Card]', + 'display' => 'Master Card' + ); + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'creditCards[Visa]', + 'display' => 'Visa' + ); + + // }}} + // {{{ Accommodations Information + + if ($this->accommodations) { + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'AccommodationsHdr', + 'display' => 'Accommodations Information', + 'col2' => true + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'reservation_id', + 'display' => 'Reservation Id', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'num_rooms', + 'display' => 'Number of Rooms', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'year_round', + 'display' => 'Open all Year', + 'val' => array(0, 1) + ); + } + + // }}} + // {{{ Restaurant Information + + if ($this->restaurant) { + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'RestaurantHdr', + 'display' => 'Restaurant Information', + 'col2' => true + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'breakfast', + 'display' => 'Breakfast', + 'att' => array('id' => 'breakfast'), + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'breakfast_from', + 'display' => 'From', + 'opts' => array('class' => 'priceFrom') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'breakfast_to', + 'display' => 'To', + 'opts' => array('class' => 'priceTo') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'brunch', + 'display' => 'Brunch', + 'att' => array('id' => 'brunch'), + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'brunch_from', + 'display' => 'From', + 'opts' => array('class' => 'priceFrom') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'brunch_to', + 'display' => 'To', + 'opts' => array('class' => 'priceTo') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'lunch', + 'display' => 'Lunch', + 'att' => array('id' => 'lunch'), + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'lunch_from', + 'display' => 'From', + 'opts' => array('class' => 'priceFrom') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'lunch_to', + 'display' => 'To', + 'opts' => array('class' => 'priceTo') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'dinner', + 'display' => 'Dinner', + 'att' => array('id' => 'dinner'), + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'dinner_from', + 'display' => 'From', + 'opts' => array('class' => 'priceFrom') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'dinner_to', + 'display' => 'To', + 'opts' => array('class' => 'priceTo') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'alcohol', + 'display' => 'Alcohol', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'non_smoking', + 'display' => 'Non-Smoking', + 'val' => array(0, 1) + ); + } + + // }}} + // {{{ Golf Information + + if ($this->golf) { + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'GolfingHdr', + 'display' => 'Golf Course Information', + 'col2' => true + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'par', + 'display' => 'Par', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'yardage', + 'display' => 'Yardage', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'course_rating', + 'display' => 'Course Rating', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'slope_rating', + 'display' => 'Slope Rating', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'walking_course', + 'display' => 'Walking Course', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'holes18', + 'display' => '18 Holes', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'holes9', + 'display' => '9 Holes', + 'opts' => array('class' => 'text') + ); + } + + // }}} + // {{{ Social Media Links + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'SocialMediaHdr', + 'display' => 'Social Media Links', + 'col2' => true, + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'facebook', + 'display' => 'Facebook', + 'col2' => true, + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'twitter', + 'display' => 'Twitter', + 'col2' => true, + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'myspace', + 'display' => 'MySpace', + 'col2' => true, + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'linkedin', + 'display' => 'LinkedIn', + 'col2' => true, + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'blog', + 'display' => 'Blog', + 'col2' => true, + ); + + // }}} + + $this->setupElements($e); + } + + // }}} + // {{{ configureFilters() + + /** + * Setup the filters to apply to the elements before we are + * handed the values submitted + * + * @return void + * @access public + */ + public function configureFilters() + { + $f = array(); + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + $f[] = array( + 'element' => 'facebook', + 'filter' => array(&$this, 'filterURI') + ); + $f[] = array( + 'element' => 'twitter', + 'filter' => array(&$this, 'filterURI') + ); + $f[] = array( + 'element' => 'myspace', + 'filter' => array(&$this, 'filterURI') + ); + $f[] = array( + 'element' => 'linkedin', + 'filter' => array(&$this, 'filterURI') + ); + $f[] = array( + 'element' => 'blog', + 'filter' => array(&$this, 'filterURI') + ); + $f[] = array( + 'element' => 'url', + 'filter' => array(&$this, 'filterURI') + ); + $f[] = array( + 'element' => 'phone', + 'filter' => array(&$this, 'filterPhone') + ); + $f[] = array( + 'element' => 'fax', + 'filter' => array(&$this, 'filterPhone') + ); + $f[] = array( + 'element' => 'toll_free', + 'filter' => array(&$this, 'filterPhone') + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Wrapper function to handle setting up the form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + $this->configureDefaults(); + $this->configureConstants(); + } + + // }}} + // {{{ configureModules() + + /** + * Turns on a modules if the member has the appropriate category + * + * @return void + * @access protected + */ + protected function configureModules() + { + if (is_array($this->memberCategories)) { + try { + $sql = " + SELECT * + FROM category + WHERE category_id = :cid"; + $stmt = $this->dbh->prepare($sql); + foreach ($this->memberCategories as $cid => $v) { + $stmt->bindParam(':cid', $cid, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if ($row['accommodations'] == 't') { + $this->accommodations = true; + } + if ($row['restaurant'] == 't') { + $this->restaurant = true; + } + if ($row['golf'] == 't') { + $this->golf = true; + } + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + } + + // }}} + // {{{ configureRules() + + /** + * Sets up all the rules to be used when the form is validated. + * + * @return void + * @access public + */ + public function configureRules() + { + $mimeTypes = array( + 'image/jpe', + 'image/jpeg', + 'image/jpg', + 'image/jfif', + 'image/pjpeg', + 'image/pjp', + 'image/gif', + 'image/png', + ); + + $r = array(); + + $r[] = array( + 'element' => 'reservation_id', + 'message' => 'ERROR: Must be an integer!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'process_email', + 'message' => 'ERROR: Invalid email format!', + 'type' => 'checkEmail', + 'format' => array('use_rfc822' => true), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'member_contact_email', + 'message' => 'ERROR: Invalid email format!', + 'type' => 'checkEmail', + 'format' => array('use_rfc822' => true), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'join_date', + 'message' => 'ERROR: Invalid date!', + 'type' => 'callback', + 'format' => array(&$this, 'checkDate'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'url', + 'message' => 'ERROR: Invalid URL format', + 'type' => 'checkURI', + 'format' => array( + 'allowed_schemes' => array('http', 'https'), + 'strict' => true + ), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'num_rooms', + 'message' => 'ERROR: Must be an integer!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'member_name', + 'message' => 'ERROR: There is an existing account with this name!', + 'type' => 'callback', + 'format' => array($this, 'checkMemberName'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'member_login', + 'message' => 'ERROR: Sorry, but this username has already been taken!', + 'type' => 'callback', + 'format' => array($this, 'checkUName'), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'state_id', + 'message' => 'ERROR: Invalid State!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'mailing_state_id', + 'message' => 'ERROR: Invalid State!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'region', + 'message' => 'ERROR: Invalid Region!', + 'type' => 'numeric', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'zip', + 'message' => 'ERROR: Invalid Zip Code!', + 'type' => 'zip', + 'format' => array('requireDBCheck' => false), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'mailing_zip', + 'message' => 'ERROR: Invalid Zip Code!', + 'type' => 'zip', + 'format' => array('requireDBCheck' => false), + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'phone', + 'message' => 'ERROR: Invalid Phone Number! (xxx) xxx-xxxx', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'fax', + 'message' => 'ERROR: Invalid Phone Number! (xxx) xxx-xxxx', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'toll_free', + 'message' => 'ERROR: Invalid Phone Number! (xxx) xxx-xxxx', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'new_logo_rmv', + 'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!', + 'type' => 'mimetype', + 'format' => $mimeTypes, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ emailOwner() + + /** + * Emails the owner and anyone else who wants to be advised of updates + * + * A false value in the primaryAdvisee will cause no email to be sent. + * all secondary advisees listed in the constructor are carbon copied + * in the email. + * + * Emails are sent out in both HTML and TXT forms. + * + * @return boolean result of email + * @access protected + */ + protected function emailOwner() + { + if ($this->primaryAdvisee === false) { + return; + } else { + try { + $sql = " + SELECT member_name + FROM member + WHERE member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $memberName = $row['member_name']; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass(); + $page->member = $memberName; + $page->url = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL : BASE_URL; + $page->email = OWNER_EMAIL; + $page->siteName = SITENAME; + $page->link = 'link'; + + $template->compile($this->emailTemplate); + // Merge the compiled template with the $page object. + $htmlMsg = $template->bufferedOutputObject($page); + + $msg = " +

    $memberName

    +

    + Has updated thier business record and is now in a pending + state. To approve / reject thier changes you can either log + into your {$page->siteName} admin area or follow this + {$page->link} +

    "; + $crlf = "\n"; + $mimeMail = new Mail_mime($crlf); + $from = ereg_replace("[^A-Za-z ]", "", SITENAME) . ' <' . OWNER_EMAIL . '>'; + $mimeMail->setFrom($from); + $mimeMail->setSubject('Member Record Update'); + if (!empty($this->secondaryAdvisees)) { + foreach ($this->secondaryAdvisees as $k => $v) { + if (is_string($k) && !is_numeric($k)) { + $email = "$k <$v>"; + } else { + $email = $v; + } + $mimeMail->addCC($email); + } + } + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $mail =& Mail::factory('mail'); + $body = $mimeMail->get(); + $headers = $mimeMail->headers($hdrs); + + $res = $mail->send($this->primaryAdvisee, $headers, $body); + if (PEAR::isError($res)) { + return Toolkit_Common::handleError($res); + } else { + return $res; + } + } + } + + // }}} + + // {{{ fieldPending() + + /** + * Determines if template fields are pending or not + * + * Each field in the template calls this function to determine if it + * is in a pending state or not. Fields that return true get a + * different colored background and border so they are easily recognizable. + * + * fields are considered pending if they are in the pendingFields array. + * + * @param string $elem element to check for pending + * + * @return boolean If the field is pending + * @access protected + */ + public function fieldPending($elem) + { + if (!is_array($this->pendingFields)) { + return false; + } else { + return in_array($elem->name, $this->pendingFields); + } + } + + // }}} + // {{{ filterURI() + + /** + * Filters uri's before they are validated + * + * @param string $uri URI to filter + * + * @return mixed new uri if missing scheme + * @access + */ + protected function filterURI($uri) + { + if (strstr($uri, 'http://') != $uri) { + return "http://$uri"; + } else { + return $uri; + } + } + + // }}} + // {{{ filterPhone() + + /** + * Filters phone numbers before they are validated + * + * @param string $phone number to filter + * + * @return mixed newly formatted phone number + * @access + */ + protected 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; + } + + // }}} + + // {{{ generateLatLon() + + /** + * Generates the listings lat and lon coordinates from either an address + * or their zip code. Depending on what gets entered into the form. + * + * If generating by zip code, we simply query the zip DB stored on ds3. + * Otherwise we query using google. + * + * @param mixed $data Array of data or zip + * + * @return Array Array of lat/lon coordinates + * @access protected + */ + protected function generateLatLon($data) + { + if (is_array($data)) { + try { + // Since we don't store the city or state names we need to query + // for it really quick to get it. + $sql = " + SELECT state_name + FROM state s + WHERE state_id = :sid"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':sid', $data['state_id'], PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + // Use google maps to get the lan/lon coords from our data. + $api_key = 'ABQIAAAAWqyv9sBAgUBdsdOdgo7LsRTeX7yNUukyMrmY8FsCXcCA9axlYBRmLDu7pJM7HIzM1e6MYO-pqjjp5w'; + $addr = $values['street']; + $city = $values['city']; + $state = $row['state_name']; + $zip = $values['zip']; + $url = "http://maps.google.com/maps/geo?output=xml&key=$api_key&q="; + $q = "$addr, $city, $state, $zip"; + $url .= urlencode($q); + // Query Google for this location's longitude and latitude + $command = "/usr/bin/curl '$url'"; + exec($command, $output, $return); + if (preg_match_all("/(-?[0-9]{1,2}\.[0-9]{6})\,(-?[0-9]{1,2}\.[0-9]{6})\,0<\/coordinates>/", $output[0], $temp)) { + if (isset($temp[1][1])) { + $lon = $temp[1][1]; + $lat = $temp[2][1]; + } elseif (isset($temp[1][0])) { + $lon = $temp[1][0]; + $lat = $temp[2][0]; + } else { + $lat = 'NULL'; + $lon = 'NULL'; + } + } + $lat_lon['lat'] = $lat; + $lat_lon['lon'] = $lon; + return $lat_lon; + } else { + // We have a zip, just lookup in the db. + try { + $dsn = 'pgsql:host=ds3.gaslightmedia.com user=postgres dbname=zip'; + $driverOptions = array( + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + ); + $zipPDO = new PDO($dsn, null, null, $driverOptions); + $zipPDO->setAttribute( + PDO::ATTR_ERRMODE, + PDO::ERRMODE_EXCEPTION + ); + + $sql = " + SELECT lat, lon + FROM zip + WHERE zipcode = :zip"; + $stmt = $zipPDO->prepare($sql); + $stmt->bindParam(':zip', $data); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $return['lat'] = (float) $row['lat']; + $return['lon'] = (float) $row['lon']; + return $return; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + } + + // }}} + // {{{ getCategories() + + /** + * Creates array structure of the category tree for use in a select element. + * + * This method will also instantiate a class property called tree for your + * class. This object will hold the tree structure of the categories list + * from the Database. + * + * @return array The array list of categories that can be loaded + * into a select element + * + * @access protected + * @see Toolkit_Members_CategoryTree + */ + protected function getCategories() + { + try { + $sql = " + SELECT * + FROM category + WHERE parent_id = 0 + ORDER BY name"; + foreach ($this->dbh->query($sql, PDO::FETCH_ASSOC) as $row) { + $this->tree[] = new Toolkit_Members_CategoryTree($row['category_id'], + $row['name'], + $this->dbh); + } + if (!empty($this->tree)) { + foreach ($this->tree as $t) { + $this->createCategories($t); + } + } + + if (empty($this->categories)) { + $this->categories = array('' => '-- No Categories Created Yet --'); + } else { + $this->categories + = array('' => '-- Select Category --') + $this->categories; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getRegions() + + /** + * Configure the regions for member stored in the database into an array + * + * @return array the regions + * @access protected + */ + protected function getRegions() + { + try { + $sql = " + SELECT * + FROM region + ORDER BY region_name"; + foreach ($this->dbh->query($sql) as $row) { + $regions[$row['region_id']] = $row['region_name']; + } + if (!empty($regions)) { + $regions = array('' => '-- Choose Region --') + $regions; + } else { + $regions = array('' => '-- No Regions Created Yet -- '); + } + return $regions; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getCities() + + /** + * Configure the cities for member stored in the database into an array + * + * @return array the cities + * @access protected + */ + protected function getCities() + { + try { + $sql = " + SELECT * + FROM city + ORDER BY city_name"; + foreach ($this->dbh->query($sql) as $row) { + $regions[$row['city_id']] = $row['city_name']; + } + if (!empty($regions)) { + $regions = array('' => '-- Choose City --') + $regions; + } else { + $regions = array('' => '-- No Cities Created Yet -- '); + } + return $regions; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ hasLogo() + + /** + * Determine if the member record has a logo + * + * @return boolean if the record has a logo or not + * @access protected + */ + protected function hasLogo() + { + try { + $member_id = $_GET['id']; + + $sql = " + SELECT logo + FROM {$this->tableName} + WHERE member_id = :member_id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + if (get_class($this) === 'Toolkit_Members_EditMemberOnlyInfo') { + $sql = " + SELECT count(*) AS total + FROM {$this->pendingTable} + WHERE member_id = :member_id + AND field = 'logo'"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT); + $stmt->execute(); + $pendingLogos = $stmt->fetch(PDO::FETCH_ASSOC); + } + + $hasPending = !empty($pendingLogos['total']); + $hasLogo = !is_null($row['logo']); + + return ($hasLogo || $hasPending); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ inColumn2() + + /** + * Lets the form know when to add a new column + * + * When rendering the form, we need to know what element + * to start rendering the new columns on, this function + * checks to see if we should start on the current + * element or not. + * + * This function is called from within the template. + * + * @param string $section element to check + * + * @return boolean if the section is in the 2nd column or not + * @access protected + */ + public function inColumn2($section) + { + return ($this->formHeaders[$section]['col2']); + } + + // }}} + // {{{ insertData() + + /** + * Create a new record in the database from the data on the form + * + * When a member is first created, we don't have to worry about + * and module data ie.(golf, restaurant, accommodations), since + * they initially don't have any categories associated with them. + * + * Lat / Lon coordinates are not generated here, but they are + * injected into the form values if they are not filled in. This + * enables us to use google driving directions on all our members. + * + * Two groups of data are pulled from the values array of data. + * (categories & credit cards), these values are then unset in + * the values array, b/c we don't insert this data into the primary + * table. They each have their own table they get inserted into and + * are then associated to the newly inserted member. + * + * Empty field values are inserted as NULLS vs empty strings to allow + * for unique member_login names. + * + * A transaction is used to avoid orphaned data if any of the sql queries + * fail to properly insert the data. + * + * @param array $values Form values + * + * @return boolean False on error, True otherwise. + * @access public + */ + public function insertData($values) + { + // {{{ Golfing + + // Remove Golf Fields for Special Insert. + $fields = array( + 'par', + 'yardage', + 'course_rating', + 'slope_rating', + 'walking_course', + 'holes18', + 'holes9', + ); + + foreach ($fields as $v) { + $golfFields[$v] = $values[$v]; + unset($values[$v]); + } + + // }}} + // {{{ Accommodations + + // Remove Accommodation Fields for Special Insert. + $fields = array( + 'reservation_id', + 'num_rooms', + 'year_round', + ); + foreach ($fields as $v) { + $accommodationFields[$v] = $values[$v]; + unset($values[$v]); + } + + // }}} + // {{{ Restaurant + + // Remove Restaurant Fields for Special Insert. + $fields = array( + 'breakfast', + 'breakfast_from', + 'breakfast_to', + 'brunch', + 'brunch_from', + 'brunch_to', + 'lunch', + 'lunch_from', + 'lunch_to', + 'dinner', + 'dinner_from', + 'dinner_to', + 'alcohol', + 'non_smoking', + ); + foreach ($fields as $v) { + $restaurantFields[$v] = $values[$v]; + unset($values[$v]); + } + + // }}} + + $ccards = $values['creditCards']; + $pattern = '/^-?(.+)$/i'; + $replacement = '$1'; + // Adjust the lat/lon coordinates to negative #'s if needed + // The only way this will be needed is if the lat/lon boxes + // were filled in instead of letting this class determine + // them via street address or zip code. + $coords = array('lat' => 'South', 'lon' => 'East'); + foreach ($coords as $k => $v) { + if ($values["{$k}Direction"] == $v && !empty($values[$k])) { + $string = $values[$k]; + $values[$k] = preg_replace($pattern, $replacement, $string); + $values[$k] = "-{$values[$k]}"; + } + } + // If they dynamically add any categories, but then realize they + // want to remove them, they will show up in this array. + if (isset($values['removeCat'])) { + // So remove them before we get the categories to insert for the member. + $this->removeCategories($values['removeCat'], &$values['member_cats']); + } + // Now get the cats so we can insert them into a seperate table later. + $categories = $values['member_cats']; + + // Unneeded data that will not be stored in the member table + unset($values['lonDirection'], + $values['latDirection'], + $values['member_cats'], + $values['removeCat'], + $values['creditCards'] + ); + + try { + $params = implode(', ', array_keys($values)); + $bindParams = ':' . implode(', :', array_keys($values)); + $sql = " + INSERT INTO {$this->tableName} ($params) + VALUES ($bindParams) + RETURNING member_id"; + $this->dbh->beginTransaction(); + $stmt = $this->dbh->prepare($sql); + foreach ($values as $k => &$v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } elseif ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + // for empty values that are not actually a zero (0), we + // want to insert null's. + // This will help hold the unique values for member_logins, + // as empty values '', are not considered unique + if (empty($v) && $v !== 0) { + $v = null; + $dataType = PDO::PARAM_NULL; + } + $stmt->bindParam(":$k", $v, $dataType); + } + $stmt->execute(); + $stmt->bindColumn('member_id', $mid); + $stmt->fetch(); + + // Insert the categories into the DB and associate + // them w/ the newly inserted member. + if (!empty($categories)) { + $sql = " + INSERT INTO member_category(member_id, category_id) + VALUES(:member_id, :cid)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $mid, PDO::PARAM_INT); + foreach ($categories as $cid) { + // If the user didn't select a category, + // Then don't run an insert query. + if (!empty($cid)) { + $stmt->bindParam(':cid', $cid, PDO::PARAM_INT); + $stmt->execute(); + } + } + } + + // Insert the members credit cards into the DB and associate + // the w/ our new member. We get the ccard ID # by querying for + // it in the ccard_type table by the ccard name. + if (!empty($ccards)) { + $sql = " + INSERT INTO member_ccard_type(member_id, ccard_type_id) + SELECT :member_id, ccard_type_id + FROM ccard_type + WHERE ccard_type_name = :cctn"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $mid, PDO::PARAM_INT); + foreach ($ccards as $k => $v) { + $stmt->bindParam(':cctn', $k, PDO::PARAM_STR); + $stmt->execute(); + } + } + + $golf = $restaurant = $accommodations = false; + if (!empty($categories)) { + $sql = " + SELECT * + FROM category + WHERE category_id = :cid"; + $stmt = $this->dbh->prepare($sql); + foreach ($categories as &$cid) { + if (!empty($cid)) { + $stmt->bindParam(':cid', $cid, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + // If any of the module statuses are true, set them. + // otherwise leave them as they were, (we don't want + // to set a true back to a false). + $golf = ($row['golf'] == 't') ? true : $golf; + $accommodations = ($row['accommodations'] == 't') ? + true : $accommodations; + $restaurant = ($row['restaurant'] == 't') ? + true : $restaurant; + } + } + } + $this->clearModule('member_golf'); + if ($golf) { + $this->updateModuleFields($golfFields, 'member_golf', $mid); + } + $this->clearModule('member_accommodations'); + if ($accommodations) { + $this->updateModuleFields($accommodationFields, 'member_accommodations', $mid); + } + $this->clearModule('member_restaurants'); + if ($restaurant) { + $this->updateModuleFields($restaurantFields, 'member_restaurants', $mid); + } + $this->dbh->commit(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + header('Location: ' . BASE_URL . "admin/members.php?cat=2&subCat=2&tab=1&id=$mid"); + return true; + } + + // }}} + + // {{{ newColumn() + + /** + * Determines if we've reached the field that should start a new column + * + * This is used from the Flexy template. Each field name is passed into + * this function, when we reach the appropriate field, we will know that + * we need to start a new column. + * + * @param string $string The name of the field we're checking. + * + * @return boolean True on the right field, otherwise false. + * @access protected + */ + public function newColumn($string) + { + return ($string == 'Account Info'); + } + + // }}} + + // {{{ processData() + + /** + * Handles processing the submitted forms data. + * + * Sets up the table meta data so we can insert into the member table. + * removes any unwanted fields from the values array. these fields + * will be denoted by the '_rmv' at the end of thier name in the + * configureElements function + * + * + * ... 'name' => 'remove_rmv', ... + * + * + * This function also verifies that the lat/lon values were properly filled + * out, if they were left blank then the values will either be looked up + * via google maps or through our own zip DB. These values will then be + * inserted into the values array AND also injected into the form field + * values so they will display when the form comes back around. + * + * The form then decides if it is handeling a new member or not and calls + * the appropriate function to insert or update data. + * + * @param array $values The array of all submitted form values. + * + * @return boolean Whether the insert/update succeeded. + * @access public + */ + public function processData($values) + { + // Clean up some form elements before we try any processing + if (is_array($values['join_date'])) { + if (is_numeric($values['join_date']['m'])) { + $values['join_date'] = implode('-', $values['join_date']); + } else { + $values['join_date'] = null; + } + } + $this->processLogo(&$values); + Toolkit_Common::getTableMetaData(); + + foreach ($values as $k => $v) { + switch ($k) { + case 'MAX_FILE_SIZE' : + unset($values[$k]); + break; + + default : + if (preg_match('/^.+_rmv$/', $k)) { + unset($values[$k]); + } + break; + } + } + + //$this->verifyLatLon(&$values); + + $existingMember = (is_numeric($_GET['id'])); + if ($existingMember) { + return $this->updateData($values); + } else { + return $this->insertData($values); + } + } + + // }}} + + // {{{ processLogo() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access protected + */ + protected function processLogo($values) + { + // Keep a tidy house. + // There are 2 scenarios to deal w/ logos: + // 1. Removing logo: + // Delete the image from the image server + // and set the values['logo'] to null. + // 2. New logo: + // Check to see if old_logo_rmv holds a value, + // if it does then remove that logo + // Upload the image and put new filename + // into values['logo'] variable. + $imgServer = new Toolkit_Image_Server(); + + if ($values['remove_logo_rmv'] == 1) { + $imgServer->imageDelete($values['old_logo_rmv']); + $values['logo'] = null; + + if (get_class($this) == 'Toolkit_Members_EditMemberOnlyInfo') { + try { + // Make sure any logos that were pending are removed as well. + $sql = " + DELETE FROM {$this->pendingTable} + WHERE field = 'logo' + AND member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + $sql = " + UPDATE {$this->tableName} + SET logo = :logo + WHERE member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':logo', $values['logo'], PDO::PARAM_NULL); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + } + + // If a new logo is uploaded, have the image server + // process that logo and give us back the file name on + // the server. + if ($values['new_logo_rmv']['size'] > 0) { + $imgName = $imgServer->imageUpload('new_logo_rmv'); + $values['logo'] = $imgName; + $img = ''. $imgName . ''; + + // If the old_logo_rmv key is set and not empty + // then we are replacing an existing logo and did not + // check the remove logo checkbox. + // remove this old logo just for good house keeping. + if (isset($values['old_logo_rmv']) && !empty($values['old_logo_rmv'])) { + $imgServer->imageDelete($values['old_logo_rmv']); + // update the elements on the form if we are replacing an existing logo. + if ($this->elementExists('old_logo_rmv')) { + $e =& $this->getElement('old_logo_rmv'); + $e->setValue($imgName); + } + if ($this->elementExists('image_rmv')) { + $e =& $this->getElement('image_rmv'); + $e->setValue($img); + } + } else { + $source =& $this->createElement( + 'checkbox', + 'remove_logo_rmv', + 'Remove Logo' + ); + $this->insertElementBefore($source, 'new_logo_rmv'); + + $source =& $this->addElement('hidden', 'old_logo_rmv'); + $source->setValue($imgName); + + $source =& $this->createElement( + 'static', + 'image_rmv', + 'Current Logo' + ); + $source->setValue($img); + $element = $this->insertElementBefore($source, 'new_logo_rmv'); + + if (PEAR::isError($element)) { + die ('there was an error uploading your file!'); + } else { + // I don't know why, but the insertElementBefore + // function was erasing the value we set earlier. + // so just reset it to make double sure its there. + $element->setValue($img); + } + } + } + + // We clicked to remove the logo and did not upload a new one. + if ($values['remove_logo_rmv'] == 1 && $values['new_logo_rmv']['size'] == 0) { + if ($this->elementExists('remove_logo_rmv')) { + $this->removeElement('remove_logo_rmv', false); + } + if ($this->elementExists('image_rmv')) { + $this->removeElement('image_rmv', false); + } + if ($this->elementExists('old_logo_rmv')) { + $this->removeElement('old_logo_rmv', false); + } + } + } + + // }}} + + // {{{ removeCategories() + + /** + * Remove categories from the values['member_cats'] array + * + * Any values in the removeCats array are removed from the + * values['member_cats'] array which is passed in by reference + * so we don't have to return any values. + * + * @param array $targets All the category id's we want to remove + * @param array &$values All the categories submitte. + * + * @return void + * @access protected + */ + protected function removeCategories($targets, &$values) + { + foreach ($targets as $cid) { + $key = array_search($cid, $values); + unset($values[$key]); + } + } + + // }}} + + // {{{ setConfig() + + /** + * Sets the query to use to fetch the datagrid results + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function setConfig(Config_Container $c) + { + $this->config = $c; + } + + // }}} + // {{{ setStates() + + /** + * Set the states available for the form + * + * @param array $states Array of states available for the form + * + * @return void + * @access public + */ + public function setStates(array $states) + { + $this->states = $states; + } + + // }}} + // {{{ setupFormCategories() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function setupFormCategories() + { + try { + // Determine if this is a new member record or we're editing + // an existing member record. + $member_id = $_GET['id']; + // Get all the categories already associated w/ this member. + // This part is primarily for editing existing members. + // That way they categories initially show up. + // They are ordered by the mem_cat_id which should keep + // them in the same order as they were added. + $sql = " + SELECT * + FROM member_category + WHERE member_id = :id + ORDER BY member_category_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $member_id, PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $memCats[$row['category_id']] = true; + } + + // If we submitted the form: + // 1. Get all the member_cat values on the form that were submitted. + // If we flip the key/value pairs when we add the submitted values + // we won't have to worry about checking for duplicate cats submitted. + // 2. If we clicked on a remove button determine the x/y coords + // (hint: the coords will be empty if we didn't click on one). + // if the coords are not empty, then remove the category we clicked + // on, it will be the removeCat form element. + if ($this->isSubmitted()) { + if (!is_array($memCats)) { + $memCats = array(); + } + $submittedMemberCats = $this->getSubmitValue('member_cats'); + if (is_array($submittedMemberCats) && !empty($submittedMemberCats)) { + $memCats += array_flip($this->getSubmitValue('member_cats')); + } + // Holds a possible array of category id's we want to remove. + $removeTargets = $this->getSubmitValue('removeCat'); + // If the array is not empty, then scoot through it and remove + // any of the categories form the memCats array so they won't + // show up again. + if (!empty($removeTargets)) { + foreach ($removeTargets as $k => $v) { + unset($memCats[$v]); + } + } + } + + // Unset the blank key so the sql query doesn't puke when trying to + // add it into the DB. The blank key will occur if no cat is selected. + // its the default option for the select list. + unset($memCats['']); + $this->memberCategories = $memCats; + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setupRenderers() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $renderer =& new HTML_QuickForm_Renderer_Object(true); + + $this->accept($renderer); + + $this->template =& new HTML_Template_Flexy($this->flexyOptions); + + $m = new Toolkit_Members_RecordNavigation($this->config); + $m->setupAdminNavStructure(); + // Make the view a copy of the $this object + // That way we have access to call functions in + // this class from within the template. + $this->view = $this; + $this->view->baseUrl = BASE_URL; + $this->view->form = $renderer->toObject(); + $this->view->nav = $m->getPageNav(); + $this->template->compile($this->formTemplate); + } + + // }}} + // {{{ showCategories() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return string Return description (if any) ... + * @access public + */ + public function showCategories() + { + if (!empty($this->memberCategories)) { + try { + $sql = " + SELECT * + FROM category + WHERE category_id = :cid"; + $stmt = $this->dbh->prepare($sql); + foreach ($this->memberCategories as $cid => $v) { + $stmt->bindParam(':cid', $cid, PDO::PARAM_INT); + $stmt->execute(); + $category = $stmt->fetch(PDO::FETCH_ASSOC); + + $out .= ' + + + + '.$category['name'].' + '; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + return $out; + } + + // }}} + + // {{{ toHTML() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @return string The rendered form + * @access public + */ + public function toHTML() + { + // We need to validate (and freeze if needed) + // before we render the form. That way the + // template knows about any errors on the form. + $this->validated = $this->validate(); + if ($this->validated) { + $processed = $this->process(array(&$this, 'processData'), $this->mergeFiles); + } + + // ProcessData handles settingup the lat/lon coordinates if they were not entered + // into the form. these values ar calculated and then inserted into the forms + // element values. So we need to process the data first and then render the form. + $this->setupRenderers(); + + return $this->template->bufferedOutputObject($this->view); + } + + // }}} + + // {{{ updateData() + + /** + * Update the record data + * + * @param array $values scrubbed values submitted from the form + * + * @return object True on success + * @access public + */ + public function updateData($values) + { + /* + // Remove any cache we have for this member so the next + // page load of that member profile will generate new content. + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member-{$_GET['id']}", 'Dynamic'); + */ + + $member_id = $_GET['id']; + // {{{ Golfing + + // Remove Golf Fields for Special Insert. + $fields = array( + 'par', + 'yardage', + 'course_rating', + 'slope_rating', + 'walking_course', + 'holes18', + 'holes9', + ); + + foreach ($fields as $v) { + $golfFields[$v] = $values[$v]; + unset($values[$v]); + } + + // }}} + // {{{ Accommodations + + // Remove Accommodation Fields for Special Insert. + $fields = array( + 'reservation_id', + 'num_rooms', + 'year_round', + ); + foreach ($fields as $v) { + $accommodationFields[$v] = $values[$v]; + unset($values[$v]); + } + + // }}} + // {{{ Restaurant + + // Remove Restaurant Fields for Special Insert. + $fields = array( + 'breakfast', + 'breakfast_from', + 'breakfast_to', + 'brunch', + 'brunch_from', + 'brunch_to', + 'lunch', + 'lunch_from', + 'lunch_to', + 'dinner', + 'dinner_from', + 'dinner_to', + 'alcohol', + 'non_smoking', + ); + foreach ($fields as $v) { + $restaurantFields[$v] = $values[$v]; + unset($values[$v]); + } + + // }}} + + // Remove values not wanted before we get all the member categories. + if (isset($values['removeCat'])) { + // So remove them before we get the categories to insert for the member. + $this->removeCategories($values['removeCat'], &$values['member_cats']); + } + // Now get the cats so we can insert them into a seperate table later. + $categories = $values['member_cats']; + + $ccards = $values['creditCards']; + $pattern = '/^-?(.+)$/i'; + $replacement = '$1'; + // Adjust the lat/lon coordinates to negative #'s if needed + $coords = array('lat' => 'South', 'lon' => 'East'); + foreach ($coords as $k => $v) { + if ($values["{$k}Direction"] == $v && !empty($values[$k])) { + $string = $values[$k]; + $values[$k] = preg_replace($pattern, $replacement, $string); + $values[$k] = "-{$values[$k]}"; + } + } + unset($values['lonDirection'], + $values['latDirection'], + $values['member_cats'], + $values['removeCat'], + $values['creditCards'] + ); + + try { + $params = array_keys($values); + $length = count($params); + for ($i = 0; $i < $length; ++$i) { + $bindParams .= "{$params[$i]} = :{$params[$i]}"; + if ($i < ($length - 1)) { + $bindParams .= ', '; + } + } + $this->dbh->beginTransaction(); + $sql = " + UPDATE {$this->tableName} + SET $bindParams + WHERE member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT); + foreach ($values as $k => &$v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + // for empty values that are not actually a zero (0), we + // want to insert null's. + // This will help hold the unique values for member_logins, + // as empty values '', are not considered unique + if (empty($v) && $v !== 0) { + $v = null; + $dataType = PDO::PARAM_NULL; + } + $stmt->bindParam(":$k", $v, $dataType); + } + $stmt->execute(); + + // Handle updating the credit cards + $sql = " + DELETE FROM member_ccard_type + WHERE member_id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $member_id, PDO::PARAM_INT); + $stmt->execute(); + + if (is_array($ccards)) { + $sql = " + INSERT INTO member_ccard_type (member_id, ccard_type_id) + SELECT :id, ccard_type_id + FROM ccard_type + WHERE ccard_type_name = :cctn"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $member_id, PDO::PARAM_INT); + foreach ($ccards as $k => &$v) { + if ($v) { + $stmt->bindParam(':cctn', $k, PDO::PARAM_STR); + $stmt->execute(); + } + } + } + + // Handle updating the categories + $sql = " + DELETE FROM member_category + WHERE member_id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $member_id, PDO::PARAM_INT); + $stmt->execute(); + + if (is_array($categories)) { + $sql = " + INSERT INTO member_category (member_id, category_id) + VALUES (:member_id, :cid)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $member_id, PDO::PARAM_INT); + foreach ($categories as &$cid) { + if (!empty($cid)) { + $stmt->bindParam(':cid', $cid, PDO::PARAM_INT); + $stmt->execute(); + } + } + } + + $golf = $restaurant = $accommodations = false; + if (!empty($categories)) { + $sql = " + SELECT * + FROM category + WHERE category_id = :cid"; + $stmt = $this->dbh->prepare($sql); + foreach ($categories as &$cid) { + if (!empty($cid)) { + $stmt->bindParam(':cid', $cid, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + // If any of the module statuses are true, set them. + // otherwise leave them as they were, (we don't want + // to set a true back to a false). + $golf = ($row['golf'] == 't') ? true : $golf; + $accommodations = ($row['accommodations'] == 't') ? + true : $accommodations; + $restaurant = ($row['restaurant'] == 't') ? + true : $restaurant; + } + } + } + $this->clearModule('member_golf'); + if ($golf) { + $this->updateModuleFields($golfFields, 'member_golf'); + } + $this->clearModule('member_accommodations'); + if ($accommodations) { + $this->updateModuleFields($accommodationFields, 'member_accommodations'); + } + $this->clearModule('member_restaurants'); + if ($restaurant) { + $this->updateModuleFields($restaurantFields, 'member_restaurants'); + } + + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member_Profile-{$_GET['id']}", 'Dynamic'); + + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ updateModuleFields() + + // member_id in the params is for inserting the data if the form fails validation + // first and comes back around and module categories will be included on the form + // and you need to be able to insert the data and associate to the member. + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * @param unknown $tableName Parameter description (if any) ... + * @param unknown $member_id Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access protected + */ + protected function updateModuleFields($values, $tableName, $member_id = null) + { + Toolkit_Common::getTableMetaData(null, $tableName); + $values['member_id'] = (!is_null($member_id)) ? $member_id : $_GET['id']; + try { + $params = implode(', ', array_keys($values)); + $bindParams = ':' . implode(', :', array_keys($values)); + $sql = " + INSERT INTO $tableName ($params) + VALUES ($bindParams)"; + $stmt = $this->dbh->prepare($sql); + foreach ($values as $k => &$v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + // for empty values that are not actually a zero (0), we + // want to insert null's. + // This will help hold the unique values for member_logins, + // as empty values '', are not considered unique + if (empty($v) && $v !== 0) { + $v = null; + $dataType = PDO::PARAM_NULL; + } + $stmt->bindParam(":$k", $v, $dataType); + } + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ validated() + + /** + * Checks if the form is validated + * + * If the form is validated display the success msg. + * If the form is submitted but not validated, display + * the error msg. Other wise display nothing. + * + * This function is called from within the template. + * + * @return string The success or error msg for the user. + * @access protected + */ + public function validated() + { + if ($this->validated) { + return $this->successMsg; + } elseif ($this->isSubmitted()) { + return $this->errorMsg; + } + } + + // }}} + // {{{ verifyLatLon() + + /** + * Adjust lat / lon values on form if needed + * + * Checks to make sure the latitude and longitude values are present on the form. + * If either one is empty, it calculates the coordinates from the given data on the + * and inserts or updates the form element values. + * + * @param array $values lat/lon values + * + * @return string The rendered form + * @access protected + */ + protected function verifyLatLon($values) + { + if (empty($values['lat']) || empty($values['lon'])) { + if (!empty($values['street'])) { + $coords = $this->generateLatLon(&$values); + } else { + $coords = $this->generateLatLon($values['zip']); + } + } + + // Set each lat and lon value if its not empty. + // insert the value back into the forms GROUPED element. + if (!empty($coords['lat'])) { + $values['lat'] = $coords['lat']; + $e =& $this->getElement('lat'); + $e->setValue($coords['lat']); + } + if (!empty($coords['lon'])) { + $values['lon'] = $coords['lon']; + $e =& $this->getElement('lon'); + $e->setValue($coords['lon']); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/EditMemberOnlyAmenities.php b/Toolkit/Members/EditMemberOnlyAmenities.php new file mode 100644 index 0000000..77817b4 --- /dev/null +++ b/Toolkit/Members/EditMemberOnlyAmenities.php @@ -0,0 +1,451 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditMemberOnlyAmenities.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Short description for class + * + * Long description (if any) ... + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_EditMemberOnlyAmenities + extends Toolkit_Members_EditMemberAmenities implements Toolkit_Form +{ + // {{{ properties + + /** + * All the default data + * + * When we load the default data (member record from the database), we will + * store all that data in this variable. That way when we process the form + * we will have all the information to compare against, so we can find the + * updates. + * + * @var string + * @access protected + */ + protected $oldData; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + * @see Toolkit_Members_EditMemberInfo + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $pdo, + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->setPending(); + } + + // }}} + + // {{{ createPendingData() + + /** + * Make any changes into a pending state + * + * If strict pending is turned on, any changes that were made will + * have to fall into a pending state. to do that we need to drop + * any update into the updates table. + * + * @param array $values submitted form values + * + * @return boolean + * @access Protected + */ + protected function createPendingData($values) + { + try { + $this->handleReconsiderations(&$values); + // Find out all the amenities the member currently has. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $currentAmenities[] = $row['amenity_id']; + } + + // If they have no amenities already, we need to make sure + // this variable is at least defined as an array so + // we can get the array_diff. + if (empty($currentAmenities)) { + $currentAmenities = array(); + } + // Find out all the new amenities that where added. + $alteredAmenities + = array_diff(array_keys($values), $currentAmenities); + + $sql = " + SELECT * + FROM amenity + WHERE amenity_id = :aid"; + $fetchStmt = $this->dbh->prepare($sql); + $sql = " + INSERT INTO member_updates (update, data_type, member_id, field, + db_table, label) + VALUES (:update, 'string', :member_id, :field, :table, :label)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->bindParam(':table', $this->tableName, PDO::PARAM_STR); + // If any amenities where added + // insert them into the updates table to be in a pending state. + if (!empty($alteredAmenities)) { + $update = 1; + $stmt->bindParam(':update', $update, PDO::PARAM_STR); + foreach ($alteredAmenities as $k => &$v) { + $fetchStmt->bindParam(':aid', $v, PDO::PARAM_INT); + $fetchStmt->execute(); + $row = $fetchStmt->fetch(PDO::FETCH_ASSOC); + + $stmt->bindParam(':label', $row['amenity_name'], PDO::PARAM_STR); + $stmt->bindParam(':field', $v, PDO::PARAM_STR); + $stmt->execute(); + } + } + + $update = 0; + // If any amenities are removed + // insert the removal request into the updates table + // so it can be in a pending state. + foreach ($currentAmenities as $k => &$v) { + if (!array_key_exists($v, $values)) { + $fetchStmt->bindParam(':aid', $v, PDO::PARAM_INT); + $fetchStmt->execute(); + $row = $fetchStmt->fetch(PDO::FETCH_ASSOC); + + $stmt->bindParam(':update', $update, PDO::PARAM_STR); + $stmt->bindParam(':label', $row['amenity_name'], PDO::PARAM_STR); + $stmt->bindParam(':field', $v, PDO::PARAM_STR); + $stmt->execute(); + } + } + + return true; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureDefaults() + + /** + * Loads default values for the form + * + * Setup the members default values to load into the form. + * Copy all these values, which is the old data we will use to compare + * against when the form is submitted to determine the updates, into + * the oldData variable. + * + * @return void + * @access protected + */ + public function configureDefaults() + { + $this->oldData = parent::configureDefaults(); + + try { + $sql = " + SELECT field, 'update' + FROM member_updates + WHERE id in ( + SELECT max(id) + FROM member_updates + GROUP BY field) + AND member_id = :member_id + AND db_table = '{$this->tableName}'"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $this->oldData[$row['field']] = $row['update']; + } + $this->setupDefaults($this->oldData); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ fieldPending() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $elem Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function fieldPending($elem) + { + if (!is_array($this->pendingFields)) { + return false; + } else { + return in_array($elem->label, $this->pendingFields); + } + } + + // }}} + + // {{{ handleReconsiderations() + + /** + * Makes amenities not pending anymore if they get re-added or re-removed + * + * These two cases both reset the field to its previous state before + * the original request was made. So it bypasses the need of an admin + * to approve or reject the request, removes the fields from the updates + * table, and resets the field to its state before the request was made. + * + * If an amenity was added and removed before the admin has the ability + * to approve the request, we remove the field from the updates table + * and reset the pending field. Same happens if an amenity is removed + * and added back in before the admin approves the removal request. + * + * @param mixed $values array of values submitted from the form. + * + * @return void + * @access public + */ + protected function handleReconsiderations($values) + { + // Get all the latest updates for this member's amenities. + $sql = " + SELECT * + FROM member_updates + WHERE id IN ( + SELECT max(id) + FROM member_updates + WHERE member_id = :member_id + GROUP BY field) + AND db_table = '{$this->tableName}'"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $updates[$row['field']] = $row; + } + + // Set up the query to remove an amenity. + $sql = " + DELETE FROM member_updates + WHERE field = :field + AND db_table = '{$this->tableName}' + AND member_id = :member_id"; + $delStmt = $this->dbh->prepare($sql); + $delStmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + // This case can only happen if there are updates pending. + // If any amenities were re-added or re-removed, then remove + // them from the updates table cause they went back to their + // original state. + if (!empty($updates)) { + $updateableAmenities = array_keys($updates); + foreach ($updateableAmenities as $k => &$v) { + $keyExists = array_key_exists($v, $values); + $adding = (bool) $updates[$v]['update']; + // Removed then added back in. + $reAdded = (!$keyExists && $adding) ? true : false; + // Added then removed again. + $reRemoved = ($keyExists && !$adding) ? true : false; + + if ($reAdded || $reRemoved) { + $delStmt->bindParam(':field', $v, PDO::PARAM_INT); + $delStmt->execute(); + } + } + } + } + + // }}} + + // {{{ processData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return void + * @access public + */ + public function processData($values) + { + Toolkit_Common::getTableMetaData(); + + foreach ($values as $k => $v) { + switch ($k) { + default : + if (preg_match('/^.+_rmv$/', $k)) { + unset($values[$k]); + } + break; + } + } + + $this->dbh->beginTransaction(); + if ($this->updateData($values)) { + // insert into pending table + $this->dbh->commit(); + } else { + $this->dbh->rollBack(); + } + + $listPage = BASE_URL . + "memberdb/index.php?Option=Member&Action=Edit&tab=4"; + header("Location: $listPage"); + } + + // }}} + + // {{{ setPending() + + /** + * Determines if the member has made any update requests + * + * Any update requests that are in the member_updates table + * will let us know if this member is pending or not. + * + * @return void + * @access protected + * @see Toolkit_FormBuilder::setupElements() + */ + public function setPending() + { + unset ($this->pendingFields); + try { + $sql = " + SELECT DISTINCT label + FROM {$this->pendingTable} + WHERE member_id = :member_id + AND db_table = '{$this->tableName}'"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $this->pendingFields[] = $row['label']; + } + $this->pending = (count($this->pendingFields)) ? true : false; + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setupRenderers() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $renderer =& new HTML_QuickForm_Renderer_Object(true); + + $this->accept($renderer); + + $this->template =& new HTML_Template_Flexy($this->flexyOptions); + + $m = new Toolkit_Members_RecordNavigation($this->config); + $m->setupUserNavStructure(); + // Make the view a copy of the $this object + // That way we have access to call functions in + // this class from within the template. + $this->view = $this; + $this->view->form = $renderer->toObject(); + $this->view->nav = $m->getPageNav(); + $this->template->compile($this->formTemplate); + } + + // }}} + + // {{{ updateData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $values Parameter description (if any) ... + * + * @return unknown Return description (if any) ... + * @access public + */ + public function updateData($values) + { + $id = $GLOBALS['memberAuth']->getAuthData('member_id'); + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member_Profile-$id", 'Dynamic'); + + if ($this->strictPending) { + $this->emailOwner(); + return $this->createPendingData($values); + } else { + return parent::insertData($values); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/EditMemberOnlyContacts.php b/Toolkit/Members/EditMemberOnlyContacts.php new file mode 100644 index 0000000..f0df06b --- /dev/null +++ b/Toolkit/Members/EditMemberOnlyContacts.php @@ -0,0 +1,728 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditMemberOnlyContacts.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Handle associating contacts along with member records + * + * Controls all aspects of creating and rendering the form used to manipulate + * the business contacts. Form is not rendered until the user is added into the Database. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_EditMemberOnlyContacts + extends Toolkit_Members_EditMemberOnlyInfo implements Toolkit_Form +{ + // {{{ properties + + /** + * The table name in the database used to store the data of the files + * + * @var string + * @access public + */ + public $tableName = 'member_contacts'; + + /** + * The template used to render the form + * + * @var string + * @access protected + */ + protected $formTemplate = 'editContacts.tpl'; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $pdo, + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + } + + // }}} + + // {{{ configureDefaults() + + /** + * Sets the defaults for elements in the form. + * + * @return void + * @access public + */ + public function configureDefaults() + { + try { + if (isset($_GET['cid'])) { + $sql = " + select * from {$this->tableName} where id = :cid"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':cid', $_GET['cid'], PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $defaults['id'] = $row['id']; + $defaults['title'] = $row['title']; + $defaults['fname'] = $row['fname']; + $defaults['lname'] = $row['lname']; + $defaults['email'] = $row['email']; + $defaults['phone'] = $row['phone']; + $defaults['send_mail'] = $row['send_mail']; + } + $sql = " + SELECT *, fname || ' ' || lname AS name, + CASE send_mail + WHEN 'true' THEN 'Can Mail' + ELSE 'No Mail' + END AS send_mail + FROM {$this->tableName} + WHERE member_id = :id + ORDER BY id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + $i = 0; + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $defaults["cid$i"] = $row['id']; + $defaults["title$i"] = $row['title']; + $defaults["name$i"] = $row['name']; + $defaults["email$i"] = $row['email']; + $defaults["phone$i"] = $row['phone']; + $defaults["send_mail$i"] = $row['send_mail']; + ++$i; + } + $this->setupDefaults($defaults); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + $contacts = $this->getMemberContacts(); + // All Grouped Elements are created here. + $submitText = (is_numeric($_GET['cid'])) ? 'Update' : 'Submit'; + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'fileHdr', + 'display' => 'Contacts' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'id' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'title', + 'display' => 'Title', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'fname', + 'display' => 'First Name', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'lname', + 'display' => 'Last Name', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'email', + 'display' => 'Email', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Phone', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'send_mail', + 'display' => 'Receive Mail', + 'val' => array(0, + 1) + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit', + 'display' => $submitText, + 'opts' => array('class' => 'submit') + ); + if (is_array($contacts)) { + foreach ($contacts as $k => $v) { + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => "fileHdr$k" + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "cid$k" + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "name$k", + 'display' => 'Name' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "title$k" + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "email$k", + 'display' => 'Email' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "phone$k", + 'display' => 'Phone' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => "send_mail$k", + 'display' => 'Receive Mail' + ); + } + } + + $this->setupElements($e); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up all the rules to be used when the form is validated. + * + * @return void + * @access public + */ + public function configureRules() + { + // form rules + $r = array(); + $this->registeredRules = array('phone', 'email'); + $r[] = array( + 'element' => 'email', + 'message' => 'ERROR: Invalid Email Address!', + 'type' => 'email', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + /* + $r[] = array( + 'element' => 'phone', + 'message' => 'ERROR: Invalid Phone Number!', + 'type' => 'phone', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + */ + $this->setupRules($r); + } + + // }}} + + // {{{ getDelUrl() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $sec Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function getDelUrl($sec) + { + return $_SERVER['REQUEST_URI'] . "&d=t&cid={$sec->elements[0]->html}"; + } + + // }}} + // {{{ getEditUrl() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $sec Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function getEditUrl($sec) + { + return $_SERVER['REQUEST_URI'] . "&cid={$sec->elements[0]->html}"; + } + + // }}} + // {{{ getImgUrl() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $type Parameter description (if any) ... + * + * @return string Return description (if any) ... + * @access public + */ + public function getImgUrl($type) + { + return BASE_URL . "assets/$type"; + } + + // }}} + // {{{ getMailIcon() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $sec Parameter description (if any) ... + * + * @return string Return description (if any) ... + * @access public + */ + public function getMailIcon($sec) + { + $status = $sec->elements[5]->html; + $icon = ($status == 'No Mail') ? '-Not-Ok' : '-Ok'; + return 'mail'; + } + + // }}} + // {{{ getMemberContacts() + + /** + * Get all the contacts data uploaded to a member into an array + * + * @return array member contacts + * @access protected + */ + protected function getMemberContacts() + { + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE member_id = :id + ORDER BY id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $contacts[] = $row; + } + return $contacts; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access public + */ + public function insertData($values) + { + unset( + $values['id'], + $values['target'], + $values['submit'] + ); + $values['member_id'] = $_GET['id']; + try { + $params = implode(', ', array_keys($values)); + $bindParams = ':' . implode(', :', array_keys($values)); + $sql = " + INSERT INTO {$this->tableName} ($params) + VALUES ($bindParams)"; + $stmt = $this->dbh->prepare($sql); + foreach ($values as $k => $v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } elseif ($metaData == 'double precision') { + $dataType = null; + } else { + $dataType = PDO::PARAM_STR; + } + $stmt->bindParam(":$k", $values[$k], $dataType); + } + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ isEmail() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $name Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function isEmail($name) + { + return (substr($name, 0, 5) == 'email'); + } + + // }}} + // {{{ isForm() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $sec Parameter description (if any) ... + * + * @return unknown Return description (if any) ... + * @access public + */ + public function isForm($sec) + { + return !$sec; + } + + // }}} + // {{{ isName() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $name Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function isName($name) + { + return (substr($name, 0, 4) == 'name'); + } + + // }}} + // {{{ isPhone() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $name Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function isPhone($name) + { + return (substr($name, 0, 5) == 'phone'); + } + + // }}} + // {{{ isTitle() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $name Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function isTitle($name) + { + return (substr($name, 0, 5) == 'title'); + } + + // }}} + + // {{{ processData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return void + * @access public + */ + public function processData($values) + { + Toolkit_Common::getTableMetaData(); + if (empty($values['id'])) { + $this->insertData($values); + } else { + $this->updateData($values); + } + $listPage = BASE_URL . + "memberdb/index.php?Option=Member&Action=Edit&tab=6"; + header("Location: $listPage"); + } + + // }}} + + // {{{ removeContact() + + /** + * Remove a contact from a member record + * + * @param integer $cid contact id + * @param integer $mid member id + * + * @return void + * @access public + */ + public function removeContact($cid, $mid) + { + try { + $sql = " + DELETE FROM {$this->tableName} + WHERE id = :cid + AND member_id = :mid"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':cid', $cid, PDO::PARAM_INT); + $stmt->bindParam(':mid', $mid, PDO::PARAM_INT); + $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ setupRenderers() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $renderer =& new HTML_QuickForm_Renderer_Object(true); + + $this->accept($renderer); + + $this->template =& new HTML_Template_Flexy($this->flexyOptions); + + $m = new Toolkit_Members_RecordNavigation($this->config); + $m->setupUserNavStructure(); + // Make the view a copy of the $this object + // That way we have access to call functions in + // this class from within the template. + $this->view = $this; + $this->view->form = $renderer->toObject(); + $this->view->nav = $m->getPageNav(); + $this->template->compile($this->formTemplate); + } + + // }}} + // {{{ show() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + public function show() + { + if (isset($_GET['d'])) { + $this->removeContact($_GET['cid']); + $target = BASE_URL . + "memberdb/index.php?Option=Member&Action=Edit&tab=6"; + header("Location: $target"); + } + Toolkit_Common::show(); + } + + // }}} + + // {{{ updateData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access public + */ + public function updateData($values) + { + if (array_key_exists('delete', $values)) { + $this->deleteFile($values); + } + + unset( + $values['target'], + $values['submit'] + ); + + try { + $params = array_keys($values); + $length = count($params); + for ($i = 0; $i < $length; ++$i) { + $bindParams .= "{$params[$i]} = :{$params[$i]}"; + if ($i < ($length - 1)) { + $bindParams .= ', '; + } + } + $sql = " + UPDATE {$this->tableName} + SET $bindParams + WHERE id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $pid, PDO::PARAM_INT); + foreach ($values as $k => $v) { + $metaData = $this->tableMetaData[$k]; + if ($metaData == 'integer') { + $dataType = PDO::PARAM_INT; + } else if ($metaData == 'boolean') { + $dataType = PDO::PARAM_BOOL; + } else { + $dataType = PDO::PARAM_STR; + } + $stmt->bindParam(":$k", $values[$k], $dataType); + } + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/EditMemberOnlyFile.php b/Toolkit/Members/EditMemberOnlyFile.php new file mode 100644 index 0000000..8376510 --- /dev/null +++ b/Toolkit/Members/EditMemberOnlyFile.php @@ -0,0 +1,424 @@ + + * @author Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditMemberOnlyFile.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Controls for uploading / editing files for a business record + * + * Controls all aspects of creating and rendering the form used to manipulate + * the business files. Form is not rendered until the user is added into the + * Database. + * + * @category MembersDB + * @package Toolkit_Members + * @author Steve Sutton + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_Members_EditMemberInfo, Toolkit_Members_EditMemberFile + */ +class Toolkit_Members_EditMemberOnlyFile + extends Toolkit_Members_EditMemberFile implements Toolkit_Form +{ + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $pdo, + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->setPending(); + } + + // }}} + + // {{{ configureDefaults() + + /** + * Sets the defaults for elements in the form + * + * Handles setting the normal defaults by way of the parents function. + * Then overrides any caption updates by grabbing the latest update + * submitted for any caption in the updates table and sets those as + * the defaults instead. + * + * @return void + * @access public + */ + public function configureDefaults() + { + parent::configureDefaults(); + try { + // Get all the latest file name updates for the files + // EXCEPT any file that has an update of [0]. + // zero denotes a newly uploaded file and doesn't yet have + // a caption. + $sql = " + SELECT 'mu.update', mf.id + FROM {$this->pendingTable} mu, {$this->tableName} mf + WHERE mu.id in ( + SELECT max(id) + FROM {$this->pendingTable} + WHERE db_table = '{$this->tableName}' + AND member_id = :member_id + GROUP BY foreign_key) + AND mu.field = 'file_name' + AND mu.foreign_key = mf.id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $fields[] = $row; + } + + if (!empty($fields)) { + $sql = " + SELECT count(*) + FROM {$this->tableName} + WHERE id < :id + AND member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + foreach ($fields as &$f) { + $stmt->bindParam(':id', $f['id'], PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $defaults["file_name{$row['count']}"] = $f['update']; + } + $this->setupDefaults($defaults); + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertData() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function insertData($values) + { + if ($this->strictPending) { + try { + $this->dbh->beginTransaction(); + // Insert the file the normal way, w/ pending being true. + parent::insertData($values, $pending = true); + + // Get the last file inserted. + $sql = " + SELECT * + FROM {$this->tableName} + WHERE pending = true + AND member_id = :member_id + ORDER BY id DESC"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $file = $stmt->fetch(PDO::FETCH_ASSOC); + + // Insert the file into the updates table for approval. + $fname = empty($values['file_name']) ? + $values['file_rmv']['name'] : + $values['file_name']; + $imgTag = 'pdf Image'; + $label = ''; + $update = false; + $dataType = 'boolean'; + $field = 'pending'; + $sql = " + INSERT INTO {$this->pendingTable} + (member_id, field, update, db_table, data_type, label, foreign_key) + VALUES + (:member_id, :field, :update, :db_table, :data_type, :label, :foreign_key)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->bindParam(':field', $field, PDO::PARAM_STR); + $stmt->bindParam(':update', $update, PDO::PARAM_BOOL); + $stmt->bindParam(':db_table', $this->tableName, PDO::PARAM_STR); + $stmt->bindParam(':data_type', $dataType, PDO::PARAM_STR); + $stmt->bindParam(':label', $label, PDO::PARAM_STR); + $stmt->bindParam(':foreign_key', $file['id'], PDO::PARAM_STR); + $stmt->execute(); + $this->emailOwner(); + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollBack(); + return Toolkit_Common::handleError($e); + } + } else { + return parent::insertData($values); + } + } + + // }}} + + // {{{ pendingClass() + + /** + * Returns a pending class for the file if it is in a pending state + * + * The offset passed in is controlled from the loop in the template + * that creates each file form. + * + * @param integer $offset which file we're dealing with + * + * @return mixed + * @access Protected + * @see Toolkit_Members_EditMemberFile::getMemberFiles() + */ + public function pendingClass($offset) + { + $files = $this->getMemberFiles(); + + // If the offset is empty (0) then we know we're dealing + // with the upload box. + if (empty($offset)) { + return; + } else { + // Otherwise we need to see if this file is pending or not. + try { + // Get all the files that are pending in the updates table. + $sql = " + SELECT DISTINCT foreign_key AS fid + FROM {$this->pendingTable} + WHERE db_table = '{$this->tableName}' + AND member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $pendingFiles[] = $row['fid']; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + + --$offset; + + // If our current file is in the pending table + // return the pending class. + if (in_array($files[$offset]['id'], $pendingFiles)) { + return 'pending'; + } + } + } + + // }}} + // {{{ processData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $values Parameter description (if any) ... + * + * @return void + * @access public + */ + public function processData($values) + { + $id = $GLOBALS['memberAuth']->getAuthData('member_id'); + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member_Profile-$id", 'Dynamic'); + + parent::processData($values); + $listPage = BASE_URL . + "memberdb/index.php?Option=Member&Action=Edit&tab=5"; + header("Location: $listPage"); + } + + // }}} + + // {{{ setPending() + + /** + * Determines if the member has made any update requests + * + * Any update requests that are in the member_updates table + * will let us know if this member is pending or not. + * + * @return boolean + * @access protected + */ + public function setPending() + { + unset ($this->pendingFields); + try { + $sql = " + SELECT DISTINCT foreign_key AS fid + FROM {$this->pendingTable} + WHERE member_id = :member_id + AND db_table = '{$this->tableName}'"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $this->pendingFields[] = $row['fid']; + } + $this->pending = (count($this->pendingFields)) ? true : false; + return true; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setupRenderers() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $renderer =& new HTML_QuickForm_Renderer_Object(true); + + $this->accept($renderer); + + $this->template =& new HTML_Template_Flexy($this->flexyOptions); + + $m = new Toolkit_Members_RecordNavigation($this->config); + $m->setupUserNavStructure(); + // Make the view a copy of the $this object + // That way we have access to call functions in + // this class from within the template. + $this->view = $this; + $this->view->form = $renderer->toObject(); + $this->view->nav = $m->getPageNav(); + $this->template->compile($this->formTemplate); + } + + // }}} + + // {{{ updateData() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $values Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + public function updateData($values) + { + if ($this->strictPending) { + if (array_key_exists('delete', $values)) { + return $this->deleteFile($values); + } + try { + $fid = $values["file{$values['target']}"]; + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $fid, PDO::PARAM_INT); + $stmt->execute(); + $file = $stmt->fetch(PDO::FETCH_ASSOC); + + $fname = empty($file['file_name']) ? + $file['original_name'] : + $file['file_name']; + $imgTag = 'pdf Image'; + $label = '' . + $imgTag . $fname . ''; + + $dataType = 'text'; + $label = '
    ' . + $label . 'File Name
    '; + $field = 'file_name'; + $sql = " + INSERT INTO {$this->pendingTable} + (member_id, field, update, db_table, data_type, label, foreign_key) + VALUES + (:member_id, :field, :update, :db_table, :data_type, :label, :foreign_key)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->bindParam(':field', $field, PDO::PARAM_INT); + $stmt->bindParam(':update', $values["file_name{$values['target']}"], PDO::PARAM_STR); + $stmt->bindParam(':db_table', $this->tableName, PDO::PARAM_INT); + $stmt->bindParam(':data_type', $dataType, PDO::PARAM_INT); + $stmt->bindParam(':label', $label, PDO::PARAM_INT); + $stmt->bindParam(':foreign_key', $fid, PDO::PARAM_INT); + $this->emailOwner(); + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } else { + return parent::updateData($values); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/EditMemberOnlyInfo.php b/Toolkit/Members/EditMemberOnlyInfo.php new file mode 100644 index 0000000..171ee73 --- /dev/null +++ b/Toolkit/Members/EditMemberOnlyInfo.php @@ -0,0 +1,1194 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditMemberOnlyInfo.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Edit member info stored in the database + * + * Controls all aspects of creating and rendering the form used to manipulate + * the member data. Handles adding / editing module details, including: + * 1. Restaurants + * 2. Accommodations + * 3. Golfing + * + * Controls the addition of categories to a member record. Categories have + * dynamic settings which allow users to dynamically set which categories are + * associated to which modules (golf, accommodations, restaurant, etc...). + * Depending on which category is selected and assigned to a member record + * controls which modules are displayed on the form. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_Members, member_admin + */ +class Toolkit_Members_EditMemberOnlyInfo + extends Toolkit_Members_EditMemberInfo implements Toolkit_Form +{ + // {{{ properties + + /** + * Set all the tables in the DB that hold the module info + * + * @var string + * @access protected + */ + protected $moduleTables = array( + 'member_golf' => array(), + 'member_restaurants' => array(), + 'member_accommodations' => array(), + ); + + /** + * All the default data + * + * When we load the default data (member record from the database), we will + * store all that data in this variable. That way when we process the form + * we will have all the information to compare against, so we can find the + * updates. + * + * @var string + * @access protected + */ + protected $oldData; + + // }}} + + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + * @see Toolkit_Members_EditMemberInfo + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $pdo, + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->setPending(); + // Unset this so it won't get displayed. + $this->successMsg = null; + } + + // }}} + + // {{{ configureDefaults() + + /** + * Loads default values for the form + * + * Setup the members default values to load into the form. + * Copy all these values, which is the old data we will use to compare + * against when the form is submitted to determine the updates, into + * the oldData variable. + * + * @return array default values + * @access protected + */ + public function configureDefaults() + { + $this->oldData = parent::configureDefaults(); + + try { + $sql = " + SELECT field, 'update' + FROM {$this->pendingTable} + WHERE id in ( + SELECT max(id) + FROM {$this->pendingTable} + WHERE member_id = :member_id + AND (db_table = 'member' OR + db_table = 'member_ccard_type' OR + db_table = 'member_accommodations' OR + db_table = 'member_restaurants' OR + db_table = 'member_golf') + GROUP BY field)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + if ($row['field'] == 'logo') { + $this->oldData['old_logo_rmv'] = $row['update']; + $row['update'] = ''.$row['update'].''; + $row['field'] = 'image_rmv'; + } + $this->oldData[$row['field']] = $row['update']; + } + return $this->setupDefaults($this->oldData); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * Categories are populated into the protected class property $categories. + * These categories are used to populate the select list of categories. + * Modules are configured before any elements are setup, that way we will + * know if we need to include them in the rendering of the form. + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + + // get reference to [listing type] section of config file + $config =& $this->config->getItem('section', 'listing type'); + // get coupon + $singularDirective =& $config->getItem('directive', 'singular'); + $singularType = $singularDirective->getContent(); + $pluralDirective =& $config->getItem('directive', 'plural'); + $pluralType = $pluralDirective->getContent(); + + // get reference to [conf] section of config file + $config =& $this->config->getItem('section', 'conf'); + // get controlled cities + $ctrlCtyDirective =& $config->getItem('directive', 'controlledCities'); + + $this->setupFormCategories(); + $this->configureModules(); + + $this->getCategories(); + $states = Toolkit_Common::getStates($this->dbh); + + // All Grouped Elements are created here. + // All Elements are created here. This includes group element definitions. + + // {{{ Member Information + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'memberInfoHdr', + 'display' => "$singularType Information", + 'col1' => true + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'primary_contact_fname', + 'display' => 'Primary Contact First Name', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'primary_contact_lname', + 'display' => 'Primary Contact Last Name', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'process_email', + 'display' => 'Primary Contact Email', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'member_cats[]', + 'display' => "$singular Category", + 'opts' => $this->categories, + 'att' => array('id' => 'categories') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'phone', + 'display' => 'Primary Phone', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'toll_free', + 'display' => 'Toll Free Phone', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'fax', + 'display' => 'Fax Number', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'member_contact_email', + 'display' => 'Email on Website', + 'opts' => array('class' => 'text') + ); + /* + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'country', + 'display' => 'Country', + 'opts' => array( + '' => '-- Select Country --', + 'USA' => 'USA', + 'Canada' => 'Canada' + ) + ); + */ + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'url', + 'display' => 'Website Address', + 'opts' => array('class' => 'text') + ); + + // }}} + // {{{ Physical Address + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'physicalAddressHdr', + 'display' => 'Street Address', + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'street', + 'display' => 'Street Address', + 'opts' => array('class' => 'text') + ); + if ($ctrlCtyDirective->getContent()) { + $e[] = array( + 'type' => 'select', + 'req' => true, + 'name' => 'city_id', + 'display' => 'City', + 'opts' => $this->getCities(), + ); + } else { + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'city', + 'display' => 'City', + 'opts' => array('class' => 'text') + ); + } + $e[] = array( + 'type' => 'select', + 'req' => true, + 'name' => 'state_id', + 'display' => 'State / Province', + 'opts' => array('' => '-- Select --') + $states + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'zip', + 'display' => 'Zip / Postal Code', + 'opts' => array('class' => 'text') + ); + + // }}} + // {{{ Mailing Address + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'MailingAddressHdrRmv', + 'display' => 'Mailing Address (if different than physical address)', + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'mailing_address', + 'display' => 'Mailing Address', + 'opts' => array('class' => 'text') + ); + if ($ctrlCtyDirective->getContent()) { + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'mailing_city_id', + 'display' => 'City', + 'opts' => $this->getCities(), + ); + } else { + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'mailing_city', + 'display' => 'City', + 'opts' => array('class' => 'text') + ); + } + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'mailing_state_id', + 'display' => 'State / Province', + 'opts' => array('' => '-- Select --') + $states + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'mailing_zip', + 'display' => 'Zip / Postal Code', + 'opts' => array('class' => 'text') + ); + + // }}} + // {{{ Member Description + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'memberDescHdr', + 'display' => "$singularType Description", + 'col1' => true + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'display' => 'Description', + 'opts' => array( + 'id' => 'description', + 'rows' => 8, + 'cols' => 43 + ) + ); + + // }}} + // {{{ Account Info + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'accountInfoHdr', + 'display' => 'Account Info', + 'col2' => true + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'member_login', + 'display' => 'Username', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'member_passwd', + 'display' => 'Password', + 'opts' => array('class' => 'text') + ); + + // }}} + // {{{ Member Logo + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'logoHdr', + 'display' => "$singularType Logo", + 'col2' => true + ); + if ($this->hasLogo()) { + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'remove_logo_rmv', + 'display' => 'Remove Logo' + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'image_rmv', + 'display' => 'Current Logo' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'old_logo_rmv' + ); + } + + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'new_logo_rmv', + 'display' => 'New Logo', + 'opts' => array('class' => 'file') + ); + + // }}} + // {{{ Payment Type Accepted + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'CreditCardsHdr', + 'display' => 'Payment Type Accepted', + 'col2' => true + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'creditCards[American Express]', + 'display' => 'American Express', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'creditCards[Discover]', + 'display' => 'Discover', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'creditCards[Master Card]', + 'display' => 'Master Card', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'creditCards[Visa]', + 'display' => 'Visa', + 'val' => array(0, 1) + ); + + // }}} + // {{{ Accommodations Information + + if ($this->accommodations) { + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'AccommodationsHdr', + 'display' => 'Accommodations Information', + 'col2' => true + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'reservation_id', + 'display' => 'Reservation Id', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'num_rooms', + 'display' => 'Number of Rooms', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'year_round', + 'display' => 'Open all Year', + 'val' => array(0, 1) + ); + } + + // }}} + // {{{ Restaurant Information + + if ($this->restaurant) { + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'RestaurantHdr', + 'display' => 'Restaurant Information', + 'col2' => true + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'breakfast', + 'display' => 'Breakfast', + 'att' => array('id' => 'breakfast'), + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'breakfast_from', + 'display' => 'From', + 'opts' => array('class' => 'priceFrom') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'breakfast_to', + 'display' => 'To', + 'opts' => array('class' => 'priceTo') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'brunch', + 'display' => 'Brunch', + 'att' => array('id' => 'brunch'), + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'brunch_from', + 'display' => 'From', + 'opts' => array('class' => 'priceFrom') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'brunch_to', + 'display' => 'To', + 'opts' => array('class' => 'priceTo') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'lunch', + 'display' => 'Lunch', + 'att' => array('id' => 'lunch'), + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'lunch_from', + 'display' => 'From', + 'opts' => array('class' => 'priceFrom') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'lunch_to', + 'display' => 'To', + 'opts' => array('class' => 'priceTo') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'dinner', + 'display' => 'Dinner', + 'att' => array('id' => 'dinner'), + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'dinner_from', + 'display' => 'From', + 'opts' => array('class' => 'priceFrom') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'dinner_to', + 'display' => 'To', + 'opts' => array('class' => 'priceTo') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'alcohol', + 'display' => 'Alcohol', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'non_smoking', + 'display' => 'Non-Smoking', + 'val' => array(0, 1) + ); + } + + // }}} + // {{{ Golf Information + + if ($this->golf) { + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'GolfingHdr', + 'display' => 'Golf Course Information', + 'col2' => true + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'par', + 'display' => 'Par', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'yardage', + 'display' => 'Yardage', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'course_rating', + 'display' => 'Course Rating', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'slope_rating', + 'display' => 'Slope Rating', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'walking_course', + 'display' => 'Walking Course', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'holes18', + 'display' => '18 Holes', + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'holes9', + 'display' => '9 Holes', + 'opts' => array('class' => 'text') + ); + } + + // }}} + // {{{ Social Media Links + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'SocialMediaHdr', + 'display' => 'Social Media Links', + 'col2' => true, + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'facebook', + 'display' => 'Facebook', + 'col2' => true, + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'twitter', + 'display' => 'Twitter', + 'col2' => true, + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'myspace', + 'display' => 'MySpace', + 'col2' => true, + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'linkedin', + 'display' => 'LinkedIn', + 'col2' => true, + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'blog', + 'display' => 'Blog', + 'col2' => true, + ); + + // }}} + + $this->setupElements($e); + } + + // }}} + + // {{{ processData() + + /** + * Handles processing the submitted forms data + * + * See parent function for better description. + * + * @param array $values The array of all submitted form values. + * + * @return boolean Whether the insert/update succeeded. + * @access public + * @see Toolkit_Members_EditMemberInfo::processData() + */ + public function processData($values) + { + $id = $GLOBALS['memberAuth']->getAuthData('member_id'); + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member_Profile-$id", 'Dynamic'); + + $return = parent::processData(&$values); + $this->setPending(); + return $return; + } + + // }}} + + // {{{ setPending() + + /** + * Determines if the member has made any update requests + * + * Any update requests that are in the member_updates table + * will let us know if this member is pending or not. + * + * @return void + * @access public + */ + public function setPending() + { + unset ($this->pendingFields); + try { + $sql = " + SELECT DISTINCT + CASE field + WHEN 'lat' THEN 'latitude' + WHEN 'lon' THEN 'longitude' + WHEN 'logo' THEN 'image_rmv' + ELSE field + END AS field + FROM {$this->pendingTable} + WHERE member_id = :member_id + AND (db_table = '{$this->tableName}' + OR db_table = 'member_ccard_type' + OR db_table = 'member_restaurants' + OR db_table = 'member_accommodations' + OR db_table = 'member_golf')"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $this->pendingFields[] = $row['field']; + } + $this->pending = (count($this->pendingFields)); + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setupRenderers() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $renderer =& new HTML_QuickForm_Renderer_Object(true); + + $this->accept($renderer); + + $this->template =& new HTML_Template_Flexy($this->flexyOptions); + + $m = new Toolkit_Members_RecordNavigation($this->config); + $m->setupUserNavStructure(); + // Make the view a copy of the $this object + // That way we have access to call functions in + // this class from within the template. + $this->view = $this; + $this->view->form = $renderer->toObject(); + $this->view->nav = $m->getPageNav(); + $this->template->compile($this->formTemplate); + } + + // }}} + // {{{ showCategories() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return string Return description (if any) ... + * @access public + */ + public function showCategories() + { + if (!empty($this->memberCategories)) { + try { + $sql = " + SELECT * + FROM category + WHERE category_id = :cid"; + $stmt = $this->dbh->prepare($sql); + foreach ($this->memberCategories as $cid => $v) { + $stmt->bindParam(':cid', $cid, PDO::PARAM_INT); + $stmt->execute(); + $category = $stmt->fetch(PDO::FETCH_ASSOC); + + $out .= ' + + '; + if (defined('MEMBERS_ONLY_AREA_ON') && MEMBERS_ONLY_AREA_ON == true) { + } else { + $out .= ' + '; + } + $out .= "{$category['name']}"; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + return $out; + } + + // }}} + + // {{{ updateData() + + /** + * Insert the values that were updated from the member only form + * + * 1. Get all the field types in the DB for the module tables + * 2. Check the module fields against the old Data (the original values + * we obtained when we got the defaults for the form). If the + * value is not the same, then add the value to the column field of + * the table in the moduleUpdates array. + * 3. Get the updates for the member record. + * 4. Insert all the updates into the member_updates table. + * + * @param array $values submitted form values + * + * @return mixed + * @access public + */ + public function updateData($values) + { + if ($this->strictPending) { + foreach ($this->moduleTables as $tname => &$arr) { + Toolkit_Common::getTableMetaData(null, $tname); + if (is_array($this->tableMetaData)) { + foreach ($this->tableMetaData as $k => $v) { + switch ($k) { + case 'id' : + case 'member_id' : + break; + + default : + $arr[$k]['data_type'] = $v; + $arr[$k]['value'] = $values[$k]; + unset($values[$k]); + break; + } + } + } + } + // Check for updates in the module tables. + foreach ($this->moduleTables as $tname => &$arr) { + foreach ($arr as $k => $v) { + if (array_key_exists($k, $this->oldData)) { + if ($v['data_type'] != 'boolean') { + if ($v['value'] != $this->oldData[$k]) { + $moduleUpdates[$tname][$k] = $v; + } + } else { + // Due to how PDO's cast a boolean value False + // to '' when you query the DB. + // we need to adjust any empty fields + // that are of data_type boolean to a 0, True + // values are queried as 1. + // See: http://bugs.php.net/bug.php?id=33876 + // for more info. + $oldData = (empty($this->oldData[$k])) ? 0 : 1; + if ($v['value'] != $oldData) { + $moduleUpdates[$tname][$k] = $v; + } + } + // If the field was set in the module Updates array + // then also try and set what type of field we are + // dealing w/ on the form. + if (isset($moduleUpdates[$tname][$k])) { + if ($this->elementExists($k)) { + $e =& $this->getElement($k); + if (PEAR::isError($e)) { + return Toolkit_Common::handleError($e); + } + $moduleUpdates[$tname][$k]['field_type'] = $e->getType(); + } + } + } + } + } + + // Need a special case for the credit cards. + if (is_array($values['creditCards'])) { + foreach ($values['creditCards'] as $k => $v) { + if (array_key_exists("creditCards[$k]", $this->oldData)) { + if ($v != $this->oldData["creditCards[$k]"]) { + $ccUpdates["creditCards[$k]"]['data_type'] = 'integer'; + $ccUpdates["creditCards[$k]"]['value'] = $v; + } + } elseif (!empty($v)) { + $ccUpdates["creditCards[$k]"]['data_type'] = 'integer'; + $ccUpdates["creditCards[$k]"]['value'] = $v; + } + // If the credit card was set in the credit card updates array + // then also try and set what type of field we are dealing w/ + // on the form. + if (isset($ccUpdates["creditCards[$k]"])) { + if ($this->elementExists("creditCards[$k]")) { + $e =& $this->getElement("creditCards[$k]"); + if (PEAR::isError($e)) { + return Toolkit_Common::handleError($e); + } + $ccUpdates["creditCards[$k]"]['field_type'] = $e->getType(); + } + } + } + } + } else { + return parent::updateData($values); + } + + $ccards = $values['creditCards']; + $pattern = '/^-?(.+)$/i'; + $replacement = '$1'; + // Adjust the lat/lon coordinates to negative #'s if needed + $coords = array('lat' => 'South', 'lon' => 'East'); + foreach ($coords as $k => $v) { + if ($values["{$k}Direction"] == $v && !empty($values[$k])) { + $string = $values[$k]; + $values[$k] = preg_replace($pattern, $replacement, $string); + $values[$k] = "-{$values[$k]}"; + } + } + unset($values['lonDirection'], + $values['latDirection'], + $values['member_cats'], + $values['creditCards'] + ); + + Toolkit_Common::getTableMetaData(); + // Check for updates in the member record. + // If we find any, add that field to the list of record updates + // along with what type of field it is in the member table. + // We will use the data_type field when the admin is dealing + // w/ the updates to determine values on boolean records and empty + // text field records. + foreach ($values as $k => $v) { + if (array_key_exists($k, $this->oldData)) { + if ($v != $this->oldData[$k]) { + if ($this->elementExists($k)) { + $e =& $this->getElement($k); + if (PEAR::isError($e)) { + return Toolkit_Common::handleError($e); + } + $recordUpdates[$k]['field_type'] = $e->getType(); + } + $recordUpdates[$k]['data_type'] = $this->tableMetaData[$k]; + $recordUpdates[$k]['value'] = $v; + } + } + // We need a special case for the member image. cause Its a pain + // in the ass. + if ($k == 'logo') { + if (!empty($v)) { + if (array_key_exists('old_logo_rmv', $this->oldData)) { + if ($v != $this->oldData['old_logo_rmv']) { + $recordUpdates[$k]['data_type'] = 'boolean'; + $recordUpdates[$k]['field_type'] = 'file'; + $recordUpdates[$k]['value'] = $v; + } + } + } + } + } + + // Combine the update arrays for the modules and the member record + // into one single array. The array will hold this pattern. + // An array of tables that holds an array of fields that were updated + // [DB Table] => array + // ( + // [Column Name] => array + // ( + // [data_type] => boolean / text / integer + // [field_type] => text / select / checkbox + // [value] => updated value from the form. + // ) + // ) + // Make sure to only add these array's if there is update information + // in them. + $updates = array(); + if (is_array($moduleUpdates)) { + $updates += $moduleUpdates; + } + if (is_array($recordUpdates)) { + $updates += array('member' => $recordUpdates); + } + if (is_array($ccUpdates)) { + $updates += array('member_ccard_type' => $ccUpdates); + } + + try { + // If we have an array of updates, we need to insert all the + // updates into the member_updates table. This will signal that + // the member has pending updates that the admin needs to + // authorize. + if (!empty($updates)) { + // Loop through all the elements that were updated and get + // the label we use on the form so when the admin is looking + // at the updates they will know what field its for. + // We can be sure we are getting the right label because + // there can only be unique element names in the form. + foreach ($updates as &$sec) { + foreach ($sec as $field => $v) { + switch ($field) { + case 'lat' : + $g =& $this->getElement('latitude'); + $e =& $g->getElements(); + $sec[$field]['label'] = $e[1]->getLabel(); + break; + + case 'lon' : + $g =& $this->getElement('longitude'); + $e =& $g->getElements(); + $sec[$field]['label'] = $e[1]->getLabel(); + break; + + case '' : + case null : + break; + + default : + $e =& $this->getElement($field); + // Check to make sure an actual element was + // returned. If a "module" is unassigned from a + // category, those elements will not be created. + // so we won't be able to get the labels for those + // elements. In this case, just use the field + // name. + if (PEAR::isError($e)) { + $sec [$field]['label'] = $field; + } else { + $sec[$field]['label'] = $e->getLabel(); + } + break; + } + } + } + $this->dbh->beginTransaction(); + + $sql = " + INSERT INTO {$this->pendingTable} (member_id, field, update, db_table, data_type, field_type, label) + VALUES (:member_id, :field, :update, :table, :data_type, :field_type, :label)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $GLOBALS['memberAuth']->getAuthData('member_id'), PDO::PARAM_INT); + foreach ($updates as $table => &$sec) { + $stmt->bindParam(':table', $table, PDO::PARAM_STR); + foreach ($sec as $k => &$v) { + $dataType = PDO::PARAM_STR; + // Fields that are empty which have a data_type of text + // can be inserted as NULL values. + if (empty($v['value']) && $v['data_type'] == 'text') { + $v['value'] = null; + $dataType = PDO::PARAM_NULL; + } + $stmt->bindParam(":field", $k, PDO::PARAM_STR); + $stmt->bindParam(":update", $v['value'], $dataType); + $stmt->bindParam(":data_type", $v['data_type'], PDO::PARAM_STR); + $stmt->bindParam(":field_type", $v['field_type'], PDO::PARAM_STR); + $stmt->bindParam(":label", $v['label'], PDO::PARAM_STR); + $stmt->execute(); + } + } + $this->setPending(); + $this->emailOwner(); + return $this->dbh->commit(); + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + + return; + } + + // }}} +} +?> diff --git a/Toolkit/Members/EditPackages.php b/Toolkit/Members/EditPackages.php new file mode 100644 index 0000000..351aadc --- /dev/null +++ b/Toolkit/Members/EditPackages.php @@ -0,0 +1,1506 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditPackages.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see Toolkit/Image/Server.php + */ + + +/** + * The image server processing class + */ +require_once BASE . 'Toolkit/Image/Server.php'; + +/** + * Constructor class to setup the page layout + * + * this class determines if the user can upload any more packages to their + * account and if so renders the add package form. It also controls + * rending the individual forms for each previously uploaded package. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_EditPackages extends Toolkit_Members_Admin_EditPackages +{ + // {{{ properties + + /** + * The table name in the database used to store the data + * @var string + * @access public + */ + public $tableName = 'member_packages'; + + /** + * Template used to layout form when editing a package + * @var string + * @access protected + */ + protected $pageTemplate = 'editPackages.tpl'; + + /** + * Sets the max number of packages allowed for each listing + * @var integer + * @access protected + */ + protected $maxPackages = 2; + + /** + * What is the maximum caption length for packages + * + * @var array + * @access public + * @static + */ + static public $maxTitleLength = 60; + + /** + * Objects that will go into the page (add form, edit package forms) + * @var object + * @access protected + */ + protected $page; + + /** + * Description for protected + * @var unknown + * @access protected + */ + protected $dbh; + + // }}} + + // {{{ canAddPackages() + + /** + * Determine if this member can have more packages added to their profile + * + * Load the entire package gallery into member via a linked list. + * Then return if the # of linked list nodes is smaller than + * the maximum limit of packages. + * + * @access protected + * @return boolean If the linked list is smaller than max packages allowed + */ + protected function canAddPackages() + { + $id = $GLOBALS['memberAuth']->getAuthData('member_id'); + $ll = new Toolkit_Members_Packages(null, $id); + $ll->setDbh($this->dbh); + $ll->createMemberList(); + return ($ll->getListSize() < $this->maxPackages); + } + + // }}} + + // {{{ displayPage() + + /** + * Displays the page to the screen + * + * @return void + * @access public + */ + public function displayPage() + { + echo $this->getPage(); + } + + // }}} + + // {{{ getUploadedPackages() + + /** + * Get an array of package ids from the DB that have been uploaded for this member + * + * - Create a linked list of all the members packages + * - Walk through the linked list extracting the id from each node into an array + * + * @access protected + * @return array Ids of all uploaded packages for this member + */ + protected function getUploadedPackages() + { + $id = $GLOBALS['memberAuth']->getAuthData('member_id'); + $packages = new Toolkit_Members_Packages(null, $id); + $packages->setDbh($this->dbh); + $packages->createMemberList(); + $packages->rewind(); + + $ids = array(); + foreach ($packages as $i) { + // Don't show the pending packages here. + if (!$i->getPending()) { + $ids[] = $i->getId(); + } + } + + return $ids; + } + + // }}} + + // {{{ setUpPage() + + /** + * Sets up the page to manipulate packages for a member + * + * Checks if all the packages uploaded for a member (pending & non-pending) + * exceed or match the maximum # of packages allowed for each member to + * upload to their account. + * + * For every package that is already uploaded, create an edit-package form that + * will allow the user to update the caption or delete the package. + * + * @return void + * @access public + */ + public function setUpPage() + { + $this->page = new StdClass; + + // Find out if we can still add packages to the record. + // If we can, then add the upload form to the page for the member to see. + if ($this->canAddPackages()) { + $addForm = new AddPackage($this->dbh, + 'new_member_package', + 'post', + '', + '', + null, + true); + + $addForm->configureForm(); + $this->page->uploadForm = $addForm->toHtml($this->tEngine); + } + + // Find out if we have any packages already uploaded. + // If we do, then add the edit package form to the page for each package + // so the member can edit/delete their packages. + if ($packages = $this->getUploadedPackages()) { + $this->page->editForm = array(); + while (list($i, $j) = each($packages)) { + $editForm = new EditPackage($this->dbh, + "edit_member_package_$j", + 'post', + '', + '', + array('id' => $j), + true); + + $editForm->configureForm(); + $this->page->editForm[] = $editForm->toHtml($this->tEngine); + } + } + } + + // }}} +} + +/** + * Form to handle creating a new package in the members only area + * + * Handles inserting new package into db as a pending package and creating a + * tuple in the member_updates table which will allow the admin to + * approve/deny the new package request. + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + */ +class AddPackage extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * The table name in the database used to store the data + * + * @var string + * @access public + */ + public $tableName = 'member_packages'; + + /** + * The template used to render the form + * + * @var string + * @access protected + */ + protected $formTemplate = 'addPackage.tpl'; + + /** + * Description for protected + * @var array + * @access protected + */ + protected $registeredRules = array(); + + /** + * Description for protected + * @var string + * @access protected + */ + protected $successMsg + = '
    + You successfully uploaded your package. +
    '; + + /** + * Description for protected + * @var array + * @access protected + */ + protected $mimeTypes = array( + 'image/jpe', + 'image/jpeg', + 'image/jpg', + 'image/jfif', + 'image/pjpeg', + 'image/pjp', + 'image/gif', + 'image/png', + ); + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional) Form's method defaults to 'POST' + * @param string $action (optional) Form's action. + * @param string $target (optional) Form's target defaults to '_self' + * @param mixed $attributes (optional) Extra attributes for tag. + * @param bool $trackSubmit (optional) Whether to track if the form was + * submitted by adding a special hidden + * field. + * + * @access public + * @see Toolkit_Members_Admin_EditPackages + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->dbh = $pdo; + } + + // }}} + + // {{{ configureForm() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @access public + * @see Toolkit_FormBuilder::setupElements() + * @return void + */ + public function configureElements() + { + $e = array(); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'title', + 'display' => 'Package Title', + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'display' => 'Package Description', + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'sdate', + 'display' => 'Start Date', + 'opts' => array( + 'format' => 'm / d / Y', + 'minYear' => date('Y'), + 'maxYear' => date('Y') + 10, + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy', + ), + ) + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'edate', + 'display' => 'End Date', + 'opts' => array( + 'format' => 'm / d / Y', + 'minYear' => date('Y'), + 'maxYear' => date('Y') + 10, + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy', + ), + ) + ); + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'remove_img_rmv', + 'display' => 'Remove Image', + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'curr_image', + 'display' => 'Current Image', + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'curr_image_rmv', + ); + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'image', + 'display' => 'Upload a Package Photo / Image', + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'add_rmv', + 'display' => 'Upload new package', + 'opts' => array('class' => 'submit') + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureRules() + + /** + * Configure rules for form + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + + $checkDate = create_function('$d', '$d = implode("-", $d); return Validate::date($d, array("format" => "%n-%j-%Y"));'); + $r[] = array( + 'element' => 'sdate', + 'message' => 'ERROR: Invalid Date!', + 'type' => 'callback', + 'format' => $checkDate, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'edate', + 'message' => 'ERROR: Invalid Date!', + 'type' => 'callback', + 'format' => $checkDate, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'image', + 'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!', + 'type' => 'mimetype', + 'format' => $this->mimeTypes, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + // {{{ configureConstants() + + /** + * Configure constants for form + * + * @return void + * @access public + */ + public function configureConstants() + { + $c = array( + 'remove_img_rmv' => false + ); + + $this->setupConstants($c); + } + + // }}} + // {{{ configureFilters() + + /** + * Configure filters for form + * + * @return void + * @access public + */ + public function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + + // {{{ deleteImage() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $is Parameter description (if any) ... + * @param unknown $img Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access protected + */ + protected function deleteImage(Toolkit_Image_Server $is, $img) + { + return $is->imageDelete($img); + } + + // }}} + + // {{{ insertData() + + /** + * Create a new package in the db + * + * @param array &$values Form submitted values + * + * @return object db result of adding package + * @access protected + */ + protected function insertData(&$values) + { + try { + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ processData() + + /** + * Handles setting up the from processing and which function to get it done + * + * @param array $values Submitted values from the form. + * + * @return void + * @access protected + */ + protected function processData($values) + { + $id = $GLOBALS['memberAuth']->getAuthData('member_id'); + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member_Profile-$id", 'Dynamic'); + + $e =& $this->getElement('curr_image_rmv'); + + $packages = new Toolkit_Members_Packages(null, $id); + $packages->setDbh($this->dbh); + $packages->createMemberList(); + $values['pos'] = $packages->getListSize() + 1; + $values['image'] = $e->getValue('curr_image_rmv'); + $values['member_id'] = $GLOBALS['memberAuth']->getAuthData('member_id'); + $values['pending'] = false; + $values['sdate'] = implode('-', $values['sdate']); + $values['edate'] = implode('-', $values['edate']); + unset($values['MAX_FILE_SIZE'], + $values['curr_image_rmv'], + $values['remove_img_rmv'], + $values['add_rmv']); + + Toolkit_Common::getTableMetaData(); + $this->insertData($values); + + $listPage = BASE_URL . + "memberdb/index.php?Option=Member&Action=Edit&tab=3"; + header("Location: $listPage"); + } + + // }}} + + // {{{ setupRenderers() + + /** + * Set up the rendering engine we are going to use to display this form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $fo = Toolkit_Members::getFlexyOptions(); + + $this->template = new HTML_Template_Flexy($fo); + + $renderer =& new HTML_QuickForm_Renderer_ObjectFlexy($this->template); + + $this->accept($renderer); + $this->view = new StdClass; + $this->view->showCurrImg = $this->showCurrImg; + $this->view->form = $renderer->toObject(); + $this->template->compile($this->formTemplate); + } + + // }}} + + // {{{ validNewImg() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $newImg Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + function validNewImg(array $newImg) + { + return (is_numeric($newImg['size']) && + $newImg['size'] > 0 && + in_array($newImg['type'], $this->mimeTypes)); + } + + // }}} + // {{{ removeOldImage() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $is Parameter description (if any) ... + * @param unknown $oldImg Parameter description (if any) ... + * + * @return void + * @access public + */ + function removeOldImage(Toolkit_Image_Server $is, $oldImg) + { + $this->deleteImage($is, $oldImg); + if ($this->elementExists('curr_image_rmv')) { + $e =& $this->getElement('curr_image_rmv'); + $e->setValue(null); + $this->_submitValues['curr_image_rmv'] = null; + } + } + + // }}} + // {{{ syncCurrImage() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function syncCurrImage() + { + $is = new Toolkit_Image_Server(); + + $delImg = $this->getSubmitValue('remove_img_rmv'); + $oldImg = $this->getSubmitValue('curr_image_rmv'); + $newImg = $this->getSubmitValue('image'); + + if ($delImg && $oldImg) { + $this->removeOldImage($is, $oldImg); + unset($oldImg); + } elseif ($oldImg && $this->validNewImg($newImg)) { + $this->removeOldImage($is, $oldImg); + unset($oldImg); + } + + if ($this->validNewImg($newImg)) { + $image = $this->uploadImage($is, 'image'); + } else { + $image = $oldImg; + } + + if ($image) { + $this->updatePhotoElements($is, $image); + $this->showCurrImg = true; + } + } + + // }}} + // {{{ toHtml() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @return string The rendered form + * @access public + */ + public function toHtml() + { + // We need to validate (and freeze if needed) + // before we render the form. That way the + // template knows about any errors on the form. + $this->validated = $this->validate(); + + // If they have submitted the form and uploaded a proper image + // but some other element had an error, then we need to show + // their uploaded image in the form + if ($this->isSubmitted()) { + $this->syncCurrImage(); + } + + $this->setupRenderers(); + + if ($this->validated) { + $processed = $this->process( + array(&$this, 'processData'), + $this->mergeFiles + ); + } + + return $this->template->bufferedOutputObject($this->view); + } + + // }}} + + // {{{ updatePhotoElements() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $is Parameter description (if any) ... + * @param string $image Parameter description (if any) ... + * + * @return void + * @access public + */ + public function updatePhotoElements(Toolkit_Image_Server $is, $image) + { + // Get the dimensions of the image + $dimensions = $is->getImageSize(MEMBER_PHOTOS . $image); + if (PEAR::isError($dimensions)) { + Toolkit_Common::handleError($dimensions); + } + list($w, $h) = $dimensions; + $s = MEMBER_PHOTOS . $image; + + // Set the image to show in the element + $e =& $this->getElement('curr_image'); + $e->setText(''); + + // updated the hidden elements value to make sure it + // holds the most up-to-date image name + $e =& $this->getElement('curr_image_rmv'); + $e->setValue($image); + } + + // }}} + // {{{ uploadImage() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $is Parameter description (if any) ... + * @param unknown $field Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access protected + */ + protected function uploadImage(Toolkit_Image_Server $is, $field) + { + return $is->imageUpload($field); + } + + // }}} +} + +/** + * Form to handle editing/deleting existing packages in members only area + * + * Handles updating caption requests for a member or to remove a + * package from thier profile + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + * @see Toolkit_FormBuilder + */ +class EditPackage extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * The table name in the database used to store the data + * + * @var string + * @access public + */ + public $tableName = 'member_packages'; + + /** + * The template used to render the form + * + * @var string + * @access protected + */ + protected $formTemplate = 'editPackage.tpl'; + + /** + * Id of package in db + * @var integer + * @access protected + */ + protected $packageId; + + /** + * Description for protected + * @var string + * @access protected + */ + protected $successMsg + = '
    + You successfully updated your package. +
    '; + + /** + * Any rules we want to register for this form + * @var array + * @access protected + */ + protected $registeredRules = array(); + + /** + * Description for protected + * @var array + * @access protected + */ + protected $mimeTypes = array( + 'image/jpe', + 'image/jpeg', + 'image/jpg', + 'image/jfif', + 'image/pjpeg', + 'image/pjp', + 'image/gif', + 'image/png', + ); + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $formName Form's name. + * @param string $method (optional) Form's method defaults to 'POST' + * @param string $action (optional) Form's action. + * @param string $target (optional) Form's target defaults to '_self' + * @param mixed $attributes (optional) Extra attributes for tag. + * @param bool $trackSubmit (optional) Whether to track if the form was + * submitted by adding a special hidden + * field. + * + * @access public + * @see Toolkit_Members_Admin_EditPackages + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->packageId = $attributes['id']; + $id = $GLOBALS['memberAuth']->getAuthData('member_id'); + $this->packages = new Toolkit_Members_Packages(null, $id); + $this->packages->setDbh($pdo); + $this->packages->createMemberList(); + $this->dbh = $pdo; + } + + // }}} + + // {{{ configureForm() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureDefaults(); + $this->configureFilters(); + $this->configureRules(); + } + + // }}} + // {{{ configureDefaults() + + /** + * Setup the element default values for form + * + * @access public + * @see Toolkit_FormBuilder::setupDefaults() + * @return void + */ + public function configureDefaults() + { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = {$this->packageId}"; + + $defaults = $this->dbh->query($sql)->fetch(PDO::FETCH_ASSOC); + $defaults['curr_image_rmv'] = $defaults['image']; + $img = ''; + $defaults['curr_image'] = sprintf($img, MEMBER_PHOTOS . $defaults['image']); + $this->showCurrImg = $defaults['image']; + $this->setupDefaults($defaults); + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @access public + * @see Toolkit_FormBuilder::setupElements() + * @return void + */ + public function configureElements() + { + $e = array(); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'title', + 'display' => 'Package Title', + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'display' => 'Package Description', + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'sdate', + 'display' => 'Start Date', + 'opts' => array( + 'format' => 'm / d / Y', + 'minYear' => date('Y'), + 'maxYear' => date('Y') + 10, + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy', + ), + ) + ); + $e[] = array( + 'type' => 'date', + 'req' => true, + 'name' => 'edate', + 'display' => 'End Date', + 'opts' => array( + 'format' => 'm / d / Y', + 'minYear' => date('Y'), + 'maxYear' => date('Y') + 10, + 'addEmptyOption' => true, + 'emptyOptionValue' => '', + 'emptyOptionText' => array( + 'm' => 'mm', + 'd' => 'dd', + 'Y' => 'yyyy', + ), + ) + ); + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'remove_img_rmv', + 'display' => 'Remove Image', + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'curr_image', + 'display' => 'Current Image', + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'curr_image_rmv', + ); + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'image', + 'display' => 'Upload a Package Photo / Image', + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'add_rmv', + 'display' => 'Update Package', + 'opts' => array('class' => 'submit') + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'remove_rmv', + 'display' => 'Remove Package', + 'opts' => array('class' => 'submit') + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureRules() + + /** + * Configure rules for form + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + + $checkDate = create_function('$d', '$d = implode("-", $d); return Validate::date($d, array("format" => "%n-%j-%Y"));'); + $r[] = array( + 'element' => 'sdate', + 'message' => 'ERROR: Invalid Date!', + 'type' => 'callback', + 'format' => $checkDate, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'edate', + 'message' => 'ERROR: Invalid Date!', + 'type' => 'callback', + 'format' => $checkDate, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + $r[] = array( + 'element' => 'image', + 'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!', + 'type' => 'mimetype', + 'format' => $this->mimeTypes, + 'validation' => $this->validationType, + 'reset' => false, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + // {{{ configureConstants() + + /** + * Configure constants for form + * + * @return void + * @access public + */ + public function configureConstants() + { + $c = array( + 'remove_img_rmv' => false + ); + + $this->setupConstants($c); + } + + // }}} + // {{{ configureFilters() + + /** + * Configure filters for form + * + * @return void + * @access public + */ + public function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + + // {{{ deleteImage() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $is Parameter description (if any) ... + * @param unknown $img Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access protected + */ + protected function deleteImage(Toolkit_Image_Server $is, $img) + { + return $is->imageDelete($img); + } + + // }}} + + // {{{ processData() + + /** + * Handles setting up the from processing and which function to get it done + * + * @param array $values Submitted values from the form. + * + * @return void + * @access protected + */ + protected function processData($values) + { + $id = $GLOBALS['memberAuth']->getAuthData('member_id'); + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + $cache->remove("Member_Profile-$id", 'Dynamic'); + + $e =& $this->getElement('curr_image_rmv'); + + $values['image'] = $e->getValue('curr_image_rmv'); + $values['sdate'] = implode('-', $values['sdate']); + $values['edate'] = implode('-', $values['edate']); + unset($values['MAX_FILE_SIZE'], + $values['curr_image_rmv'], + $values['remove_img_rmv'], + $values['add_rmv']); + + Toolkit_Common::getTableMetaData(); + $this->updateData($values); + + $listPage = BASE_URL . + "memberdb/index.php?Option=Member&Action=Edit&tab=3"; + header("Location: $listPage"); + } + + // }}} + + // {{{ setupRenderers() + + /** + * Set up the rendering engine we are going to use to display this form + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $fo = Toolkit_Members::getFlexyOptions(); + + $this->template = new HTML_Template_Flexy($fo); + + $renderer =& new HTML_QuickForm_Renderer_ObjectFlexy($this->template); + + $this->accept($renderer); + $this->view = new StdClass; + $this->view->showCurrImg = $this->showCurrImg; + $this->view->form = $renderer->toObject(); + $this->template->compile($this->formTemplate); + } + + // }}} + + // {{{ validNewImg() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param array $newImg Parameter description (if any) ... + * + * @return mixed Return description (if any) ... + * @access public + */ + function validNewImg(array $newImg) + { + return (is_numeric($newImg['size']) && + $newImg['size'] > 0 && + in_array($newImg['type'], $this->mimeTypes)); + } + + // }}} + // {{{ removeOldImage() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $is Parameter description (if any) ... + * @param unknown $oldImg Parameter description (if any) ... + * + * @return void + * @access public + */ + function removeOldImage(Toolkit_Image_Server $is, $oldImg) + { + $this->deleteImage($is, $oldImg); + if ($this->elementExists('curr_image_rmv')) { + $e =& $this->getElement('curr_image_rmv'); + $e->setValue(null); + $this->_submitValues['curr_image_rmv'] = null; + } + } + + // }}} + // {{{ syncCurrImage() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function syncCurrImage() + { + $is = new Toolkit_Image_Server(); + + $delImg = $this->getSubmitValue('remove_img_rmv'); + $oldImg = $this->getSubmitValue('curr_image_rmv'); + $newImg = $this->getSubmitValue('image'); + + if ($delImg && $oldImg) { + $this->removeOldImage($is, $oldImg); + unset($oldImg); + } elseif ($oldImg && $this->validNewImg($newImg)) { + $this->removeOldImage($is, $oldImg); + unset($oldImg); + } + + if ($this->validNewImg($newImg)) { + $image = $this->uploadImage($is, 'image'); + } else { + $image = $oldImg; + } + + if ($image) { + $this->updatePhotoElements($is, $image); + $this->showCurrImg = true; + } + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @return string The rendered form + * @access public + */ + public function toHtml() + { + // We need to validate (and freeze if needed) + // before we render the form. That way the + // template knows about any errors on the form. + $this->validated = $this->validate(); + + // If they have submitted the form and uploaded a proper image + // but some other element had an error, then we need to show + // their uploaded image in the form + if ($this->isSubmitted()) { + $this->syncCurrImage(); + } + + $this->setupRenderers(); + + if ($this->validated) { + $processed = $this->process( + array(&$this, 'processData'), + $this->mergeFiles + ); + } + + return $this->template->bufferedOutputObject($this->view); + } + + // }}} + + // {{{ removePackage() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param unknown $id Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access protected + */ + protected function removePackage($id) + { + try { + // need to delete the image associated w/ this package here. + $sql = " + DELETE FROM {$this->tableName} + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ updateData() + + /** + * Update the package caption + * + * @param array $values Submitted form values + * + * @return boolean Result of updating the caption in the db + * @access public + */ + protected function updateData($values) + { + try { + if (array_key_exists('remove_rmv', $values)) { + return $this->removePackage($this->packageId); + } + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('id = :id') + ); + + $values['id'] = $this->packageId; + return Toolkit_Common::processQuery($this->dbh, $sql, $values); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ updatePhotoElements() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $is Parameter description (if any) ... + * @param string $image Parameter description (if any) ... + * + * @return void + * @access public + */ + public function updatePhotoElements(Toolkit_Image_Server $is, $image) + { + // Get the dimensions of the image + $dimensions = $is->getImageSize(MEMBER_PHOTOS . $image); + if (PEAR::isError($dimensions)) { + Toolkit_Common::handleError($dimensions); + } + list($w, $h) = $dimensions; + $s = MEMBER_PHOTOS . $image; + + // Set the image to show in the element + $e =& $this->getElement('curr_image'); + $e->setText(''); + + // updated the hidden elements value to make sure it + // holds the most up-to-date image name + $e =& $this->getElement('curr_image_rmv'); + $e->setValue($image); + } + + // }}} + // {{{ uploadImage() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @param object $is Parameter description (if any) ... + * @param unknown $field Parameter description (if any) ... + * + * @return object Return description (if any) ... + * @access protected + */ + protected function uploadImage(Toolkit_Image_Server $is, $field) + { + return $is->imageUpload($field); + } + + // }}} +} +?> diff --git a/Toolkit/Members/EditPhoto.php b/Toolkit/Members/EditPhoto.php new file mode 100644 index 0000000..9062fe7 --- /dev/null +++ b/Toolkit/Members/EditPhoto.php @@ -0,0 +1,235 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditPhoto.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see Toolkit/Image/Server.php + */ + + +/** + * The image server processing class + */ +require_once BASE . 'Toolkit/Image/Server.php'; + +/** + * Form to handle editing/deleting existing photos in members only area + * + * Handles updating caption requests for a member or to remove a + * photo from thier profile + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_EditPhoto extends Toolkit_Members_Admin_EditPhoto +{ + // {{{ configureDefaults() + + /** + * Sets the defaults for elements in the form. + * + * @return void + * @access public + */ + public function configureDefaults() + { + $photo = $this->photos->findNode($this->photoId); + $defaults = array( + 'caption' => $photo->getCaption(), + 'pos' => $photo->getPosition(), + 'pid' => $photo->getId(), + ); + + // overwrite the photo caption w/ the pending + // caption, ONLY if the pending caption exists. + $pc = $photo->getPendingCaption(); + if (!empty($pc)) { + $defaults['caption'] = $pc; + $photo->setFauxPending(true); + } + $this->setupDefaults($defaults); + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @param Config_Container $c application configuration + * + * @return void + * @access public + */ + public function configureElements(Config_Container $c) + { + $e = array(); + + $positions = range(1, $this->photos->getListSize(true)); + $options = array_combine($positions, $positions); + + $config =& $c->getItem('section', 'photos'); + $maxLength =& $config->getItem('directive', 'maxCaptionLength'); + // All Grouped Elements are created here. + + // All Elements are created here. This includes group element definitions. + $cur = $this->photos->findNode($this->photoId); + + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'pid' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'caption', + 'display' => 'Image Caption', + 'opts' => array( + 'class' => 'text', + 'maxlength' => $maxLength->getContent(), + ), + 'noCharLimit' => true + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'pos', + 'display' => 'Position', + 'opts' => $options, + 'att' => array('id' => "pos{$cur->getPosition()}") + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'update', + 'display' => 'Update Photo', + 'opts' => array('class' => 'submit') + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'delete', + 'display' => 'Delete Photo', + 'opts' => array('class' => 'photoDelete') + ); + + $this->setupElements($e); + } + + // }}} + // {{{ createPendingCaption() + + /** + * Updates the caption in the member_updates table for the photo + * + * @param array &$values submitted values from the form. + * @param Config_Container $c Member Configuration + * + * @return sql insert result + * @access protected + */ + protected function createPendingCaption(&$values, Config_Container $c) + { + $config = $c->getItem('section', 'tables'); + $pendingTable = $config->getItem('directive', 'pendingTable'); + + try { + // Insert the picture into the updates table for approval. + $sql = " + INSERT INTO {$pendingTable->getContent()} + (member_id, field, update, db_table, + data_type, label, foreign_key) + VALUES + (:member_id, :field, :update, :db_table, + :data_type, :label, :foreign_key)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam( + ':member_id', + $GLOBALS['memberAuth']->getAuthData('member_id'), + PDO::PARAM_INT + ); + $stmt->bindValue(':field', 'caption', PDO::PARAM_STR); + $stmt->bindParam(':update', $values['caption'], PDO::PARAM_BOOL); + $stmt->bindValue(':db_table', 'member_photos', PDO::PARAM_STR); + $stmt->bindValue(':data_type', 'text', PDO::PARAM_STR); + $stmt->bindValue(':label', 'Caption', PDO::PARAM_STR); + $stmt->bindParam(':foreign_key', $values['pid'], PDO::PARAM_STR); + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @param HTML_Template_Flexy $tEngine Templating Engine + * @param Cache_Lite $cache Caching Engine + * @param Toolkit_Image_Server $is Image Server + * @param Config_Container $c Member Configuration + * + * @return string The rendered form + * @access public + */ + public function toHtml( + HTML_Template_Flexy $tEngine, + Cache_Lite $cache, + Toolkit_Image_Server $is, + Config_Container $c + ) { + if ($this->validate()) { + $config = $c->getItem('section', 'conf'); + $strictPending = $config->getItem('directive', 'strictPending'); + + $id = $GLOBALS['memberAuth']->getAuthData('member_id'); + $res = $cache->remove("Member-$id", 'Profile'); + + if ($this->getSubmitValue('delete')) { + $this->photos->removeNode($is, $c, $this->getSubmitValue('pid')); + } + + if ($strictPending->getContent() && !$this->getSubmitValue('delete')) { + $this->createPendingCaption($this->getSubmitValues(), $c); + header('Location:' . $this->getAttribute('action')); + } else { + $this->process( + array(&$this, 'processData'), + $this->mergeFiles + ); + } + } + + $this->setupRenderers($tEngine); + + return $tEngine->bufferedOutputObject($this->view); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Exposure.php b/Toolkit/Members/Exposure.php new file mode 100755 index 0000000..1d27689 --- /dev/null +++ b/Toolkit/Members/Exposure.php @@ -0,0 +1,255 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: Exposure.php,v 1.2 2009/12/15 20:18:15 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Members_Exposure + * + * Exposure Tracking for Member DB + * tracking: + * list view + * detail view + * click thru + * Tracking record in exposure table are updated if they have + * one already for that month. + * If they do not then one is added. + * NOTE: + * A check is done to see if the table exposure is there. + * If it is not there then it is created + * + * @category MembersDB + * @package Toolkit_Members + * @author Steve Sutton + * @copyright 2009 Steve Sutton + * @license Gaslight Media + * @link http://pear.php.net/package/Members + * @see References to other sections (if any)... + */ +class Toolkit_Members_Exposure +{ + // {{{ properties + + /** + * PDO Object instance + * @var object + * @access private + */ + private $_dbh; + + /** + * Member's member_id + * @var unknown + * @access private + */ + private $_member_id; + + /** + * Original Table name is exposure + * can be changed to anything though + * @var unknown + * @access private + */ + private $_tableName = 'exposure'; + /** + * Type of update list,detail,click + * @var unknown + * @access private + */ + private $_type; + + // }}} + // {{{ __construct($member_id, $type = 'list') + + /** + * __construct + * + * @param unknown $member_id Member + * @param string $type Which Type + * + * @return void + * @access public + */ + function __construct($member_id, $type = 'list') + { + $this->_type = $type; + $this->_member_id = $member_id; + if (!$this->checkType()) { + die('Invalid type given'); + } + $this->_dbh = Toolkit_Database::getInstance(); + $this->checkTableInstallation(); + $this->runUpdate(); + } + + // }}} + // {{{ createTable() + + /** + * createTable + * + * Creates the $this->_tableName table for tracking views + * + * @return void + * @access public + */ + function createTable() + { + $sql = " +CREATE TABLE {$this->_tableName} ( + exposure_id SERIAL PRIMARY KEY, + list integer DEFAULT 0, + click integer DEFAULT 0, + detail integer DEFAULT 0, + edate date DEFAULT current_date, + member_id integer, + FOREIGN KEY (member_id) REFERENCES member(member_id) ON DELETE CASCADE +); + "; + $this->_dbh->query($sql); + } + + // }}} + // {{{ checkTableInstallation() + + /** + * checkTableInstallation + * + * Check to see if $this->_tableName table exists in database + * + * @return void + * @access public + */ + function checkTableInstallation() + { + try { + $sql = " + SELECT column_name, data_type + FROM information_schema.columns + WHERE table_name = :tname"; + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(':tname', $this->_tableName, PDO::PARAM_STR); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if (empty($row)) { + $this->createTable(); + } + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + // }}} + // {{{ checkType() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return boolean Return description (if any) ... + * @access public + */ + function checkType() + { + return in_array($this->_type, array('list', 'detail', 'click')); + } + + // }}} + // {{{ runUpdate() + + /** + * runUpdate() + * + * Based on $this->_type an update is maed if a record exist + * for that member for the current month. + * If there is no record then one is created. + * + * @return void + * @access private + */ + function runUpdate() + { + // Make sure the member actually exists in the members table + // before we try to manipulate its exposure count. If they don't + // exists, then just get us out of here so we don't throw any errors + try { + $sql = " + SELECT count(*) AS exists + FROM member + WHERE member_id = :member_id"; + + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(':member_id', $this->_member_id, PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('exists', $exists); + $stmt->fetch(); + + if (!$exists) { + return false; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + + $sql = " + SELECT count(exposure_id) as total + FROM {$this->_tableName} + WHERE member_id = :member_id + AND date_part('month', edate) = date_part('month', current_date) + AND date_part('year', edate) = date_part('year', current_date)"; + try { + $stmt = $this->_dbh->prepare($sql); + $stmt->bindParam(":member_id", $this->_member_id, PDO::PARAM_INT); + $stmt->execute(); + $exp_data = $stmt->fetch(PDO::FETCH_ASSOC); + if ($exp_data['total'] > 0) { + // if something is found then update the exposure record + $sql = " + UPDATE {$this->_tableName} + SET {$this->_type} = {$this->_type} + 1 + WHERE member_id = :member_id"; + try { + $stmt2 = $this->_dbh->prepare($sql); + $stmt2->bindParam( + ":member_id", + $this->_member_id, + PDO::PARAM_INT + ); + $stmt2->execute(); + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + } else { + // else insert a new exposure record + $sql = " + INSERT INTO {$this->_tableName} ({$this->_type}, member_id) + VALUES (1, :member_id)"; + try { + $stmt2 = $this->_dbh->prepare($sql); + $stmt2->bindParam( + ":member_id", + $this->_member_id, + PDO::PARAM_INT + ); + $stmt2->execute(); + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + // }}} +} +?> diff --git a/Toolkit/Members/ExposureDetailReports.php b/Toolkit/Members/ExposureDetailReports.php new file mode 100755 index 0000000..bd349ab --- /dev/null +++ b/Toolkit/Members/ExposureDetailReports.php @@ -0,0 +1,175 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ExposureDetailReports.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link <> + */ + + +/** + * Short description for class + * + * Exposuer Report of Member list,click,detail views + * for admin and member only area + * flag in BASE.setup.phtml of + * + * @category MembersD + * @package Toolkit_Members + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @link <> + */ +class Toolkit_Members_ExposureDetailReports + extends Toolkit_FlexyDataGridBuilder +{ + // {{{ properties + + /** + * Table name for tracking + * @var string + * @access protected + */ + protected $tableName = 'exposure'; + + /** + * Description for protected + * @var array + * @access protected + */ + protected $queryParams = array(); + + /** + * Template File + * @var string + * @access protected + */ + protected $template = 'exposureDetail.tpl'; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * define where templates for the data grid are at, + * then call the parent constructor which will handle + * finishing the settings for the datagrid. + * + * After all settings are finished you can call the toHTML() + * function on this object and the datagrid + * will be rendered and returned as a string. + * Optionally you could call show() and the datagrid would + * be rendered and output immediatley to the screen. + * + * @param PDO $pdo PDO object used in the datagrid + * @param integer $limit The number of records to display per page. + * @param integer $page The current page view. In most cases, + * this is useless. Note: if you specify + * this, the "page"GET variable will be ignored. + * @param string $rendererType The type of renderer to use. You may + * prefer to use the $type argument of + * render, fill or getOutput. + * + * @access public + */ + public function __construct( + PDO $pdo, + $limit = null, + $page = null, + $rendererType = null + ) { + $this->pagerOptions['containerClass'] = 'pages'; + parent::__construct($pdo, $limit, $page, $rendererType); + } + + // }}} + + // {{{ configureColumns() + + /** + * Configures the columns (fields) that will be used in our datagrid renderer. + * + * @return void + * @access public + */ + protected function configureColumns() + { + $month =& new Structures_DataGrid_Column('Month', + 'month', + 'month', + null, + null, + array(&$this, 'showMonth')); + $this->addColumn($month); + + $memberName =& new Structures_DataGrid_Column('Member Name', + 'member_name', + 'member_name'); + $this->addColumn($memberName); + + $list =& new Structures_DataGrid_Column('List', + 'list', + 'list'); + $this->addColumn($list); + + $detail =& new Structures_DataGrid_Column('Detail', + 'detail', + 'detail'); + $this->addColumn($detail); + + $click =& new Structures_DataGrid_Column('Click', + 'click', + 'click'); + $this->addColumn($click); + } + + // }}} + + // {{{ setQuery() + + /** + * Sets the query to use to fetch the datagrid results + * + * @param integer $mid Member id to fetch reports for + * + * @return void + * @access public + */ + public function setQuery($mid) + { + $sql = " + SELECT e.*, date_part('epoch', e.edate) AS month, m.member_name + FROM exposure e LEFT OUTER JOIN member m + ON (m.member_id = e.member_id) + WHERE e.member_id = $mid"; + parent::setQuery($sql); + } + + // }}} + // {{{ showMonth() + + /** + * Returns the monht for a record. + * + * @param array $data Structure Datagrid + * + * @access public + * @return string + */ + public function showMonth($data) + { + return date('F, Y', $data['record']['month']); + } + + // }}} +} +?> diff --git a/Toolkit/Members/ExposureReports.php b/Toolkit/Members/ExposureReports.php new file mode 100755 index 0000000..8370c3d --- /dev/null +++ b/Toolkit/Members/ExposureReports.php @@ -0,0 +1,328 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ExposureReports.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link <> + */ + + +/** + * Toolkit_Members_ExposureReports + * + * Exposuer Report of Member list,click,detail views + * for admin and member only area + * flag in BASE.setup.phtml of + * + * @category MembersDB + * @package Toolkit_Members + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @link <> + */ +class Toolkit_Members_ExposureReports extends Toolkit_FlexyDataGridBuilder +{ + // {{{ properties + + protected $noRecMessage = 'No Data Found'; + /** + * Table name for tracking + * @var string + * @access protected + */ + protected $tableName = 'exposure'; + + /** + * Description for protected + * @var array + * @access protected + */ + protected $queryParams = array(); + + /** + * Template File + * @var string + * @access protected + */ + protected $template = 'exposureList.tpl'; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * define where templates for the data grid are at, + * then call the parent constructor which will handle + * finishing the settings for the datagrid. + * + * After all settings are finished you can call the toHTML() + * function on this object and the datagrid + * will be rendered and returned as a string. + * Optionally you could call show() and the datagrid would + * be rendered and output immediatley to the screen. + * + * @param PDO $pdo PDO object used in the datagrid + * @param integer $limit The number of records to display per page. + * @param integer $page The current page view. In most cases, + * this is useless. Note: if you specify + * this, the "page"GET variable will be ignored. + * @param string $rendererType The type of renderer to use. You may + * prefer to use the $type argument of + * render, fill or getOutput. + * + * @access public + */ + public function __construct( + PDO $pdo, + $limit = null, + $page = null, + $rendererType = null + ) { + $this->dbh = $pdo; + $this->checkTableInstallation(); + $this->pagerOptions['containerClass'] = 'pages'; + parent::__construct($pdo, $limit, $page, $rendererType); + } + + // }}} + + // {{{ createTable() + + /** + * createTable + * + * Creates the $this->tableName table for tracking views + * + * @return void + * @access public + */ + function createTable() + { + $sql = " + CREATE TABLE {$this->tableName} ( + exposure_id SERIAL PRIMARY KEY, + list integer DEFAULT 0, + click integer DEFAULT 0, + detail integer DEFAULT 0, + edate date DEFAULT current_date, + member_id integer, + FOREIGN KEY (member_id) REFERENCES member(member_id) ON DELETE CASCADE + );"; + $this->dbh->query($sql); + } + + // }}} + // {{{ checkTableInstallation() + + /** + * checkTableInstallation + * + * Check to see if $this->tableName table exists in database + * + * @return void + * @access public + */ + function checkTableInstallation() + { + try { + $sql = " + SELECT column_name, data_type + FROM information_schema.columns + WHERE table_name = :tname"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':tname', $this->tableName, PDO::PARAM_STR); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if (empty($row)) { + $this->createTable(); + } + } catch(PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureColumns() + + /** + * Configures the columns (fields) that will be used in our datagrid renderer. + * + * @return void + * @access public + */ + protected function configureColumns() + { + $recordUrl =& new Structures_DataGrid_Column('DirectURL', + 'directUrl', + 'directUrl', + null, + null, + array(&$this, 'recordUrl')); + $this->addColumn($recordUrl); + + $memberName =& new Structures_DataGrid_Column('Member Name', + 'member_name'); + $this->addColumn($memberName); + + $list =& new Structures_DataGrid_Column('List', + 'list', + 'list'); + $this->addColumn($list); + + $detail =& new Structures_DataGrid_Column('Detail', + 'detail', + 'detail'); + $this->addColumn($detail); + + $click =& new Structures_DataGrid_Column('Click', + 'click', + 'click'); + $this->addColumn($click); + } + + // }}} + + // {{{ recordUrl() + + /** + * Returns the url for a member. + * + * Used when configuring the columns for the data grid. This + * function generates the url to get to the member detail page + * + * @param array $data Structure_DataGrid + * + * @return string + * @access public + */ + public function recordUrl($data) + { + $month = ($_REQUEST['reportMonth']) ? '&reportMonth='. + $_REQUEST['reportMonth']: ''; + $cat = ($_REQUEST['cat']) ? '&cat='.$_REQUEST['cat']:''; + $subCat = ($_REQUEST['subCat']) ? '&subCat='. + $_REQUEST['subCat']:''; + return "members.php?". + "member_id={$data['record']['member_id']}". + $month. + $cat. + $subCat; + } + + // }}} + + // {{{ setControlObject() + + /** + * Sets any control object variables that are going to be used in the template + * + * @return void + * @access public + */ + protected function setControlObject() + { + $sql = " + SELECT date_part('month', min(edate)) AS start_month, + date_part('year', min(edate)) AS start_year, + date_part('month', max(edate)) AS end_month, + date_part('year', max(edate)) AS end_year + FROM exposure"; + + $sql = " + SELECT distinct ON (date_part('year', edate), + date_part('month', edate)) + date_part('month', edate) as month, + date_part('year', edate) as year + FROM exposure + WHERE member_id in ( + SELECT distinct member_id + FROM member) + ORDER BY date_part('year', edate), date_part('month', edate)"; + if ($monthData = $this->dbh->query($sql)->fetchAll()) { + if (!$_REQUEST['monthYear']) { + $m = date("n"); + $F = date("F"); + $Y = date("Y"); + $monthYear .= $m.' '.$Y; + } else { + $monthYear .= $_REQUEST['monthYear']; + } + foreach ($monthData as $data) { + $monthName = date( + "F", + mktime(0, 0, 0, $data['month'], 1, date('year')) + ); + $mData[$data['month'].'|'.$data['year']] = $monthName. + ' '.$data['year']; + } + $form = new HTML_QuickForm('ReportsListForm', 'get'); + $form->addElement('hidden', 'cat', $_REQUEST['cat']); + $form->addElement('hidden', 'subCat', $_REQUEST['subCat']); + $form->addElement( + 'select', + 'reportMonth', + 'Show Summary for month of ', + $mData + ); + $form->addElement('submit', 'reportSubmit', 'Go'); + if ($_REQUEST['reportMonth']) { + $form->setDefaults( + array('reportMonth' => $_REQUEST['reportMonth']) + ); + } else { + $form->setDefaults( + array('reportMonth' => date('n').'|'.date('Y')) + ); + } + $this->ctrlObj['exposureForm'] = $form->toHTML(); + } + } + + // }}} + // {{{ setQuery() + + /** + * Sets the query to use to fetch the datagrid results + * + * @param array $monthYear Which month to show + * + * @return void + * @access public + */ + public function setQuery($monthYear = null) + { + + if ($monthYear) { + list($month, $year) = explode("|", $monthYear); + } else { + $month = date('n'); + $year = date('Y'); + } + + $stime = date('m/d/Y', mktime(0, 0, 0, $month, 1, $year)); + $etime = date('m/d/Y', mktime(0, 0, 0, $month +1, -1, $year)); + + $sql = " + SELECT m.member_name, m.member_id, sum(e.list) AS list, + sum(e.click) as click, sum(e.detail) AS detail + FROM exposure e, member m + WHERE e.member_id = m.member_id + and e.edate >= '$stime' + and e.edate <= '$etime' + GROUP BY m.member_name, m.member_id + ORDER BY m.member_name"; + parent::setQuery($sql); + } + + // }}} +} +?> diff --git a/Toolkit/Members/FileDownload.php b/Toolkit/Members/FileDownload.php new file mode 100644 index 0000000..664f71e --- /dev/null +++ b/Toolkit/Members/FileDownload.php @@ -0,0 +1,224 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: FileDownload.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * File Download Manager + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version Release: @package_version@ + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_FileDownload +{ + // {{{ properties + + + /** + * Database Handler + * @var object + * @access protected + */ + protected $dbh; + + // }}} + // {{{ __construct() + + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object to use for dbh + * + * @return void + * @access public + */ + public function __construct(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + + // {{{ fileExists() + + + /** + * Determine if the file exists + * + * The file we are trying to get is determined by the file id passed in + * from the url. + * + * @param integer $fid File id to retrieve + * + * @return mixed array of file data if file exists, otherwise false + * @access protected + */ + protected function fileExists($fid) + { + if (!is_numeric($fid) || !ctype_digit((string) $fid)) { + return false; + } + + try { + $sql = " + SELECT * + FROM member_files + WHERE member_id = :mid + AND id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $this->mid, PDO::PARAM_INT); + $stmt->bindParam(':id', $fid, PDO::PARAM_INT); + $stmt->execute(); + + return $stmt->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ getFile() + + + /** + * Get the data about the file we are requesting + * + * @param integer $mid Member Id + * @param integer $fid File Id + * + * @return mixed Array of file data if success, otherwise PEAR error + * @access public + */ + public function getFile($mid, $fid) + { + if (!$this->memberExists($mid)) { + return PEAR::raiseError('Invalid Member'); + } + + if (!$file = $this->fileExists($fid)) { + return PEAR::raiseError('Invalid File'); + } + + if (empty($file['file_name'])) { + $file['file_name'] = $file['original_name']; + } + + return $file; + } + + // }}} + + // {{{ memberExists() + + + /** + * Determines if the member we are trying to get a file for is a real member + * + * @param integer $mid member id to check for + * + * @return boolean True if real member, False if not + * @access protected + */ + protected function memberExists($mid) + { + if (!is_numeric($mid) || !ctype_digit((string) $mid)) { + return false; + } + + try { + $sql = " + SELECT count(*) AS total + FROM member + WHERE member_id = :mid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $mid, PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('total', $total); + $row = $stmt->fetch(); + + if ($total) { + $this->mid = $mid; + return true; + } else { + return false; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ sendFileToBrowser() + // @codeCoverageIgnoreStart + + /** + * Sends the file to the browser via headers + * + * @param array $file File data to use + * + * @return void + * @access public + */ + public function sendFileToBrowser(array $file) + { + extract($file); + + $ext = pathinfo(MEMBER_UPLOADED_FILES . $name_on_disk, PATHINFO_EXTENSION); + switch ($ext) { + case 'txt' : + $type = 'text/plain'; + break; + + case 'doc' : + $type = 'application/msword'; + break; + + case 'xls' : + $type = 'application/vnd.ms-excel'; + break; + + case 'pdf' : + $type = 'application/pdf'; + break; + + default : + $type = 'application/pdf'; + break; + } + // now get the pdf from file and push out to browser + // using header() + header("Content-Type: $type;"); + header('Content-Disposition: attachment; filename="'.$file_name.'";'); + header('Content-Length: '.(string) $size); + header('Cache-Control: maxage=3600;'); //Adjust maxage appropriately + header('Pragma: public;'); + readfile(MEMBER_UPLOADED_FILES.$name_on_disk); + exit(); + } + + // @codeCoverageIgnoreEnd + // }}} +} +?> diff --git a/Toolkit/Members/Member.php b/Toolkit/Members/Member.php new file mode 100644 index 0000000..25626dc --- /dev/null +++ b/Toolkit/Members/Member.php @@ -0,0 +1,106 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Member.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Handle member record interaction + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version Release: @package_version@ + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_Member +{ + // {{{ properties + + + /** + * Description for protected + * @var unknown + * @access protected + */ + protected $pdo; + + // /// }}} + // {{{ __construct() + // @codeCoverageIgnoreStart + + /** + * Constructor + * + * @param PDO $pdo PHP Data Object + * @param Config_Container $c Application configuration + * + * @return void + * @access public + */ + public function __construct(PDO $pdo, Config_Container $c) + { + $this->dbh = $pdo; + $this->config = $c; + } + + // @codeCoverageIgnoreEnd + // }}} + + // {{{ canAddPhotos() + + /** + * calculate if a member can add more photos to their record + * + * @param Toolkit_Members_Photos $ll Linked List of member photos + * + * @return boolean + * @access public + */ + public function canAddPhotos(Toolkit_Members_Photos $ll) + { + // get reference to [conf] section of config file + $section =& $this->config->getItem('section', 'photos'); + $maxPhotos =& $section->getItem('directive', 'maxPhotos'); + + return ($ll->getListSize() < $maxPhotos->getContent()); + } + + // }}} + + // {{{ hasUploadedPhotos() + + /** + * Deterimines of the member has any photos uploaded to their record + * + * @param Toolkit_Members_Photos $ll Linked List of member photos + * @param boolean $fltr Filter pending when calculating + * + * @return boolean + * @access public + */ + public function hasUploadedPhotos( + Toolkit_Members_Photos $ll, + $fltr = false + ) { + $size = $ll->getListSize($fltr); + + return ($size > 0); + } + + // }}} +} +?> diff --git a/Toolkit/Members/Packages.php b/Toolkit/Members/Packages.php new file mode 100644 index 0000000..742b32f --- /dev/null +++ b/Toolkit/Members/Packages.php @@ -0,0 +1,370 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Packages.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see Structures/LinkedList/Double.php + * Toolkit/Members/Packages/Package.php + */ + +/** + * PEAR Linked List library + */ +require_once 'Structures/LinkedList/Double.php'; + +/** + * Linked List node class + */ +require_once 'Members/Packages/Package.php'; + +/** + * Class implementation of a linked list + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Structures/LinkedList/Double.php + */ +class Toolkit_Members_Packages extends Structures_LinkedList_Double +{ + // {{{ properties + + /** + * Database handler object + * @var object + * @access public + */ + public $dbh; + + /** + * DB id of member whos packages we are manipulating with this linked list + * @var integer + * @access protected + */ + protected $mid; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param object $root Linked List node object + * @param int $mid DB id of member we want to prepare the list for + * + * @access public + * @return void + */ + function __construct( + Structures_LinkedList_DoubleNode $root = null, + $mid = null + ) { + parent::__construct($root); + $this->setMember($mid); + } + + // }}} + + // {{{ createMemberList() + + /** + * Creates a linked list from all the packages a member has in the db. + * + * @param string $order The order to make the linked list in + * + * @return boolean false on error + * @access public + */ + public function createMemberList($order = 'pos') + { + if (!is_numeric($this->mid)) { + return; + } + + $safeOrder = array('pos', 'id'); + if (!in_array($order, $safeOrder)) { + $order = 'pos'; + } + try { + // Get each package tuple from the member_packages table. + $sql = " + SELECT * + FROM member_packages + WHERE member_id = :member_id + ORDER BY $order"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $this->mid, PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch()) { + // Create a new node w/ all the data we just extracted. + $node = $this->createNode($row); + $node->setDbh($this->dbh); + // Sets up any pending data the package might currently have. + $node->setPendingData(); + // Add the package node to the end of the linked list. + $res = $this->appendNode($node); + } + + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ createNode() + + /** + * Creates a new linked list node object + * + * @param array $data Data to populate the new node with + * + * @access public + * @return object newly created linked list node + */ + public function &createNode(array $data) + { + $node = new Toolkit_Members_Packages_Package($data); + $node->setDbh($this->dbh); + + return $node; + } + + // }}} + + // {{{ getListSize() + + /** + * Get how many nodes are currently in the linked list + * + * @param boolean $filterPending Include pending packages in the count + * + * @return integer number of nodes in the linked list + * @access public + */ + public function getListSize($filterPending = false) + { + $size = 0; + $cur = $this->rewind(); + + // If the current node is null, then we have no nodes + // in the linked list. return the empty size. + // Else we have at least one node in the linked list. + if (is_null($cur)) { + return $size; + } + + // Add one to the size of the list for every + // node we encounter. + do { + if ($filterPending) { + if (!$cur->getPending()) { + ++$size; + } + } else { + ++$size; + } + } while ($cur = $this->next()); + + return $size; + } + + // }}} + // {{{ getMemberId() + + /** + * Get which member this linked list is for + * + * @return integer id of member we are dealing with + * @access public + */ + public function getMemberId() + { + return $this->mid; + } + + // }}} + + // {{{ findNode() + + /** + * find a node from the linked list + * + * @param integer $target Id of package you are searching for + * + * @return mixed Toolkit_Members_Packages_Package if present, else false + * @access public + */ + public function &findNode($target) + { + $this->end(); + $startingId = $this->current->getId(); + + if ($target == $startingId) { + return $this->current; + } + + while ($curr = $this->previous()) { + if ($target == $curr->getId()) { + return $curr; + } + } + + return false; + } + + // }}} + + // {{{ moveNode() + + /** + * Adjust nodes position in the linked list + * + * @param integer $pid id of package you want to move + * @param integer $pos new position you want to move to + * + * @access public + * @return void + */ + public function moveNode($pid, $pos) + { + $node = $this->findNode($pid); + $oldPos = $node->getPosition(); + + if ($this->getListSize()) { + $cur = $this->rewind(); + do { + if ($cur->getId() == $pid) { + $cur->setPosition($pos); + } else { + $curPos = $cur->getPosition(); + if ($pos > $oldPos) { + if ($curPos <= $pos && $curPos > $oldPos) { + $cur->setPosition($curPos - 1); + } + } elseif ($pos < $oldPos) { + if ($curPos >= $pos && $curPos < $oldPos) { + $cur->setPosition($curPos + 1); + } + } + } + } while ($cur = $this->next()); + } + } + + // }}} + + // {{{ removeNode() + + /** + * Removes a node from the linked list + * + * @param Toolkit_Image_Server $is Image Server Object + * @param integer $target Id of package you want to remove + * + * @return boolean false on error + * @access public + */ + public function removeNode(Toolkit_Image_Server $is, $target) + { + $node = $this->findNode($target); + if (!$node) { + return false; + } + + $node->remove($is); + $remNodePos = $node->getPosition(); + + // only try and update positions in the linked list if there are nodes that + // will still exists after this node is removed ie. size is greater than 1 + if ($this->getListSize() > 1) { + $cur = $this->rewind(); + do { + if ($cur->getPosition() > $remNodePos) { + $cur->setPosition($cur->getPosition() - 1); + } + } while ($cur = $this->next()); + } + + $this->deleteNode($node); + } + + // }}} + + // {{{ setDbh() + + /** + * Set the Database Handler + * + * @param PDO $pdo PHP Data Object to use + * + * @return void + * @access public + */ + public function setDbh(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + // {{{ setMember() + + /** + * Sets which member we are working with + * + * @param integer $mid id of member + * + * @access public + * @return PEAR error on invalid member id + */ + public function setMember($mid) + { + if (is_integer($mid)) { + $this->mid = $mid; + } elseif (is_numeric($mid) && ctype_digit($mid)) { + $this->mid = $mid; + } else { + return PEAR::raiseError('invalid member id'); + } + } + + // }}} + + // {{{ emptyList() + + /** + * Deletes all nodes from a list + * + * @access public + * @return void + */ + public function emptyList() + { + $this->end(); + while ($cur = $this->current()) { + $this->deleteNode($cur); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/Packages/Package.php b/Toolkit/Members/Packages/Package.php new file mode 100644 index 0000000..b0ef42d --- /dev/null +++ b/Toolkit/Members/Packages/Package.php @@ -0,0 +1,387 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Package.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link <> + * @see Structures/LinkedList/Double.php + * Toolkit/Image/Server.php + */ + +/** + * PEAR linked list library + */ +require_once 'Structures/LinkedList/Double.php'; + +/** + * Class to handle uploading and processing of images on the image server + */ +require_once BASE . 'Toolkit/Image/Server.php'; + +/** + * Linked list node class + * + * Handles controlling all functionality for a linked list node + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link <> + * @see Structures_LinkedList_DoubleNode + */ +class Toolkit_Members_Packages_Package extends Structures_LinkedList_DoubleNode +{ + // {{{ properties + + /** + * Database handler object + * @var object + * @access public + */ + public $dbh; + + /** + * Tuple id of package in db + * @var integer + * @access protected + */ + protected $id; + + /** + * Image name on image server + * @var string + * @access protected + */ + protected $image; + + /** + * Packages position in the linked list / db + * @var integer + * @access protected + */ + protected $pos; + + /** + * If the package is new and is still pending + * @var boolean + * @access protected + */ + protected $pending; + + /** + * Member id this package belongs to + * @var integer + * @access protected + */ + protected $mid; + + /** + * DB table name where package data is stored + * @var string + * @access protected + */ + protected $tableName = 'member_packages'; + + // }}} + // {{{ __construct() + + /** + * Class Constructor + * + * @param array $data new node data + * + * @return void + * @access public + */ + public function __construct(array $data) + { + $this->id = $data['id']; + $this->image = $data['image']; + $this->title = $data['title']; + $this->pos = $data['pos']; + $this->pending = $data['pending']; + $this->mid = $data['member_id']; + } + + // }}} + + // {{{ setFauxPending() + + /** + * Make the package pending, but don't set it to pending in the DB + * + * This is useful in the members only area when only part of a + * package is pending but you need to show the entire package in a pending + * state. ie (titles can be pending) + * + * @param boolean $pending what to set the pending status to + * + * @return void + * @access public + */ + public function setFauxPending($pending) + { + $this->pending = $pending; + } + + // }}} + + // {{{ getTitle() + + /** + * Get the package title + * + * @return string packages title + * @access public + */ + public function getTitle() + { + return $this->title; + } + + // }}} + // {{{ getPendingTitle() + + /** + * Get the packages pending title (if set) + * + * @return string packages pending title + * @access public + */ + public function getPendingTitle() + { + return $this->pendingTitle; + } + + // }}} + // {{{ getId() + + /** + * Get the package id + * + * @return integer packages db id + * @access public + */ + public function getId() + { + return $this->id; + } + + // }}} + // {{{ getImage() + + /** + * Get the package image name + * + * @return string file name of image stored on image server + * @access public + */ + public function getImage() + { + return $this->image; + } + + // }}} + // {{{ getPending() + + /** + * Get the pending status of the package + * + * @return boolean if the package is pending or not + * @access public + */ + public function getPending() + { + return $this->pending; + } + + // }}} + // {{{ getPosition() + + /** + * Get the position of the package + * + * @return integer current position in the linked list / db of the package + * @access public + */ + public function getPosition() + { + return $this->pos; + } + + // }}} + + // {{{ remove() + + /** + * Remove a package from the db + * + * Handles deleting all data from the member_packages table and any + * data that might currently be pending for the package as well. + * + * @param Toolkit_Image_Server $is Image Server object + * + * @return boolean false on error + * @access public + */ + public function remove(Toolkit_Image_Server $is) + { + try { + $is->imageDelete($this->image); + // Get rid of the package in the member_packages table. + $sql = " + DELETE FROM {$this->tableName} + WHERE id = ?"; + + $stmt = $this->dbh->prepare($sql); + $stmt->execute(array($this->id)); + + // Get rid of any updates to the package so we don't have + // orphaned data lying around. + $sql = " + DELETE FROM " . Toolkit_Membersonly::PENDING_TABLE . " + WHERE db_table = '{$this->tableName}' + AND member_id = :member_id + AND foreign_key = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->bindParam(':id', $this->id, PDO::PARAM_INT); + $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ setDbh() + + /** + * Set the Database handler object + * + * @param PDO $pdo PHP Data Object + * + * @return void + * @access public + */ + public function setDbh(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + // {{{ setPending() + + /** + * Set the pending status for the package + * + * @param boolean $pending If the package is pending or not + * + * @return boolean result of db update + * @access public + */ + public function setPending($pending) + { + $this->pending = $pending; + try { + $sql = " + UPDATE {$this->tableName} + SET pending = ? + WHERE member_id = ? + AND id = ?"; + + $stmt = $this->dbh->prepare($sql); + return $stmt->execute(array($pending, $this->mid, $this->id)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setPendingData() + + /** + * Set the content of any data that might be pending + * + * Currently this only supports pending title + * + * @return bolean false on error + * @access public + */ + public function setPendingData() + { + try { + // Get any updates for that package that are still in + // a pending status. + $sql = " + SELECT * + FROM " . Toolkit_Membersonly::PENDING_TABLE . " + WHERE id in ( + SELECT max(id) + FROM " . Toolkit_Membersonly::PENDING_TABLE . " + WHERE foreign_key = :foreign_key + AND db_table = 'member_packages' + GROUP BY field)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->execute(array($this->id)); + $row = $stmt->fetch(); + + if ($row['field'] == 'title') { + $this->pendingCaption = $row['update']; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setPosition() + + /** + * Set a new position for a node + * + * Handle updating the nodes position in the linked list as well as db. + * + * @param integer $pos new position number for node + * + * @return boolean result of position update + * @access public + */ + public function setPosition($pos) + { + // Not updating anything so just return. + if ($pos == $this->pos) { + return true; + } + try { + $this->pos = $pos; + + $sql = " + UPDATE {$this->tableName} + SET pos = ? + WHERE member_id = ? + AND id = ?"; + + $stmt = $this->dbh->prepare($sql); + return $stmt->execute(array($pos, $this->mid, $this->id)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/Photos.php b/Toolkit/Members/Photos.php new file mode 100644 index 0000000..acd93ba --- /dev/null +++ b/Toolkit/Members/Photos.php @@ -0,0 +1,359 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Photos.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see Structures/LinkedList/Double.php + * Toolkit/Members/Photos/Photo.php + */ + +/** + * PEAR Linked List library + */ +require_once 'Structures/LinkedList/Double.php'; + +/** + * Linked List node class + */ +require_once 'Members/Photos/Photo.php'; + +/** + * Class implementation of a linked list + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Structures/LinkedList/Double.php + */ +class Toolkit_Members_Photos extends Structures_LinkedList_Double +{ + // {{{ properties + + /** + * DB id of member whos photos we are manipulating with this linked list + * @var integer + * @access protected + */ + protected $mid; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param Structures_LinkedList_DoubleNode $root Linked List node object + * @param integer $mid id of member we want + * to prepare the list for + * + * @access public + * @return void + */ + function __construct( + Structures_LinkedList_DoubleNode $root = null, + $mid = null + ) { + parent::__construct($root); + $this->setMember($mid); + /* + if (is_numeric($mid)) { + $this->createMemberList($mid); + } + */ + } + + // }}} + + // {{{ createMemberList() + + /** + * Creates a linked list from all the photos a member has in the db. + * + * @param PDO $dbh PHP Data Object + * @param Config_Container $c Member configuration + * @param string $order The order to make the linked list in + * + * @return boolean false on error + * @access public + */ + public function createMemberList( + PDO $dbh, + Config_Container $c, + $order = 'pos' + ) { + if (!ctype_digit((string) $this->mid)) { + return; + } + + // Make sure the list is actually empty before you recreate it + // otherwise you can end up w/ duplicate values in the LL + $this->emptyList(); + + $safeOrder = array('pos', 'id'); + if (!in_array($order, $safeOrder)) { + $order = 'pos'; + } + try { + // Get each photo tuple from the member_photos table. + $sql = " + SELECT * + FROM member_photos + WHERE member_id = :member_id + ORDER BY $order"; + + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':member_id', $this->mid, PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch()) { + // Create a new node w/ all the data we just extracted. + $node = $this->createNode($row); + $node->setDbh($dbh); + // Sets up any pending data the photo might currently have. + $node->setPendingData($c); + // Add the photo node to the end of the linked list. + $res = $this->appendNode($node); + } + + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ createNode() + + /** + * Creates a new linked list node object + * + * @param array $data Data to populate the new node with + * + * @return Toolkit_Members_Photos_Photo linked list node + * @access public + */ + public function &createNode(array $data) + { + return new Toolkit_Members_Photos_Photo($data); + } + + // }}} + + // {{{ getListSize() + + /** + * Get how many nodes are currently in the linked list + * + * @param boolean $filterPending Include pending photos in the count + * + * @return integer number of nodes in the linked list + * @access public + */ + public function getListSize($filterPending = false) + { + $size = 0; + $cur = $this->rewind(); + + // If the current node is null, then we have no nodes + // in the linked list. return the empty size. + // Else we have at least one node in the linked list. + if (is_null($cur)) { + return $size; + } + + // Add one to the size of the list for every + // node we encounter. + do { + if ($filterPending) { + if (!$cur->getPending()) { + ++$size; + } + } else { + ++$size; + } + } while ($cur = $this->next()); + + return $size; + } + + // }}} + // {{{ getMemberId() + + /** + * Get which member this linked list is for + * + * @return integer id of member we are dealing with + * @access public + */ + public function getMemberId() + { + return $this->mid; + } + + // }}} + + // {{{ findNode() + + /** + * find a node from the linked list + * + * @param integer $target Id of photo you are searching for + * + * @return mixed Toolkit_Members_Photos_Photo object if present, else false + * @access public + */ + public function &findNode($target) + { + $this->end(); + $startingId = $this->current->getId(); + + if ($target == $startingId) { + return $this->current; + } + + while ($curr = $this->previous()) { + if ($target == $curr->getId()) { + return $curr; + } + } + + return false; + } + + // }}} + + // {{{ moveNode() + + /** + * Adjust nodes position in the linked list + * + * @param integer $pid id of photo you want to move + * @param integer $pos new position you want to move to + * + * @return void + * @access public + */ + public function moveNode($pid, $pos) + { + $node = $this->findNode($pid); + $oldPos = $node->getPosition(); + + if ($this->getListSize()) { + $cur = $this->rewind(); + do { + if ($cur->getId() == $pid) { + $cur->setPosition($pos); + } else { + $curPos = $cur->getPosition(); + if ($pos > $oldPos) { + if ($curPos <= $pos && $curPos > $oldPos) { + $cur->setPosition($curPos - 1); + } + } elseif ($pos < $oldPos) { + if ($curPos >= $pos && $curPos < $oldPos) { + $cur->setPosition($curPos + 1); + } + } + } + } while ($cur = $this->next()); + } + } + + // }}} + + // {{{ removeNode() + + /** + * Removes a node from the linked list + * + * @param Toolkit_Image_Server $is Image Server Object + * @param Config_Container $c Member configuration + * @param integer $target Id of photo you want to remove + * + * @return boolean false on error + * @access public + */ + public function removeNode( + Toolkit_Image_Server $is, + Config_Container $c, + $target + ) { + $node = $this->findNode($target); + if (!$node) { + return false; + } + + $node->remove($is, $c); + $remNodePos = $node->getPosition(); + + // only try and update positions in the linked list if there are nodes that + // will still exists after this node is removed ie. size is greater than 1 + if ($this->getListSize() > 1) { + $cur = $this->rewind(); + do { + if ($cur->getPosition() > $remNodePos) { + $cur->setPosition($cur->getPosition() - 1); + } + } while ($cur = $this->next()); + } + + $this->deleteNode($node); + } + + // }}} + + // {{{ setMember() + + /** + * Sets which member we are working with + * + * @param integer $mid id of member + * + * @access public + * @return void + */ + public function setMember($mid) + { + if (ctype_digit((string) $mid)) { + $this->mid = $mid; + } + } + + // }}} + + // {{{ emptyList() + + /** + * Deletes all nodes from a list + * + * @access public + * @return void + */ + public function emptyList() + { + $this->end(); + while ($cur = $this->current()) { + $this->deleteNode($cur); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/Photos/Photo.php b/Toolkit/Members/Photos/Photo.php new file mode 100644 index 0000000..0dfa9aa --- /dev/null +++ b/Toolkit/Members/Photos/Photo.php @@ -0,0 +1,440 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Photo.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see Structures/LinkedList/Double.php + * Toolkit/Image/Server.php + */ + +/** + * PEAR linked list library + */ +require_once 'Structures/LinkedList/Double.php'; + +/** + * Class to handle uploading and processing of images on the image server + */ +require_once BASE . 'Toolkit/Image/Server.php'; + +/** + * Linked list node class + * + * Handles controlling all functionality for a linked list node + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Structures_LinkedList_DoubleNode + */ +class Toolkit_Members_Photos_Photo extends Structures_LinkedList_DoubleNode +{ + // {{{ properties + + /** + * Database handler object + * @var object + * @access public + */ + public $dbh; + + /** + * Tuple id of photo in db + * @var integer + * @access protected + */ + protected $id; + + /** + * Image name on image server + * @var string + * @access protected + */ + protected $image; + + /** + * Photo caption + * @var string + * @access protected + */ + protected $caption; + + /** + * Photo pending caption (if set) + * @var string + * @access protected + */ + protected $pendingCaption; + + /** + * Photos position in the linked list / db + * @var integer + * @access protected + */ + protected $pos; + + /** + * If the photo is new and is still pending + * @var boolean + * @access protected + */ + protected $pending; + + /** + * Member id this photo belongs to + * @var integer + * @access protected + */ + protected $mid; + + /** + * DB table name where photo data is stored + * @var string + * @access protected + */ + protected $tableName = 'member_photos'; + + // }}} + // {{{ __construct() + + /** + * Class Constructor + * + * @param array $data new node data + * + * @return void + * @access public + */ + public function __construct(array $data) + { + $this->id = $data['id']; + $this->image = $data['image']; + $this->caption = $data['caption']; + $this->pos = $data['pos']; + $this->pending = $data['pending']; + $this->mid = $data['member_id']; + } + + // }}} + + // {{{ setFauxPending() + + /** + * Make the photo pending, but don't set it to pending in the DB + * + * This is useful in the members only area when only part of a + * photo is pending but you need to show the entire photo in a pending + * state. ie (captions can be pending) + * + * @param boolean $pending what to set the pending status to + * + * @return void + * @access public + */ + public function setFauxPending($pending) + { + $this->pending = $pending; + } + + // }}} + + // {{{ getCaption() + + /** + * Get the photo caption + * + * @return string photos caption + * @access public + */ + public function getCaption() + { + return $this->caption; + } + + // }}} + // {{{ getPendingCaption() + + /** + * Get the photos pending caption (if set) + * + * @return string photos pending caption + * @access public + */ + public function getPendingCaption() + { + return $this->pendingCaption; + } + + // }}} + // {{{ getId() + + /** + * Get the photo id + * + * @return integer photos db id + * @access public + */ + public function getId() + { + return $this->id; + } + + // }}} + // {{{ getImage() + + /** + * Get the photo image name + * + * @return string file name of image stored on image server + * @access public + */ + public function getImage() + { + return $this->image; + } + + // }}} + // {{{ getPending() + + /** + * Get the pending status of the photo + * + * @return boolean if the photo is pending or not + * @access public + */ + public function getPending() + { + return $this->pending; + } + + // }}} + // {{{ getPosition() + + /** + * Get the position of the photo + * + * @return integer current position in the linked list / db of the photo + * @access public + */ + public function getPosition() + { + return $this->pos; + } + + // }}} + + // {{{ remove() + + /** + * Remove a photo from the db + * + * Handles deleting all data from the member_photos table and any + * data that might currently be pending for the photo as well. + * + * @param Toolkit_Image_Server $is Image Server object + * @param Config_Container $c Member Configuration + * + * @return boolean false on error + * @access public + */ + public function remove(Toolkit_Image_Server $is, Config_Container $c) + { + try { + $is->imageDelete($this->image); + // Get rid of the photo in the member_photos table. + $sql = " + DELETE FROM {$this->tableName} + WHERE id = ?"; + + $stmt = $this->dbh->prepare($sql); + $stmt->execute(array($this->id)); + + $config = $c->getItem('section', 'tables'); + $pendingTable = $config->getItem('directive', 'pendingTable'); + + // Get rid of any updates to the photo so we don't have + // orphaned data lying around. + $sql = " + DELETE FROM {$pendingTable->getContent()} + WHERE db_table = '{$this->tableName}' + AND member_id = :member_id + AND foreign_key = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->bindParam(':id', $this->id, PDO::PARAM_INT); + return $stmt->execute(); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ setCaption() + + /** + * Set the caption for the photo + * + * @param string $caption new caption text + * + * @return boolean result of db update + * @access public + */ + public function setCaption($caption) + { + $this->caption = $caption; + try { + $sql = " + UPDATE {$this->tableName} + SET caption = ? + WHERE member_id = ? + AND id = ?"; + + $stmt = $this->dbh->prepare($sql); + return $stmt->execute(array($caption, $this->mid, $this->id)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setDbh() + + /** + * sets the database handler object + * + * using dependecy injection to help testing this application + * + * @param PDO $pdo PHP Data Object used for DB calls. + * + * @return void + * @access public + */ + public function setDbh(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + // {{{ setPending() + + /** + * Set the pending status for the photo + * + * @param boolean $pending If the photo is pending or not + * + * @return boolean result of db update + * @access public + */ + public function setPending($pending) + { + $this->pending = $pending; + try { + $sql = " + UPDATE {$this->tableName} + SET pending = ? + WHERE member_id = ? + AND id = ?"; + + $stmt = $this->dbh->prepare($sql); + return $stmt->execute(array($pending, $this->mid, $this->id)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setPendingData() + + /** + * Set the content of any data that might be pending + * + * Currently this only supports pending caption + * + * @param Config_Container $c Member configuration + * + * @return bolean false on error + * @access public + */ + public function setPendingData(Config_Container $c) + { + $config = $c->getItem('section', 'tables'); + $pendingTable = $config->getItem('directive', 'pendingTable'); + + try { + // Get any updates for that photo that are still in + // a pending status. + $sql = " + SELECT * + FROM {$pendingTable->getContent()} + WHERE id in ( + SELECT max(id) + FROM {$pendingTable->getContent()} + WHERE foreign_key = :foreign_key + AND db_table = 'member_photos' + GROUP BY field)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->execute(array($this->id)); + $row = $stmt->fetch(); + + if ($row['field'] == 'caption') { + $this->pendingCaption = $row['update']; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setPosition() + + /** + * Set a new position for a node + * + * Handle updating the nodes position in the linked list as well as db. + * + * @param integer $pos new position number for node + * + * @return boolean result of position update + * @access public + */ + public function setPosition($pos) + { + // Not updating anything so just return. + if ($pos == $this->pos) { + return true; + } + try { + $this->pos = $pos; + + $sql = " + UPDATE {$this->tableName} + SET pos = ? + WHERE member_id = ? + AND id = ?"; + + $stmt = $this->dbh->prepare($sql); + return $stmt->execute(array($pos, $this->mid, $this->id)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} +} +?> diff --git a/Toolkit/Members/ProfilePage.php b/Toolkit/Members/ProfilePage.php new file mode 100644 index 0000000..d74dd08 --- /dev/null +++ b/Toolkit/Members/ProfilePage.php @@ -0,0 +1,910 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: ProfilePage.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Generates Member profile pages + * + * Uses server side caching to increase page return speed. If a cache exists + * for a member the cache will be returned. If the member profile template + * has been changed after the cache file was written, all the cached + * profiles will be cleaned so they can be rewritten on the next pull + * using the new template. + * + * @category MemberDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version Release: @package_version@ + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_ProfilePage +{ + // {{{ properties + + /** + * Database handler + * @var object + * @access protected + */ + protected $dbh; + + /** + * Cache handler + * @var object + * @access protected + */ + protected $cache; + + /** + * Image Server + * @var object + * @access protected + */ + protected $is; + + /** + * Page catid + * @var integer + * @access private + */ + private $_catid; + + /** + * Member Id to get profile for + * @var integer + * @access private + */ + private $_mid; + + // }}} + // {{{ __construct() + + /** + * constructor + * + * @param PDO $pdo Database handler + * @param Toolkit_Image_Server $is Image Server Object + * @param integer $mid Member to get profile for + * + * @return void + * @access public + */ + public function __construct(PDO $pdo, Toolkit_Image_Server $is, $mid) + { + $this->dbh = $pdo; + $this->is = $is; + $this->setMemberId($mid); + } + + // }}} + + // {{{ _isNewMember() + + /** + * Determines if we are dealing w/ a new member from the addyourbusiness form + * + * @return boolean + * @access private + */ + private function _isNewMember() + { + try { + $sql = " + SELECT new_member + FROM member + WHERE member_id = :mid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('new_member', $isNew); + $stmt->fetch(); + + return (bool) $isNew; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ isTemplateNewer() + + /** + * Check to see if a template has been updated after a cache file + * + * @param string $tpl path to template file + * @param string $cache path to cache file + * + * @return boolean If template mod time is lte cache mod time + * @access protected + */ + protected function isTemplateNewer($tpl, $cache) + { + // If the cache profile exists + if (file_exists($cache)) { + // if the template was modified after the cache was written + // mod time will be greater + return (filemtime($cache) <= filemtime($tpl)); + } + } + + // }}} + + // {{{ getImageServer() + + /** + * Returns the Image Server set for the class + * + * @return mixed Image Server if set, otherwise false + * @access protected + */ + protected function getImageServer() + { + return is_object($this->is) ? $this->is : false; + } + + // }}} + + // {{{ memberActive() + + /** + * Check to make sure the member is active in the DB. + * + * @return boolean true or false if the member is active + * @access private + */ + private function _memberActive() + { + if (!ctype_digit((string) $this->_mid)) { + return false; + } + + try { + $sql = " + SELECT CASE + WHEN active THEN 1 + ELSE 0 + END AS active + FROM member + WHERE member_id = :member_id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('active', $active); + $stmt->fetch(); + + return (bool) $active; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ memberExists() + + /** + * Check to make sure the member exists in the database + * + * @return boolean true or false if the member exists + * @access private + */ + private function _memberExists() + { + if (!ctype_digit((string) $this->_mid)) { + return false; + } + + try { + $sql = " + SELECT count(*) AS total + FROM member + WHERE member_id = :member_id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':member_id', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('total', $total); + $stmt->fetch(); + + return (bool) $total; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ setCatId() + + /** + * Set the catid for the page + * + * @param integer $catid page id from db + * + * @return void + * @access public + * @throws PEAR Error on invalid member id + */ + public function setCatId($catid) + { + if (is_numeric($catid) && ctype_digit((string) $catid)) { + $this->_catid = $catid; + } else { + $this->_catid = null; + throw new PEAR_Exception('Invalid catid'); + } + } + + // }}} + // {{{ setConfig() + + /** + * Sets the query to use to fetch the datagrid results + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function setConfig(Config_Container $c) + { + $this->config = $c; + } + + // }}} + // {{{ setMemberAccommodations() + + /** + * Get all the member accommodation info + * + * @param object &$page The object you want to use with the flexy template + * + * @return void + * @access protected + */ + protected function setMemberAccommodations(&$page) + { + try { + // Check to see if there are any rows in the + // member_accommodations table that are linked to this + // member. If there are, then we know this member + // needs the hotel section + $sql = " + SELECT reservation_id, num_rooms, year_round + FROM member_accommodations + WHERE member_id = :mid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + + if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $accommodations = array_filter($row); + } + + $page->has_accommodations = !empty($accommodations); + $page->does_online_reservations = !is_null($accommodations['reservation_id']); + $page->reservation_id = $accommodations['reservation_id']; + $page->lists_number_of_rooms = !is_null($accommodations['num_rooms']); + $page->num_rooms = $accommodations['num_rooms']; + $page->year_round = $accommodations['year_round']; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setMemberAmenities() + + /** + * Get all the member amenity info + * + * @param object &$page The object you want to use with the flexy template + * + * @return void + * @access protected + */ + protected function setMemberAmenities(&$page) + { + try { + $sql = " + SELECT * + FROM amenity + WHERE amenity_id in ( + SELECT amenity_id + FROM member_amenity + WHERE member_id = :mid)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch()) { + $page->amenities[] = $row['amenity_name']; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setMemberCCards() + + /** + * Get all the member Credit Card info + * + * @param object &$page The object you want to use with the flexy template + * + * @return void + * @access protected + */ + protected function setMemberCCards(&$page) + { + try { + $sql = " + SELECT * + FROM ccard_type + WHERE ccard_type_id in ( + SELECT ccard_type_id + FROM member_ccard_type + WHERE member_id = :mid)"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch()) { + $page->ccards[] = $row['ccard_type_name']; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setMemberDetail() + + /** + * Get the member profile page + * + * @param object &$page controller object that will be used with + * the template + * @param string $imagePath URI path to use with image server for target + * images + * + * @return string html string of member profile page + * @access public + */ + public function setMemberDetail(stdClass &$page, $imagePath) + { + if (!$this->_validMember()) { + return false; + } + + // track member exposure report as detail page + //$exposure = new Toolkit_Members_Exposure($this->_mid, 'detail'); + + $page->image_path = $imagePath; + $page->base_url = BASE_URL; + + $this->setMemberInfo($page); + $this->setMemberPhotos($page); + $this->setMemberAccommodations($page); + $this->setMemberAmenities($page); + $this->setMemberCCards($page); + $this->setMemberSocialMedia($page); + $this->setMemberFiles($page); + $this->setMemberPackages($page); + $this->setMemberGolf($page); + $this->setMemberRestaurant($page); + + $page->show_attributes = ($page->has_accommodations || + $page->has_social_media || + is_array($page->ccards)); + return true; + } + + // }}} + // {{{ setMemberFiles() + + /** + * Get all the file data for the the member profile being looked at + * + * @param object &$page The object you want to use with the flexy template + * + * @return void + * @access protected + */ + protected function setMemberFiles(&$page) + { + try { + $sql = " + SELECT * + FROM member_files + WHERE member_id = :mid + AND NOT pending"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + + $count = 0; + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $page->files[$count]['href'] = BASE_URL . "member-file/$mid/{$row['id']}/"; + $page->files[$count]['name'] = empty($row['file_name']) ? + $row['original_name'] : + $row['file_name']; + ++$count; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setMemberGolf() + + /** + * Get all the golf data for the the member profile being looked at + * + * @param object &$page The object you want to use with the flexy template + * + * @return void + * @access protected + */ + protected function setMemberGolf(&$page) + { + try { + $sql = " + SELECT column_name, data_type + FROM information_schema.columns + WHERE table_name = 'member_golf'"; + + $tableData = $this->dbh->query($sql)->fetchAll(); + + $sql = " + SELECT * + FROM member_golf + WHERE member_id = :mid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + + if ($row = $stmt->fetch()) { + $show = false; + foreach ($tableData as $td) { + switch ($td['data_type']) { + case 'radio' : + case 'boolean' : + $golf[$td['column_name']] = ($row[$td['column_name']] == 't') ? 'Yes': 'No'; + break; + + case 'integer' : + break; + + case 'text' : + default : + $golf[$td['column_name']] = $row[$td['column_name']]; + if (!empty($row[$td['column_name']])) { + $show = true; + } + break; + } + } + + $page->golf_info = $show; + $page->par = $golf['par']; + $page->yardage = $golf['yardage']; + $page->course_rating = $golf['course_rating']; + $page->slope_rating = $golf['slope_rating']; + $page->walking_course = $golf['walking_course']; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setMemberId() + + /** + * Set a new member id + * + * @param integer $mid member id to set + * + * @return void + * @access public + * @throws PEAR Error on invalid member id + */ + public function setMemberId($mid) + { + if (is_numeric($mid) && ctype_digit((string) $mid)) { + $this->_mid = $mid; + } else { + $this->_mid = null; + throw new PEAR_Exception('Invalid Member Id'); + } + } + + // }}} + // {{{ setMemberInfo() + + /** + * Set the record data stored in the database for the template + * + * @param object &$page The object you want to use with the flexy template + * + * @return void + * @access protected + */ + protected function setMemberInfo(&$page) + { + try { + $sql = " + SELECT m.*, c.city_name, s.state_name, + s.state_abb AS state_abbr + FROM member m JOIN city c USING (city_id), state s + WHERE m.member_id = :mid + AND m.state_id = s.state_id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(); + + if (!empty($row['logo'])) { + $page->logo = $row['logo']; + if ($is = $this->getImageServer()) { + $img = $page->image_path . $row['logo']; + list($w, $h, ) = $is->getImageSize($img); + $page->logo_width = $w; + $page->logo_height = $h; + } + } + + $page->member_name = $row['member_name']; + $page->street = $row['street']; + // get reference to [listing type] section of config file + $config =& $this->config->getItem('section', 'conf'); + $ctrlCtyD =& $config->getItem('directive', 'controlledCities'); + if ($ctrlCtyD->getContent()) { + $page->city = $row['city_name']; + } else { + $page->city = $row['city']; + } + $page->state_name = $row['state_name']; + $page->state_abbr = $row['state_abbr']; + $page->zip = $row['zip']; + $page->phone = $row['phone']; + $page->toll_free = $row['toll_free']; + $page->fax = $row['fax']; + $page->email = $row['member_contact_email']; + + // this needs to goto memberClick.php page first for tracking + // of the member clicked url's + if ($row['url']) { + $page->url = BASE_URL . 'Toolkit/Members/memberClickThru.php?member_id=' . + $this->_mid . '&href=' . urlencode(str_replace('http://', '', $row['url'])); + } + + if (!empty($row['lat']) && !empty($row['lon'])) { + $fromAddress = trim(urlencode(str_replace("\n", "", strip_tags($row['member_name'])))); + $fromAddress .= "@{$row['lat']},{$row['lon']}"; + } else { + $fromAddress = trim(urlencode(str_replace("\n", "", strip_tags($row['street'])))) + .','.trim(urlencode(str_replace("\n", "", strip_tags($row['city'])))) + .','.trim(urlencode(str_replace("\n", "", strip_tags($row['state_name'])))); + } + + $page->daddr = $fromAddress; + $page->description = $row['description']; + + if (defined("MEMBER_SESSION_LIST") && MEMBER_SESSION_LIST) { + if ($_SESSION['wish_list'][$this->_mid]) { + $page->addToLink = false; + } else { + $page->addToLink = true; + } + $page->plink = BASE_URL . "Toolkit/Members/TripPlanner/" . + "wish-list.php?catid={$this->_catid}&member_id={$row['member_id']}&detail=1"; + } else { + $page->plink = null; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setMemberPackages() + + /** + * Get all the file data for the the member profile being looked at + * + * @param object &$page The object you want to use with the flexy template + * + * @return void + * @access protected + */ + protected function setMemberPackages(&$page) + { + try { + $sql = " + SELECT title, description, image + FROM member_packages + WHERE member_id = :mid + AND NOT pending + AND CURRENT_DATE BETWEEN sdate AND edate + ORDER BY id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + + $count = 0; + $is = $this->getImageServer(); + while ($row = $stmt->fetch()) { + $page->packages[$count]['title'] = $row['title']; + if (!empty($row['image'])) { + $img = $page->image_path . $row['image']; + $page->packages[$count]['image'] = $img; + if ($is) { + list($w, $h, ) = $is->getImageSize($img); + $page->packages[$count]['w'] = $w; + $page->packages[$count]['h'] = $h; + } + } + if (!empty($row['description'])) { + $page->packages[$count]['description'] = $row['description']; + } + ++$count; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setMemberPhotos() + + /** + * set all the non-pending photos that a member has + * + * @param object &$page The object you want to use with the flexy template + * + * @return void + * @access protected + */ + protected function setMemberPhotos(&$page) + { + try { + $sql = " + SELECT * + FROM member_photos + WHERE member_id = :mid + AND (NOT pending OR pending IS NULL) + ORDER BY pos"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + + $count = 0; + $is = $this->getImageServer(); + while ($row = $stmt->fetch()) { + $images[$count]['alt'] = $row['caption']; + $images[$count]['id'] = PHOTO_LARGE_URL . $row['image']; + $images[$count]['src'] = PHOTO_SMALL_URL . $row['image']; + $images[$count]['img'] = $row['image']; + if ($is) { + list($w, $h, ) = $is->getImageSize(PHOTO_SMALL_URL . $row['image']); + $images[$count]['w'] = $w; + $images[$count]['h'] = $h; + } + ++$count; + } + + $page->photos = !empty($images) ? $images : false; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setMemberRestaurant() + + /** + * Get all the restaurant data for the the member profile being looked at + * + * @param object &$page The object you want to use with the flexy template + * + * @return void + * @access protected + */ + protected function setMemberRestaurant(&$page) + { + try { + $sql = " + SELECT column_name, data_type + FROM information_schema.columns + WHERE table_name = 'member_restaurants'"; + + $tableData = $this->dbh->query($sql)->fetchAll(); + + $sql = " + SELECT * + FROM member_restaurants + WHERE member_id = :mid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $mid, PDO::PARAM_INT); + $stmt->execute(); + + if ($row = $stmt->fetch()) { + $show = false; + foreach ($tableData as $td) { + switch ($td['data_type']) { + case 'radio' : + case 'boolean' : + $restaurant[$td['column_name']] + = ($row[$td['column_name']] == 't') ? 'Yes': 'No'; + if ($row[$td['column_name']] == 't') { + $show = true; + } + break; + + default : + $restaurant[$td['column_name']] = $row[$td['column_name']]; + break; + } + } + + $page->restaurant_info = $show; + $page->breakfast = $restaurant['breakfast']; + $page->brunch = $restaurant['brunch']; + $page->lunch = $restaurant['lunch']; + $page->dinner = $restaurant['dinner']; + $page->alcohol = $restaurant['alcohol']; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setMemberSocialMedia() + + /** + * Gets all the members social media links + * + * @param object &$page The object you want to use with the flexy template + * + * @return mixed array if the member has any links otherwise false + * @access protected + */ + protected function setMemberSocialMedia(&$page) + { + try { + $sql = " + SELECT facebook, twitter, myspace, linkedin, blog + FROM member + WHERE member_id = :mid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mid', $this->_mid, PDO::PARAM_INT); + $stmt->execute(); + + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $media = array_filter($row); + + if (!empty($media)) { + $page->has_social_media = true; + foreach ($media as $k => $v) { + $page->$k = $v; + } + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ toHtml() + + /** + * Get a profile page for a member + * + * @param HTML_Template_Flexy $tpl Flexy template object + * @param Cache_Lite $cache Cache object + * @param string $imagePath Image Server URI to image + * @param boolean $exitOnError exit the script when an error + * is encountered + * + * @return string HTML page of a members profile + * @access public + */ + public function toHtml( + HTML_Template_Flexy $tpl, + Cache_Lite $cache, + $imagePath, + $exitOnError = true + ) { + // profile cache name + $profileCache = "Member-{$this->_mid}"; + // get the profile cache if it exists + $out = $cache->get($profileCache, 'Profile'); + // template file to check + $template = BASE . 'Toolkit/Members/templates/memberDetail.tpl'; + // cache file to check + $cacheFile = BASE . "Toolkit/Members/cache/cache_Profile_$profileCache"; + + if ($this->isTemplateNewer($template, $cacheFile)) { + $cache->clean('Profile'); + $out = false; + } + + if (!$out) { + $page = new stdClass(); + if ($this->setMemberDetail($page, $imagePath)) { + $tpl->compile('memberDetail.tpl'); + $out = $tpl->bufferedOutputObject($page); + } + + if ($out === false) { + include_once BASE . '404.html'; + if ($exitOnError) { + exit(); + } + } else { + $cache->save($out); + } + } + + return $out; + } + + // }}} + + // {{{ _validMember() + + /** + * Verify the member if valid + * + * check that the member exists in the DB and that they are active + * + * @return boolean true if valid, false if not + * @access private + */ + private function _validMember() + { + if ( !$this->_memberExists() + || !$this->_memberActive() + || $this->_isNewMember() + ) { + return false; + } + + return true; + } + + // }}} +} +?> diff --git a/Toolkit/Members/RecordNavigation.php b/Toolkit/Members/RecordNavigation.php new file mode 100644 index 0000000..5fc1dde --- /dev/null +++ b/Toolkit/Members/RecordNavigation.php @@ -0,0 +1,207 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: RecordNavigation.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Base class for the memberdb + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_RecordNavigation +{ + // {{{ __construct() + + /** + * Constructor + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function __construct(Config_Container $c) + { + $this->config = $c; + } + + // }}} + // {{{ getPageNav() + + /** + * Render the page navigation that is defined in the navStructure + * + * @return string Page navigation structure + * @access public + */ + public function getPageNav() + { + $menu =& new HTML_Menu($this->navStructure, 'rows'); + $menu->forceCurrentIndex($_GET['tab']); + + $renderer =& new HTML_Menu_DirectRenderer($tpl); + $renderer->setEntryTemplate(HTML_MENU_ENTRY_INACTIVE, '
  • {Title}
  • '); + $renderer->setEntryTemplate(HTML_MENU_ENTRY_ACTIVE, '
  • {Title}
  • '); + $renderer->setEntryTemplate(HTML_MENU_ENTRY_ACTIVEPATH, '
  • {Title}
  • '); + $renderer->setMenuTemplate('', ''); + $renderer->setRowTemplate('
      ', '
    '); + + $menu->render($renderer); + return $renderer->toHtml(); + } + + // }}} + + // {{{ setupAdminNavStructure() + + /** + * Sets up a multi dimensional array used for the subnav structure + * + * @return mixed false on sql error. otherwise void + * @access public + */ + public function setupAdminNavStructure() + { + // get reference to [listing type] section of config file + $config =& $this->config->getItem('section', 'listing type'); + // get coupon + $singularDirective =& $config->getItem('directive', 'singular'); + $singularType = $singularDirective->getContent(); + $pluralDirective =& $config->getItem('directive', 'plural'); + $pluralType = $pluralDirective->getContent(); + + // Default URI parameters that will get us back to the + // page were we can edit member data. + $params = "cat=2&subCat=2"; + + // If we are editing an existing member, then we need to + // add their id into the URI so we know who we are editing + if (is_numeric($_GET['id'])) { + $params .= "&id={$_GET['id']}"; + } + + // We always show the member info tab. + // whether we are adding a member or editing a member + $nav = array( + 1 => array( + 'Title' => "$singularType Info", + 'url' => "/members.php?$params", + 'desc' => "View and edit $singularType in the database", + ) + ); + if (is_numeric($_GET['id'])) { + $nav[2] = array( + 'Title' => 'Photos', + 'url' => "/members.php?$params", + 'desc' => "View and edit $pluralType in the database", + ); + $nav[3] = array( + 'Title' => 'Packages', + 'url' => "/members.php?$params", + 'desc' => "View and edit $singularType categories", + ); + $nav[4] = array( + 'Title' => 'Amenities', + 'url' => "/members.php?$params", + 'desc' => "View and edit $singularType amenities", + ); + $nav[5] = array( + 'Title' => 'Files', + 'url' => "/members.php?$params", + 'desc' => "View and edit $singularType regions", + ); + $nav[6] = array( + 'Title' => 'Contacts', + 'url' => "/members.php?$params", + 'desc' => "View and edit $singularType cities", + ); + } + + // make full URI's and attach which tab we are working with + foreach ($nav as $i => &$j) { + $j['url'] = BASE_URL . 'admin' . $j['url'] . "&tab=$i"; + } + + $this->navStructure = $nav; + } + + // }}} + // {{{ setupUserNavSructure() + + /** + * Sets up a multi dimensional array used for the subnav structure + * + * @return mixed false on sql error. otherwise void + * @access public + */ + public function setupUserNavStructure() + { + // get reference to [listing type] section of config file + $config =& $this->config->getItem('section', 'listing type'); + // get coupon + $singularDirective =& $config->getItem('directive', 'singular'); + $singularType = $singularDirective->getContent(); + $pluralDirective =& $config->getItem('directive', 'plural'); + $pluralType = $pluralDirective->getContent(); + + $params = "Option=Member&Action=Edit"; + $nav = array( + 1 => array( + 'Title' => "$singularType Info", + 'url' => "/index.php?$params", + 'desc' => "View and edit $singularType in the database", + ), + 2 => array( + 'Title' => 'Photos', + 'url' => "/index.php?$params", + 'desc' => "View and edit $pluralType in the database", + ), + 3 => array( + 'Title' => 'Packages', + 'url' => "/index.php?$params", + 'desc' => "View and edit $singularType categories", + ), + 4 => array( + 'Title' => 'Amenities', + 'url' => "/index.php?$params", + 'desc' => "View and edit $singularType amenities", + ), + 5 => array( + 'Title' => 'Files', + 'url' => "/index.php?$params", + 'desc' => "View and edit $singularType regions", + ), + 6 => array( + 'Title' => 'Contacts', + 'url' => "/index.php?$params", + 'desc' => "View and edit $singularType cities", + ), + ); + + // make full URI's and attach which tab we are working with + foreach ($nav as $i => &$j) { + $j['url'] = BASE_URL . 'memberdb' . $j['url'] . "&tab=$i"; + } + + $this->navStructure = $nav; + } + + // }}} +} +?> diff --git a/Toolkit/Members/SearchList.php b/Toolkit/Members/SearchList.php new file mode 100644 index 0000000..bec68dd --- /dev/null +++ b/Toolkit/Members/SearchList.php @@ -0,0 +1,728 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @release CVS: $Id: SearchList.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +require_once 'FlexyDataGridBuilder.php'; +require_once 'Members/UserSearchForm.php'; +require_once 'Members/Exposure.php'; +require_once 'Common.php'; +require_once 'HTML/QuickForm/Renderer/Object.php'; + +/** + * Datagrid of search results of member db + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_SearchList extends Toolkit_FlexyDataGridBuilder +{ + // {{{ properties + + /** + * Description for protected + * @var string + * @access protected + */ + protected $tableName = 'member'; + + /** + * Description for protected + * @var array + * @access protected + */ + protected $queryParams = array(); + + /** + * Description for protected + * @var unknown + * @access protected + */ + protected $showSearchBox; + + /** + * Description for protected + * @var string + * @access protected + */ + protected $template = 'membersList.tpl'; + + /** + * Whether subcats should be included in the search results + * + * If this is turned on, the subcategories beneath all categories assigned + * to the page will be included in the search results. + * + * Example Category Tree: + * + * Parent + * |_ Child + * | |_ GrandChild + * | + * |_ Sibling + * + * If set to true and only "Parent" is assigned to a page from the toolbox, + * then members with all categories (parent, child, grandchild, sibling) will + * be included in the search results. + * + * If set to false and only Child is assigned to a page, then only members + * that have the category "Child" assigned to them will be included in the + * search Results. + * + * @var boolean + * @access protected + */ + protected $includeSubCats = true; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * define where templates for the data grid are at, then call the parent constructor which will handle + * finishing the settings for the datagrid. + * + * After all settings are finished you can call the toHTML() function on this object and the datagrid + * will be rendered and returned as a string. Optionally you could call show() and the datagrid would + * be rendered and output immediatley to the screen. + * + * @param PDO $pdo PHP Data Object to use for DB calls + * @param string $limit The number of records to display per page. + * @param int $page The current page viewed. + * In most cases, this is useless. + * Note: if you specify this, the "page" GET + * variable will be ignored. + * @param string $rendererType The type of renderer to use. + * You may prefer to use the $type argument + * of {@link render}, {@link fill} or + * {@link getOutput} + * @param boolean $showSearchBox If we should allow searching for members + * @param array $sections specific members we should show + * + * @return void + * @access public + */ + public function __construct( + PDO $pdo, + $limit = null, + $page = null, + $rendererType = null, + $showSearchBox = true, + array $sections = null + ) { + $this->showSearchBox = $showSearchBox; + $this->pagerOptions['containerClass'] = 'pages'; + parent::__construct($pdo, $limit, $page, $rendererType); + } + + // }}} + + // {{{ city() + + /** + * Returns the city for a member. + * + * If this memberdb is using controlled cities then we need to extract + * the city name via the city_id + * + * @param array $data tuple record from db + * + * @return string City name for the record + * @access public + */ + public function city($data) + { + // get reference to [conf] section of config file + $config =& $this->config->getItem('section', 'conf'); + $ctrlCtyD =& $config->getItem('directive', 'controlledCities'); + if ($ctrlCtyD->getContent()) { + return $data['record']['city_name']; + } else { + return $data['record']['city']; + } + } + + // }}} + // {{{ configureColumns() + + /** + * Configures the columns that will be used in our datagrid renderer. + * + * @return void + * @access protected + */ + protected function configureColumns() + { + $logo =& new Structures_DataGrid_Column('Logo', + 'logo', + 'logo', + null, + null, + array(&$this, 'logo')); + $this->addColumn($logo); + + $name =& new Structures_DataGrid_Column('Member Name', + 'member_name', + 'member_name'); + $this->addColumn($name); + + $street =& new Structures_DataGrid_Column('Street', + 'street', + 'street'); + $this->addColumn($street); + + $city =& new Structures_DataGrid_Column('City', + 'city', + 'city', + null, + null, + array(&$this, 'city')); + $this->addColumn($city); + + $state =& new Structures_DataGrid_Column('State', + 'state', + 'state'); + $this->addColumn($state); + + $stateAbbr =& new Structures_DataGrid_Column('State Abbr', + 'state_abbr', + 'state_abbr'); + $this->addColumn($stateAbbr); + + $zip =& new Structures_DataGrid_Column('Zip', + 'zip', + 'zip'); + $this->addColumn($zip); + + $phone =& new Structures_DataGrid_Column('Phone', + 'phone', + 'phone', + null, + null, + array(&$this, 'phone')); + $this->addColumn($phone); + + $url =& new Structures_DataGrid_Column('URL', + 'url', + 'url', + null, + null, + array(&$this, 'url')); + $this->addColumn($url); + + $reservationId =& new Structures_DataGrid_Column('Reservation Id', + 'reservation_id', + 'reservation_id'); + $this->addColumn($reservationId); + + $numRooms =& new Structures_DataGrid_Column('Number of Rooms', + 'num_rooms', + 'num_rooms'); + $this->addColumn($numRooms); + + $yearRound =& new Structures_DataGrid_Column('Year Round', + 'year_round', + 'year_round', + null, + null, + array(&$this, 'yearRound')); + $this->addColumn($yearRound); + + $hasHotelInfo =& new Structures_DataGrid_Column(null, + 'has_hotel_info', + 'has_hotel_info', + null, + null, + array(&$this, 'hasHotelInfo')); + $this->addColumn($hasHotelInfo); + + if (defined("MEMBER_SESSION_LIST") && MEMBER_SESSION_LIST) { + $link =& new Structures_DataGrid_Column('URL', + 'plink', + 'plink', + null, + null, + array(&$this, 'listUrl')); + $this->addColumn($link); + } + + $link =& new Structures_DataGrid_Column('addToLink', + 'addToLink', + 'addToLink', + null, + null, + array(&$this, 'inList')); + $this->addColumn($link); + } + + // }}} + + // {{{ getAlphaList() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return array Return description (if any) ... + * @access protected + */ + protected function getAlphaList() + { + $pattern = "/ (\s*?AND\s*?)?upper\(substr\(m.member_name, 1, 1\)\) = upper\('.'\)/i"; + $replacement = ''; + $sql = preg_replace($pattern, $replacement, $this->sql); + try { + $letters = array(); + $stmt = $this->dbh->prepare($sql); + $stmt->execute(); + + $stmt->bindColumn('member_name', $name); + + while ($row = $stmt->fetch()) { + $letters[] = strtoupper($name{0}); + } + + $letters = array_unique($letters); + sort($letters); + + // We only need to show the links of alphabet if we have more than + // one letter to display. + if (count($letters) > 1) { + foreach ($_GET as $k => $v) { + if ($k != 'alpha') { + if (is_array($v)) { + foreach ($v as $i => $j) { + $queryString .= $k . '[' . $i . ']=' . $j . '&'; + } + } else { + $queryString .= "$k=$v&"; + } + } + } + $links['All']['url'] = BASE_URL . "index.php?{$queryString}"; + $links['All']['class'] = empty($_GET['alpha']) ? 'curr' : null; + foreach ($letters as $v) { + $links[$v]['url'] = BASE_URL . "index.php?{$queryString}alpha=$v"; + if ($_GET['alpha'] == $v) { + $links[$v]['class'] = 'curr'; + } + } + return $links; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ _getMemberCategoriesForPage() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return mixed Return description (if any) ... + * @access private + */ + private function _getMemberCategoriesForPage() + { + try { + $memberCategories = array(); + $sql = " + SELECT memb_type + FROM bus_cat_member + WHERE catid = :catid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':catid', $_GET['catid'], PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('memb_type', $category); + + while ($row = $stmt->fetch()) { + $memberCategories[] = $category; + } + + // If we should include all the sub categories beneath a category. + if ($this->includeSubCats) { + // For each of the categories assigned to the page, + // we need to get all sub-categories. This way the user + // can assign a top level category as a balloon to cover all the + // subcategories w/out individually assigning them as well. + foreach ($memberCategories as $v) { + $catTree = Toolkit_Common::getHierarchicalTreeStructure( + 'category', + 'category_id', + 'parent_id', + 'pos', + $v + ); + + foreach ($catTree as $i => $j) { + $memberCategories[] = $i; + } + } + } + + return empty($memberCategories) ? false : $memberCategories; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ hasHotelInfo() + + /** + * Determines if the record has any available hotel info to display + * + * @param array $data record data + * + * @return boolean true if any data to display, otherwise false + * @access public + */ + public function hasHotelInfo($data) + { + extract($data['record']); + return !(empty($reservation_id) && empty($num_rooms) && empty($year_round)); + } + + // }}} + + // {{{ inList() + + /** + * Returns the bool for a member in session (list) + * + * Used when configuring the columns for the data grid. This + * function returns true or false if the member is in not session + * then true + * + * @param array $data tuple record from db + * + * @return boolean true if member is not in $_SESSION['wish_list'] + * @access public + */ + public function inList($data) + { + return !($_SESSION['wish_list'][$data['record']['member_id']]); + } + + // }}} + + // {{{ listUrl() + + /** + * Returns the url for a member. + * + * Used when configuring the columns for the data grid. This + * function generates the url to get to the member detail page + * + * @param array $data tuple record from db + * + * @access Public + * @version Release: @package_version@ + * @return url for the add to or remove from $_SESSION['wish_list'] + */ + public function listUrl($data) + { + if (defined("MEMBER_SESSION_LIST") && MEMBER_SESSION_LIST) { + $url = BASE_URL."Toolkit/Members/TripPlanner/wish-list.php?catid={$_GET['catid']}&member_id={$data['record']['member_id']}"; + $url .= ($_REQUEST['search']) ? "&search=" . $_REQUEST['search'] :''; + $url .= ($_REQUEST['member_name']) ? "&member_name=" . urlencode($_REQUEST['member_name']) :''; + $url .= ($_REQUEST['category_id']) ? "&category_id=" . $_REQUEST['category_id'] :''; + $url .= ($_REQUEST['sub_category_id']) ? "&sub_category_id=" . $_REQUEST['sub_category_id'] :''; + } else { + $url = false; + } + return $url; + } + + // }}} + // {{{ logo() + + /** + * Returns the logo for a member. + * + * @param array $data tuple record from db + * + * @return false when empty, otherwise logo path for member + * @access + */ + public function logo($data) + { + extract($data['record']); + return empty($logo) ? false : MEMBER_PHOTOS . $logo; + } + + // }}} + + // {{{ phone() + + /** + * Returns the phone # for a member. + * + * Used when configuring the columns for the data grid. This + * function generates the phone for the member + * + * @param array $data tuple record from db + * + * @return mixed false when empty, member phone number if not empty + * @access public + */ + public function phone($data) + { + extract($data['record']); + return empty($phone) ? false : $phone; + } + + // }}} + + // {{{ setConfig() + + /** + * Sets the query to use to fetch the datagrid results + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function setConfig(Config_Container $c) + { + $this->config = $c; + } + + // }}} + // {{{ setControlObject() + + /** + * These are the objects that will be inserted into the template. + * + * @return void + * @access protected + */ + protected function setControlObject() + { + $this->ctrlObj['base_url'] = BASE_URL; + $this->ctrlObj['letters'] = $this->getAlphaList(); + + if (isset($_GET['search']) && $this->showSearchBox) { + $action = BASE_URL . "index.php?{$_SERVER['QUERY_STRING']}"; + $form = new Toolkit_Members_UserSearchForm($this->dbh, + 'SearchForm', + 'get', + $action, + null, + null, + true); + $res = $form->setCatId($_GET['catid']); + if (PEAR::isError($res)) { + return Toolkit_Common::handleError($res); + } else { + $form->setPageMemberCategories(); + $form->configureForm($this->config); + $this->ctrlObj['member_search_form'] = $form->toHtml(); + } + } + } + + // }}} + // {{{ setQuery() + + /** + * Sets the query to use to fetch the datagrid results + * + * @return void + * @access public + */ + public function setQuery() + { + $sql = " + SELECT m.*, c.city_name, s.state_name AS state, s.state_abb + AS state_abbr, ma.reservation_id, ma.num_rooms, + ma.year_round + FROM {$this->tableName} m + NATURAL LEFT JOIN member_accommodations ma + JOIN state s ON m.state_id = s.state_id + JOIN city c ON m.city_id = c.city_id"; + + $this->queryParams = array("new_member != '1'", "active = '1'"); + + // Limit to members whose first letter starts with the letter + // a user clicked in the sort alphabetically list. + if (ctype_alpha($_GET['alpha'])) { + $this->queryParams[] = "upper(substr(m.member_name, 1, 1)) = upper('{$_GET['alpha']}')"; + } + + // Limit to members whose name contains the string a user + // entered into the member name box. + if (!empty($_GET['member_name'])) { + $this->queryParams[] = "member_name ilike '%{$_GET['member_name']}%'"; + } + + // Using controlled cities and a search was performed on a city + // get reference to [conf] section of config file + $config =& $this->config->getItem('section', 'conf'); + $ctrlCtyD =& $config->getItem('directive', 'controlledCities'); + if ($ctrlCtyD->getContent()) { + if (ctype_digit($_GET['city_id'])) { + $this->queryParams[] = "c.city_id = {$_GET['city_id']}"; + } + } + + // Limit to members who have the category assigned to them + // that a user selected from the member type box. + if (ctype_digit($_GET['sub_category_id'])) { + $this->queryParams[] = " + m.member_id IN ( + SELECT member_id + FROM member_category + WHERE category_id = {$_GET['sub_category_id']})"; + } else if (ctype_digit($_GET['category_id'])) { + unset($subCats); + if ($this->includeSubCats) { + // Members who are assigned specifically to this category + // OR + // Members who have a category assigned to them that is a child + // of the parent category. + $catTree = Toolkit_Common::getHierarchicalTreeStructure( + 'category', + 'category_id', + 'parent_id', + 'pos', + $_GET['category_id'] + ); + + if (!empty($catTree)) { + $subCats = " + OR category_id IN (".implode(', ', array_keys($catTree)).")"; + } + } + $this->queryParams[] = " + m.member_id IN ( + SELECT member_id + FROM member_category + WHERE category_id = {$_GET['category_id']} + $subCats)"; + } elseif ($categories = $this->_getMemberCategoriesForPage()) { + $this->queryParams[] = ' + m.member_id in ( + SELECT member_id + FROM member_category + WHERE category_id in ('.implode(', ', $categories).'))'; + } + + // Limit to members who have the amenities that a user + // checked off. + if (!empty($_GET['amenities'])) { + if (isset($_GET['search_all_amenity'])) { + // Member must have ALL of the selected amenities. + foreach ($_GET['amenities'] as $k => $v) { + if (ctype_digit($k)) { + $innerSql[] = " + SELECT member_id + FROM member_amenity + WHERE amenity_id = $k"; + } + } + + $innerSql = implode(' INTERSECT ', $innerSql); + $innerSql = "m.member_id in ($innerSql)"; + + $this->queryParams[] = $innerSql; + } else { + // Member can have ANY of the selected amenities + $this->queryParams[] = " + member_id in ( + SELECT member_id + FROM member_amenity + WHERE amenity_id in(".implode(', ', array_keys($_GET['amenities']))."))"; + } + } + + if (!is_null($sections)) { + foreach ($sections as $v) { + switch ($v) { + case 'packages' : + $this->queryParams[] = " + member_id IN ( + SELECT member_id + FROM member_packages)"; + break; + + default : + break; + } + } + } + + if (!empty($this->queryParams)) { + $sql .= ' WHERE ' . implode(' AND ', $this->queryParams); + } + + parent::setQuery($sql); + } + + // }}} + + // {{{ url() + + /** + * Returns the url for a member. + * + * Used when configuring the columns for the data grid. This + * function generates the url to get to the member detail page + * + * @param array $data tuple record from db + * + * @return string uri for exposure record + * @access public + */ + public function url($data) + { + $exposure = new Toolkit_Members_Exposure($data['record']['member_id'], 'list'); + return "index.php?catid={$_GET['catid']}&member_id={$data['record']['member_id']}"; + } + + // }}} + + // {{{ yearRound() + + /** + * Returns the year round for a member w/ accommodations. + * + * Used when configuring the columns for the data grid. This + * function generates the year round for the member detail page + * + * @param array $data tuple record from db + * + * @return string if the accommodations is offered year round + * @access public + */ + public function yearRound($data) + { + return ($data['record']['year_round'] == 't') ? 'Yes' : 'No'; + } + + // }}} +} +?> diff --git a/Toolkit/Members/TripPlanner/Sessions.php b/Toolkit/Members/TripPlanner/Sessions.php new file mode 100644 index 0000000..99fd319 --- /dev/null +++ b/Toolkit/Members/TripPlanner/Sessions.php @@ -0,0 +1,290 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: Sessions.php,v 1.2 2009/12/15 20:18:15 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Members_TripPlanner_Sessions + * + * Trying to place all the code for the storing of the member list to session + * into one place + * Takes the $_SESSION['wish_list'] used for the trip planner and + * add or removes members and their page id to the session + * if they're logged in with trip planner then they'll get everything saved to the + * database table member_session + * + * @category MembersDB + * @package Toolkit_Members + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version Release: @package_version@ + * @link <> + */ +class Toolkit_Members_TripPlanner_Sessions +{ + // {{{ Properties + /** + * Global PDO + * @var object + * @access protected + */ + public $dbh; + + /** + * Auth object + * @var object + * @access protected + */ + protected $auth; + + /** + * $_SESSION['wish_list'] + * @var array + * @access protected + */ + protected $session; + + // }}} + // {{{ __construct() + + /** + * Set the Auth object ad Global PDO + * + * @param integer $pdo Global pdo + * @param integer $Auth current Auth object used for valid session + * + * @return void + * @access public + */ + function __construct($pdo, Auth $Auth) + { + $this->dbh =& $pdo; + $this->auth =& $Auth; + $this->session =& $_SESSION['wish_list']; + } + + // }}} + // {{{ addRecord() + + /** + * Add the record into session storing the page it was added on. + * page shold always have the catid. + * If the user is logged in then store it in database with contact_id + * + * @param unknown $memberId member_id of record + * @param unknown $catId page catid + * + * @return void + * @access public + */ + function addRecord($memberId, $catId) + { + // add to the session the member record + $this->session[$memberId] = array( + 'catid' => $catId + ); + if ($this->isLoggedIn()) { + $cData = $this->auth->getAuthData(); + try { + $sql = " + INSERT INTO member_session + (contact_id, member_id, catid) + VALUES + (:contact_id, :member_id, :catid)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":member_id", $memberId, PDO::PARAM_INT); + $stmt->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT); + $stmt->bindParam(":catid", $catId, PDO::PARAM_INT); + $stmt->execute(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + } + + // }}} + // {{{ dumpList() + + /** + * Dump the session for the list and + * if they are logged in then remove their list in the + * database. + * + * @return void + * @access public + */ + function dumpList() + { + if ($this->isLoggedIn()) { + $cData = $this->auth->getAuthData(); + $sql = " + DELETE + FROM member_session + WHERE contact_id = :contact_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT); + $stmt->execute(); + } + unset($this->session); + unset($_SESSION['wish_list']); + session_unregister('wish_list'); + } + + // }}} + // {{{ isLoggedIn() + + /** + * Check the Auth object function checkAuth to see if the user has a valid + * login session. If so then return true. If not then return false. + * + * @return boolean true valid login false invalid login + * @access public + */ + function isLoggedIn() + { + if ($this->auth->checkAuth()) { + return true; + } else { + return false; + } + } + + // }}} + // {{{ removeRecord() + + /** + * Remove the record from the session. If the user is logged in then + * also remove the data from the database. + * + * @param unknown $memberId member id for record + * + * @return void + * @access public + */ + function removeRecord($memberId) + { + unset($this->session[$memberId]); + if ($this->isLoggedIn()) { + $cData = $this->auth->getAuthData(); + //die('

    '.print_r($cData, true).'

    '); + try { + $sql = " + DELETE FROM member_session + WHERE member_id = :member_id + AND contact_id = :contact_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":member_id", $memberId, PDO::PARAM_INT); + $stmt->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT); + $stmt->execute(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + } + + // }}} + // {{{ retrieveList() + + /** + * Retreive the list form the database storage and repopulate the accounts data + * to the session var $this->session = $_SESSION['wish_list'] + * + * @return void + * @access public + */ + function retrieveList() + { + if ($this->isLoggedIn()) { + $cData = $this->auth->getAuthData(); + try { + $sql = " + SELECT * + FROM member_session + WHERE contact_id = :contact_id"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch()) { + // don't dupe the list + if (!$this->session[$row['member_id']]) { + $this->session[$row['member_id']] = array( + 'catid' => $row['catid'] + ); + } + } + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + } + + // }}} + // {{{ saveList() + + /** + * Save the list for the user. This is called on the login page after the + * session is repopulated out from database. No worries about dupes here. + * this function checks for existing records then won't reinsert. + * + * @param int $contactId the id from contact table for lookup + * + * @return void + * @access public + */ + function saveList($contactId = null) + { + if ($this->isLoggedIn() && is_array($this->session)) { + if (isset($contactId) && is_numeric($contactId)) { + $cData['id'] = $contactId; + } else { + $cData = $this->auth->getAuthData(); + } + $sql = " + SELECT member_id + FROM member_session + WHERE contact_id = :contact_id"; + try { + $getDat = $this->dbh->prepare($sql); + $getDat->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT); + $getDat->execute(); + while ($row = $getDat->fetch()) { + $mStoreSess[$row['member_id']] = $row['member_id']; + } + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + foreach ($this->session as $memberId => $sData) { + if (!$mStoreSess[$memberId]) { + try { + $sql = " + INSERT INTO member_session + (contact_id, member_id, catid) + VALUES + (:contact_id, :member_id, :catid)"; + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":member_id", $memberId, PDO::PARAM_INT); + $stmt->bindParam(":contact_id", $cData['id'], PDO::PARAM_INT); + $stmt->bindParam(":catid", $sData['catid'], PDO::PARAM_INT); + $stmt->execute(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + } + } + } + // }}} +} +?> diff --git a/Toolkit/Members/TripPlanner/TripAuth.php b/Toolkit/Members/TripPlanner/TripAuth.php new file mode 100644 index 0000000..4a21ad5 --- /dev/null +++ b/Toolkit/Members/TripPlanner/TripAuth.php @@ -0,0 +1,788 @@ + + * @copyright 2009 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: TripAuth.php,v 1.2 2009/12/15 20:18:16 jamie Exp $ + * @link http://demo.gaslightmedia.com + * @see Toolkit_Members_Auth-LoginForm, Toolkit_Members_Auth-PasswordForm + */ + +require_once 'Auth.php'; + +/** + * Methods for the memberdb authentication system + * + * Handles Cookie and session generation, id challenges and security for + * the memberdb application + * + * @category MembersDB + * @package Toolkit_Members + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_Members_Auth-LoginForm, Toolkit_Members_Auth-PasswordForm + */ +class Toolkit_Members_TripPlanner_TripAuth extends Auth +{ + // {{{ properties + + /** + * Maximum idle time + * + * If more seconds pass before a new page request, then the user + * will have to re-authenticate back into the application. + * 1800 = 30 min + * 3600 = 1 hr + * + * @var integer + * @access protected + */ + protected $idleTime = 1800; + + /** + * Authentication options for storage driver + * + * This is setup here, so it can be overridden in subclasses and merged + * into existing authentication options. + * + * @var array + * @access protected + */ + protected $classOptions = array(); + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * Sets up the storage driver + * + * @param string $storageDriver (optional)Type of the storage driver + * @param array $options (optional)Additional options for the + * storage driver + * @param string $loginFunction (optional)Name of the function that + * creates the login form + * @param boolean $showLogin (optional)Should the login form be + * displayed if neccessary? + * + * @return void + * @access public + */ + public function __construct( + $storageDriver = 'DB', + array $options = array(), + $loginFunction = '', + $showLogin = true + ) { + // These are the default options, they are defined here b/c + // constants cannot be defined in the properites. + // subclasses that define any of the same authOptions will overwrite + // these when the options are merged. ALSO, options passed in + // via parameters will supercede/overwrite any of these authOptions + // or subclass authOptions. + $defaultOptions = array( + 'dsn' => DSN, + 'table' => 'contact', + 'usernamecol' => 'email', + 'passwordcol' => 'password', + 'db_fields' => array('id', 'fname', 'lname'), + 'cryptType' => 'md5', + ); + + $authOptions = array_merge( + $defaultOptions, + $this->classOptions, + $options + ); + + parent::Auth($storageDriver, $authOptions, $loginFunction, $showLogin); + } + + // }}} + + // {{{ loginForm() + + /** + * Function to set up the regular login form + * + * @param unknown $uname Last attempted username + * @param unknown $status The authorization status + * @param unknown &$auth The authentication object + * + * @return void + * @access public + */ + protected function loginForm($uname = null, $status = null, &$auth = null) + { + $login =& new TripPlannerLoginForm('member_login', + 'post', + BASE_URL . 'memberdb/index.php'); + $login->setDbh(Toolkit_Database::getInstance()); + $login->configureForm(); + echo $login->toHtml(); + } + + // }}} + + // {{{ passwordForm() + + /** + * Function to set up the forgot password form + * + * @return void + * @access public + */ + protected function passwordForm() + { + $pword =& new TripPlannerPasswordForm('member_password'); + $pword->setDbh(Toolkit_Database::getInstance()); + $pword->configureForm(); + echo $pword->toHtml(); + } + + // }}} + + // {{{ setIdle() + + /** + * Set the maximum idle time + * + * @param integer $time time in seconds + * @param boolean $add (optional)add time to current maximum idle time or not + * + * @return void + * @access public + */ + public function setIdle($time = null, $add = false) + { + $time = is_null($time) ? $this->idleTime : $time; + parent::setIdle($time, $add); + } + + // }}} +} + +/** + * Handles rendering and validating the member login form + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_FormBuilder + */ +class TripPlannerLoginForm extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * Custom rules to check for when validating the form + * + * @var array + * @access protected + */ + protected $registeredRules = array(); + + /** + * Where to perform validation + * + * @var string + * @access protected + */ + protected $validationType = 'client'; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param string $formName Form's name + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target + * @param mixed $attributes (optional)Extra attributes for the tag + * @param boolean $trackSubmit (optional)Whether to track if the form + * was submitted by adding a special hidden field + * + * @return void + * @access public + */ + public function __construct( + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->template = dirname(__FILE__) . '/templates/currentTables/'; + } + + // }}} + + // {{{ configureElements() + + /** + * Sets up the elements to be configured for use with the form + * + * @return void + * @access protected + */ + protected function configureElements() + { + $e = array(); + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'formHdr', + 'display' => Toolkit_Members_Admin_Controller::$listingType['singular'] . ' Login' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'username', + 'display' => 'Username' + ); + $e[] = array( + 'type' => 'password', + 'req' => true, + 'name' => 'password', + 'display' => 'Password' + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'doLogin', + 'display' => 'Login now', + 'opts' => array('id' => 'doLogin') + ); + $e[] = array( + 'type' => 'link', + 'req' => false, + 'name' => 'forgot', + 'display' => 'Forgot your password? Click', + 'opts' => BASE_URL . 'index.php?catid='.MEMBERS_CATEGORY.'&forgot=', + 'att' => 'here' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureFilters() + + /** + * Sets up the filters to be used with the form when submitted + * + * @return void + * @access protected + */ + protected function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Helper method to setup form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up required rules and extra defined rules for the form + * + * @return void + * @access protected + */ + protected function configureRules() + { + $this->setupRules($r); + } + + // }}} + + // {{{ setDbh() + + /** + * set the pdo to use for db calls + * + * @param PDO $pdo PHP Data Object to use + * + * @return void + * @access public + */ + public function setDbh(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + // {{{ setupRenderers() + + /** + * Inject custom renderers into the forms elements for custom display + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + + $renderer =& $this->defaultRenderer(); + $required = '*'; + $error = '
    {error}
    '; + + $renderer->setElementTemplate('{label} {element}', 'forgot'); + $renderer->setElementTemplate('{element}', 'doLogin'); + } + + // }}} + + // {{{ toHtml() + + /** + * Returns an HTML version of the form + * + * @return string HTML version of the form + * @access public + */ + public function toHtml() + { + $this->setupRenderers(); + if ($this->validate()) { + header('Location: ' . BASE_URL . 'memberdb/index.php'); + } elseif ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHtml(); + } else { + if ($_GET['status']) { + switch ($_GET['status']) { + case -1 : + $error = 'Your session has exceeded the maximum idle time'; + break; + + case -2 : + $error = 'Your session has expired.'; + break; + + case -3 : + $error = 'Invalid username or password.'; + break; + + case -4 : + // This is primarily used for Development. + // Users should never be presented with this error. + $error = 'Invalid Container'; + break; + + case -5 : + // This is only thrown if the advanced security system + // has detected a breach into the system. + $error = 'The system has encountered an error. Reference code: -5'; + break; + } + $output = "
    $error
    "; + } + $output .= parent::toHtml(); + } + + return $output; + } + + // }}} +} + +/** + * Handles rendering and validating the member password form + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + * @see Toolkit_FormBuilder + */ +class TripPlannerPasswordForm extends Toolkit_FormBuilder +{ + // {{{ properties + + /** + * Table to query when gathering information + * + * @var string + * @access public + */ + public $tableName = 'member'; + + /** + * Custom defined rules to validate against when the form is submitted + * + * @var array + * @access protected + */ + protected $registeredRules = array(); + + /** + * Where to perform validation + * + * @var string + * @access protected + */ + protected $validationType = 'client'; + + // }}} + // {{{ __construct() + + /** + * Constructor + * + * @param string $formName Form's name + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target + * @param mixed $attributes (optional)Extra attributes for the tag + * @param boolean $trackSubmit (optional)Whether to track if the form + * was submitted by adding a special hidden field + * + * @return void + * @access public + */ + public function __construct( + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->template = dirname(__FILE__) . '/templates/currentTables/'; + } + + // }}} + + // {{{ checkAddressExists() + + /** + * Checks to see if the email address exists before allowing an email to go out + * + * @param string $value submitted email address + * + * @return boolean If the email address exists or not + * @access public + */ + public function checkAddressExists($value) + { + try { + $sql = " + SELECT count(*) AS total + FROM {$this->tableName} + WHERE member_contact_email = :mce"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mce', $value, PDO::PARAM_STR); + $stmt->execute(); + $stmt->bindColumn('total', $exists); + $stmt->fetch(); + + return (bool) $exists; + } catch (PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ configureElements() + + /** + * Sets up the elements to be configured for use with the form + * + * @return void + * @access protected + */ + protected function configureElements() + { + $e = array(); + + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'formHdr', + 'display' => 'Email Reminder' + ); + $e[] = array( + 'type' => 'text', + 'req' => true, + 'name' => 'email', + 'display' => 'Your Member Contact Email Address' + ); + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'submit', + 'display' => 'Send' + ); + + $this->setupElements($e); + } + + // }}} + // {{{ configureFilters() + + /** + * Sets up the filters to be used with the form when submitted + * + * @return void + * @access protected + */ + protected function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Helper method to setup form + * + * @return void + * @access public + */ + public function configureForm() + { + $this->configureElements(); + $this->configureFilters(); + $this->configureRules(); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up required rules and extra defined rules for the form + * + * @return void + * @access protected + */ + protected function configureRules() + { + $r = array(); + + $r[] = array( + 'element' => 'email', + 'message' => 'ERROR: Invalid Email Format!', + 'type' => 'email', + 'format' => null, + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + $r[] = array( + 'element' => 'email', + 'message' => 'ERROR: Cannot locate email address!', + 'type' => 'callback', + 'format' => array(&$this, + 'checkAddressExists'), + 'validation' => $this->validationType, + 'reset' => true, + 'force' => false + ); + + $this->setupRules($r); + } + + // }}} + + // {{{ setDbh() + + /** + * set the pdo to use for db calls + * + * @param PDO $pdo PHP Data Object to use + * + * @return void + * @access public + */ + public function setDbh(PDO $pdo) + { + $this->dbh = $pdo; + } + + // }}} + // {{{ setupRenderers() + + /** + * Inject custom renderers into the forms elements for custom display + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + parent::setupRenderers(); + + $renderer =& $this->defaultRenderer(); + $required = '*'; + $error = '
    {error}
    '; + + $renderer->setElementTemplate('{element}', 'submit'); + } + + // }}} + + // {{{ processData() + + /** + * Processes the data submitted by the form + * + * Gets the login credentials for the matching email address and mails + * them to that email address + * + * @param array $values submitted form values + * + * @return boolean Result of mail + * @access protected + */ + protected function processData($values) + { + try { + $sql = " + SELECT member_login, member_passwd + FROM {$this->tableName} + WHERE member_contact_email = :mce"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':mce', $values['email'], PDO::PARAM_STR); + $stmt->execute(); + $row = $stmt->fetch(); + + $htmlMsg + = "Here is your " . SITENAME . " password:

    " . + "Login: {$row['member_login']}
    " . + "Email: {$values['email']}
    " . + "Password: {$row['member_passwd']}

    "; + + $msg + = "Here is your " . SITENAME . " password:\n\n" . + "Login: {$row['member_login']}\n" . + "Email: {$values['email']}\n" . + "Password: {$row['member_passwd']}"; + + $crlf = "\n"; + $mimeMail = new Mail_mime($crlf); + $mimeMail->setFrom(SITENAME . ' <' . OWNER_EMAIL . '>'); + $mimeMail->setSubject('Your ' . SITENAME . ' Password'); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $mail =& Mail::factory('mail'); + $body = $mimeMail->get(); + $headers = $mimeMail->headers($hdrs); + + $res = $mail->send($values['email'], $headers, $body); + + return PEAR::isError($res) ? + Toolkit_Common::handleError($res) : + $res; + } catch (PDOException $e) { + Toolkit_Common::handlError($e); + } + } + + // }}} + + // {{{ toHtml() + + /** + * Returns an HTML version of the form + * + * @return string HTML version of the form + * @access public + */ + public function toHtml() + { + $this->setupRenderers(); + if ($this->validate()) { + if ($this->process(array(&$this, 'processData'))) { + $url = BASE_URL . 'index.php?catid=' . MEMBERS_CATEGORY; + $e =& $this->getElement('email'); + $email = $e->getValue(); + $output + = "

    Your Login Information has been sent to $email

    " . + "

    Continue to Member Login

    "; + } else { + $output = '

    Email address not found.

    '; + } + } elseif ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHtml(); + } else { + $output .= parent::toHtml(); + } + + return $output; + } + + // }}} +} +?> diff --git a/Toolkit/Members/TripPlanner/helpme.html b/Toolkit/Members/TripPlanner/helpme.html new file mode 100644 index 0000000..aebc3c1 --- /dev/null +++ b/Toolkit/Members/TripPlanner/helpme.html @@ -0,0 +1,55 @@ + + + + Help Me + + + +
    + +

    +This section has been designed to allow you to build your own itinerary including attractions, recreation +and places to stay in Michigan's Upper Peninsula. To get started, search for the recreation, attraction or +place to stay on our Web site. As you find items that may be of interest to you, simply click the "Add to +Trip Planner" icon on each business listing. Each item will then get added to your list. Once you have +completed adding items to your planner list, you may take the following actions:

    + + + +
      +
    1. Request Info
      +This action will send an email directly to each individual business using our "Send Me More Information" +form. For the attractions, recreation or places to stay you have added to your list that do not have an +email, you will be presented with the business name and their phone number.
    2. + +
    3. Print This List
      +You may print the full list of the items you have added to your travel planner, making it an easy reference +to the business name, address, phone number, email address and Web site.
    4. + +
    5. View Map
      +View all of the items you have added to your trip planner on an interactive map, allowing you to get +driving directions to each of those locations. +
    6. + +
    7. +Save your Trip Planner
      +Create an account and SAVE your list for future reference. +
    8. + +
    + +
    + + diff --git a/Toolkit/Members/TripPlanner/login.php b/Toolkit/Members/TripPlanner/login.php new file mode 100644 index 0000000..a3ea672 --- /dev/null +++ b/Toolkit/Members/TripPlanner/login.php @@ -0,0 +1,57 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: login.php,v 1.2 2009/12/15 20:18:16 jamie Exp $ + * @link <> + */ +$dont_include_functions = true; + +/** + * Description for require_once + */ +require_once '../../../setup.phtml'; +HTTP_Session2::useCookies(false); +HTTP_Session2::start(); +$tripPlannerAuth =& new Toolkit_Members_TripPlanner_TripAuth( + 'DB', + array(), + '', + false +); +$tripPlannerAuth->setIdle(); +$tripPlannerAuth->start(); + +if (isset($_GET['logout'])) { + $tripPlannerAuth->logout(); +} + +if (!$tripPlannerAuth->checkAuth()) { + // Manually adjust the authentication status for empty credentials + if (empty($_POST['username']) || empty($_POST['password'])) { + $status = -3; + } + $status = $tripPlannerAuth->getStatus(); + header('Location: ' . BASE_URL . 'index.php?catid=' . MEMBER_SESSION_PAGE . '&status=' . $status); +} else { + $sessionList = new Toolkit_Members_TripPlanner_Sessions( + Toolkit_Database::getInstance(), + &$tripPlannerAuth + ); + $sessionList->retrieveList(); + $sessionList->saveList(); + header('Location: ' . BASE_URL . 'index.php?catid=' . MEMBER_SESSION_PAGE); +} +?> diff --git a/Toolkit/Members/TripPlanner/tripPlannerMap.php b/Toolkit/Members/TripPlanner/tripPlannerMap.php new file mode 100644 index 0000000..6048600 --- /dev/null +++ b/Toolkit/Members/TripPlanner/tripPlannerMap.php @@ -0,0 +1,162 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: tripPlannerMap.php,v 1.2 2009/12/15 20:18:16 jamie Exp $ + * @link <> + */ + +/** + * Description for require_once + */ +require_once '../../../setup.phtml'; +HTTP_Session2::useCookies(false); +HTTP_Session2::start(); + +?> + + + +The Official Travel Website for Michigan's Upper Peninsula + + + + + + + + + + + +
    +prepare($sql); + foreach ($members as $i) { + $stmt->bindParam(':mid', $i, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if (!empty($row['lat']) && !empty($row['lon'])) { + $memCoords[$i] = array( + 'name' => $row['member_name'], + 'street' => $row['street'], + 'state' => $row['state_abb'], + 'city' => $row['city_name'], + 'zip' => $row['zip'], + 'lat' => $row['lat'], + 'lng' => $row['lon'] + ); + } elseif (!empty($row['state_abb']) && + !empty($row['city_name']) && + is_numeric($row['zip']) && + !empty($row['street'])) { + + $api_key = GMAPS_API; + $addr = $row['street']; + $zip = $row['zip']; + $city = $row['city_name']; + $state = $row['state_abb']; + $url = "http://maps.google.com/maps/geo?output=xml&oe=utf8&sensor=false&key=$api_key&q="; + $q = "$addr, $city, $state, $zip"; + $url .= urlencode($q); + + // Query Google for this location's longitude and latitude + $command = "/usr/bin/curl '$url'"; + unset($output, $return); + exec($command, $output, $return); + if (preg_match_all("/(-?[0-9]{1,2}\.[0-9]+)\,(-?[0-9]{1,2}\.[0-9]+)\,0<\/coordinates>/", $output[13], $temp)) { + if (isset($temp[1][1])) { + $lng = $temp[1][1]; + $lat = $temp[2][1]; + } elseif (isset($temp[1][0])) { + $lng = $temp[1][0]; + $lat = $temp[2][0]; + } else { + $lat = 'NULL'; + $lng = 'NULL'; + } + } else { + $lat = null; + $lng = null; + } + + if (!is_null($lat) && !is_null($lng)) { + $memCoords[$i] = array( + 'name' => $row['member_name'], + 'street' => $row['street'], + 'state' => $row['state_abb'], + 'city' => $row['city_name'], + 'zip' => $row['zip'], + 'lat' => $lat, + 'lng' => $lng, + ); + } + } + if (!empty($row['logo'])) { + $memCoords[$i]['logo'] = $row['logo']; + } + if (!empty($row['member_contact_email'])) { + $memCoords[$i]['member_contact_email'] = $row['member_contact_email']; + } + if (!empty($row['url'])) { + $memCoords[$i]['url'] = $row['url']; + } + } + // Get the bounds so we can set the map zoom level + $b = array( + 'minLat' => 48.1953, + 'maxLat' => 44.9547, + 'minLng' => -90.5712, + 'maxLng' => -83.2983, + ); + foreach ($memCoords as $j) { + if ($j['lat']) { + if ($j['lat'] < $b['minLat']) { + $b['minLat'] = $j['lat']; + } + if ($j['lat'] > $b['maxLat']) { + $b['maxLat'] = $j['lat']; + } + } + if ($j['lng']) { + if ($j['lng'] < $b['minLng']) { + $b['minLng'] = $j['lng']; + } + if ($j['lng'] > $b['maxLng']) { + $b['maxLng'] = $j['lng']; + } + } + } +} catch (PDOException $e) { + return Toolkit_Common::handleError($e); +} +?> + + + diff --git a/Toolkit/Members/TripPlanner/wish-list.php b/Toolkit/Members/TripPlanner/wish-list.php new file mode 100755 index 0000000..2b5dc75 --- /dev/null +++ b/Toolkit/Members/TripPlanner/wish-list.php @@ -0,0 +1,78 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: wish-list.php,v 1.2 2009/12/15 20:18:16 jamie Exp $ + * @link <> + */ +//die('
    '.print_r($_REQUEST, true).'
    '); +$dont_include_functions = true; +/** + * requires setup.phtml + */ +require_once '../../../setup.phtml'; + +HTTP_Session2::useCookies(false); +HTTP_Session2::start(); + +$tripPlannerAuth =& new Toolkit_Members_TripPlanner_TripAuth( + 'DB', + array(), + '', + false +); +$tripPlannerAuth->setIdle(); +$tripPlannerAuth->start(); +$sessionList = new Toolkit_Members_TripPlanner_Sessions( + Toolkit_Database::getInstance(), + &$tripPlannerAuth +); +if ($_SESSION['wish_list'][$_REQUEST['member_id']]) { + $sessionList->removeRecord($_REQUEST['member_id']); + $add = false; +} else { + $sessionList->addRecord($_REQUEST['member_id'], $_REQUEST['catid']); + $add = true; +} + +//remove the email from GET array and goback to member detail page +unset($_REQUEST['member_email']); +if (is_array($_REQUEST)) { + foreach ($_REQUEST as $pname => $pval) { + if ($pval) { + $param_part[] = $pname.'='.urlencode($pval); + } + } +} +if (is_array($param_part)) { + $params = implode("&", $param_part); +} + +// need to make sure any GET parameter passed to this page get resent back +$url = BASE_URL . "index.php?catid=".$_REQUEST['catid']; +$url .= ($_REQUEST['detail']) ? "&member_id=" . $_REQUEST['member_id'] :'&_qf__SearchForm='; +$url .= ($_REQUEST['search']) ? "&search=" . $_REQUEST['search'] :''; +$url .= ($_REQUEST['business_name']) ?"&business_name=" . urlencode($_REQUEST['business_name']):''; +$url .= ($_REQUEST['category_id']) ? "&category_id=" . $_REQUEST['category_id'] :''; +$url .= ($_REQUEST['sub_category_id']) ? "&sub_category_id=" . $_REQUEST['sub_category_id'] :''; +$url .= ($_REQUEST['region_id']) ? "®ion_id=" . $_REQUEST['region_id'] :''; +$url .= ($_REQUEST['city_id']) ? "&city_id=" . $_REQUEST['city_id'] :''; +$url .= ($_REQUEST['page']) ? "&page=" . $_REQUEST['page'] :''; +$url .= ($_REQUEST['cPage']) ? "&cPage=" . $_REQUEST['cPage'] :''; +$url .= ($_REQUEST['alpha']) ? "&alpha=" . $_REQUEST['alpha'] :''; +$url .= ($_REQUEST['pageOffset']) ? "&pageOffset=" . $_REQUEST['pageOffset'] :''; +$url .= ($add == true) ? '&sessionAdd=1': '&sessionAdd=2'; +header("location: $url"); +exit(); +?> diff --git a/Toolkit/Members/TripPlannerList.php b/Toolkit/Members/TripPlannerList.php new file mode 100644 index 0000000..902675d --- /dev/null +++ b/Toolkit/Members/TripPlannerList.php @@ -0,0 +1,431 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: TripPlannerList.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link <> + */ + +/** + * Short description for class + * + * Long description (if any) ... + * + * @category Toolkit + * @package Toolkit_Members + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version Release: @package_version@ + * @link <> + */ +class Toolkit_Members_TripPlannerList +{ + // {{{ properties + + + /** + * Description for public + * @var string + * @access protected + */ + public $dbh; + + /** + * Template directory for any templates + * @var string + * @access protected + */ + protected $templatesDir = 'templates'; + + /** + * compile directory for flexy + * @var string + * @access protected + */ + protected $compiledDir = 'compiled'; + + protected $plannerListPageId; + protected $plannerFormPageId; + + // }}} + // {{{ __construct() + + + /** + * class constructor + * + * Only setup values need be done here + * any work need to be done within methods + * + * @param object $pdo PDO reference + * + * @return void + * @access public + */ + function __construct($pdo) + { + $this->dbh = $pdo; + // These settings are used to override flexyOptions. + $this->templatesDir = dirname(__FILE__) . "/{$this->templatesDir}"; + $this->compiledDir = dirname(__FILE__) . "/{$this->compiledDir}"; + $this->flexyConfig = $GLOBALS['flexyOptions']; + $this->flexyConfig['templateDir'] = $this->templatesDir; + $this->flexyConfig['compileDir'] = $this->compiledDir; + $this->pagerOptions['containerClass'] = 'pages'; + $this->plannerListPageId = MEMBER_SESSION_PAGE; + $this->plannerFormPageId = MEMBER_SESSION_FORM; + } + + // }}} + // {{{ getAncestors() + + /** + * getAncestors:get the ancestors for this category + * + * @param integer $catid catid + * @param integer $count starting counter + * + * @return array + * @access public + */ + function getAncestors($catid, $count = 0) + { + static $ancestors, $toolbox; + if (!$ancestors || $count == 0) { + $ancestors = array(); + } + if (!$toolbox) { + $toolbox = new GLM_TEMPLATE(HOME_ID); + } + if ($catid) { + $sql = " + SELECT id, category, parent + FROM bus_category + WHERE id = :catid"; + try { + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":catid", $catid, PDO::PARAM_INT); + $stmt->execute(); + $res = $stmt->fetch(); + $ancestors[$count]['id'] = $res['id']; + $ancestors[$count]['label'] = $res['category']; + } catch(PDOException $e) { + ToolkitCommon::handleError($e); + } + + $url = $toolbox->get_seo_url($res['id']); + $ancestors[$count]['link'] = $url; + $this->getAncestors($res['parent'], ++$count); + + return array_reverse($ancestors); + } + } + + // }}} + // {{{ getSessionList() + + + /** + * get list from session + * + * @return void + * @access public + */ + function getSessionList() + { + // for the session list need to sort by categories then + // we'll have to go through the session first and organize to what category they're in + // then run query + // have to order by the page name we'll need to find there names first then + $sql = " + SELECT category + FROM bus_category + WHERE id = :category_id"; + $getCatName = $this->dbh->prepare($sql); + $sql = " + SELECT member_name + FROM member + WHERE member_id = :member_id"; + $getMemberName = $this->dbh->prepare($sql); + if (is_array($_SESSION['wish_list']) && !empty($_SESSION['wish_list'])) { + foreach ($_SESSION['wish_list'] as $member_id => $mData) { + try { + $getCatName->bindParam(":category_id", $mData['catid'], PDO::PARAM_INT); + $getCatName->execute(); + $toolboxPageName = $getCatName->fetchColumn(); + $getMemberName->bindParam(":member_id", $member_id, PDO::PARAM_INT); + $getMemberName->execute(); + $memberName = $getMemberName->fetchColumn(); + $members[$toolboxPageName][$memberName] = $member_id; + } catch(PDOException $e) { + ToolkitCommon::handleError($e); + } + } + // for sorting members by the page they're added from + natSort(&$members); + try { + $sql = " + SELECT m.*, c.city_name AS city, s.state_name AS state, + s.state_abb AS state_abbr, + m.street||', '||c.city_name||', '||s.state_name||', '||m.zip AS address + FROM member m + JOIN state s USING (state_id) + JOIN city c USING (city_id) + WHERE member_id = :member_id"; + $stmt = $this->dbh->prepare($sql); + if (is_array($members)) { + $count = 0; + foreach ($members as $toolbboxPageName => $memberList) { + // for sorting members under each page + natSort(&$memberList); + foreach ($memberList as $memberName => $member_id) { + $stmt->bindParam(":member_id", $member_id, PDO::PARAM_INT); + $stmt->execute(); + // set record data + $catid = $_SESSION['wish_list'][$member_id]['catid']; + $recordSet[$count] = $stmt->fetch(); + // setup the breadCrumbs + $recordSet[$count]['breadCrumbs'] = $this->printAncestors($catid); + // setup delete link + $recordSet[$count]['deleteUrl'] = BASE_URL . + 'wish-list.php?catid=' . $_REQUEST['catid'] . + '&member_id=' . $member_id; + // setup the url + $recordSet[$count]['urlText'] = $recordSet[$count]['url']; + if ($recordSet[$count]['url']) { + $recordSet[$count]['url'] = BASE_URL . + 'Toolkit/Members/memberClickThru.php' . + '?member_id=' . $member_id . + '&href=' . urlencode($recordSet[$count]['url']); + } + ++$count; + } + } + if (is_array($recordSet)) { + $temp = new HTML_Template_Flexy($this->flexyConfig); + $page = new stdClass; + $toolbox = new GLM_TEMPLATE(HOME_ID); + $page->accountUrl = $toolbox->get_seo_url($this->plannerFormPageId); + $page->loginUrl = BASE_URL . 'Toolkit/Members/TripPlanner/login.php'; + $page->logoutUrl = BASE_URL . 'Toolkit/Members/TripPlanner/login.php?logout=1'; + $page->saveUrl = BASE_URL . 'index.php?catid='.$this->plannerListPageId.'&cPage=Save+List'; + $page->requestUrl = BASE_URL . 'index.php?catid='.$this->plannerListPageId.'&cPage=Send+List'; + $page->loginStat = ($_REQUEST['status']) ? 'Invalid username or password.': ''; + $page->isLoggedIn = $this->isLoggedIn(); + $page->username = $page->isLoggedIn; + $page->baseurl = BASE_URL; + $page->recordSet = $recordSet; + $page->numberedSet = count($recordSet); + $temp->compile("tripPlannerList.tpl"); + $out .= $temp->BufferedOutputObject($page); + } + } + //echo '
    '.print_r($page, true).'
    '; + echo $out; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } else { + echo $this->showEmpty(); + } + } + + // }}} + // {{{ isLoggedIn() + + /** + * check if user is logged in or not + * + * @access public + * @return string + */ + function isLoggedIn() + { + $tripPlannerAuth =& new Toolkit_Members_TripPlanner_TripAuth('DB', array(), '', false); + $tripPlannerAuth->setIdle(); + $tripPlannerAuth->start(); + + $test = $tripPlannerAuth->checkAuth(); + if ($test) { + // give back the username + return $tripPlannerAuth->getUsername(); + } else { + return false; + } + } + + // }}} + // {{{ printAncestors() + + /** + * printAncestors + * + * @param mixed $catid page id + * + * @access public + * @return string + */ + function printAncestors($catid) + { + $ancestors = $this->getAncestors($catid, 0); + if (is_array($ancestors)) { + for ($i = 0; $i < count($ancestors); ++$i) { + $out[] = '' . $ancestors[$i]["label"] . ''; + } + if (is_array($out)) { + return implode(" / ", $out); + } + } + } + + // }}} + // {{{ saveList() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return string Return description (if any) ... + * @access public + */ + function saveList() + { + if ($this->isLoggedIn()) { + $contactId = $_SESSION['_authsession']['data']['id']; + // if they already have something saved then wipe it out. + // (only one list per contact) + try { + $sql = " + DELETE FROM member_session + WHERE contact_id = :contact_id"; + $del = $this->dbh->prepare($sql); + $del->bindParam(":contact_id", $contactId, PDO::PARAM_INT); + $del->execute(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + + $sql = " + INSERT INTO member_session + (member_id,contact_id,catid) + VALUES + (:member_id,:contact_id,:catid)"; + $stmt = $this->dbh->prepare($sql); + if (is_array($_SESSION['wish_list'])) { + foreach ($_SESSION['wish_list'] as $member_id => $mData) { + $catid = $mData['catid']; + try { + $stmt->bindParam(":member_id", $member_id, PDO::PARAM_INT); + $stmt->bindParam(":contact_id", $contactId, PDO::PARAM_INT); + $stmt->bindParam(":catid", $catid, PDO::PARAM_INT); + $stmt->execute(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + $html = '

    You list has been saved.

    '; + } + } + return $html; + } + + // }}} + // {{{ show() + + + /** + * Calls the appropiate function for listing,saving,sending + * or printing the list also will need to handle grabbing list from + * database and repopulate the session. + * + * @return void + * @access public + */ + function show() + { + echo $this->toHTML(); + } + + // }}} + // {{{ showEmpty() + + /** + * shows the template tripPlannerNoList.tpl + * + * @access public + * @return string + */ + function showEmpty() + { + $temp = new HTML_Template_Flexy($this->flexyConfig); + $temp->compile("tripPlannerNoList.tpl"); + $page = new stdClass; + $toolbox = new GLM_TEMPLATE(HOME_ID); + $page->accountUrl = $toolbox->get_seo_url($this->plannerFormPageId); + $page->loginUrl = BASE_URL . 'Toolkit/Members/TripPlanner/login.php'; + $page->logoutUrl = BASE_URL . 'Toolkit/Members/TripPlanner/login.php?logout=1'; + $page->saveUrl = BASE_URL . 'index.php?catid='.$this->plannerListPageId.'&cPage=Save+List'; + $page->requestUrl = BASE_URL . 'index.php?catid='.$this->plannerListPageId.'&cPage=Send+List'; + $page->loginStat = ($_REQUEST['status']) ? 'Invalid username or password.': ''; + $page->isLoggedIn = $this->isLoggedIn(); + $page->username = $page->isLoggedIn; + $page->baseurl = BASE_URL; + return $temp->BufferedOutputObject($page); + } + + // }}} + // {{{ toHTML() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return string Return description (if any) ... + * @access public + */ + function toHTML() + { + if (is_array($_SESSION['wish_list']) && !empty($_SESSION['wish_list'])) { + switch ($_REQUEST['cPage']) { + case "Send List": + $pp = new Toolkit_Contacts_SendTripPlanner($this->dbh, + 'TravelList', + 'post', + BASE_URL . + 'index.php?catid='.$this->plannerListPageId); + $pp->configureForm(); + $html = $pp->toHTML(); + break; + case "Save List": + $html = $this->saveList(); + $html .= $this->getSessionList(); + break; + case "Login": + break; + case "Show List": + default: + $html = $this->getSessionList(); + break; + } + } else { + echo $this->showEmpty(); + } + return $html; + } + // }}} +} +?> diff --git a/Toolkit/Members/UserSearchForm.php b/Toolkit/Members/UserSearchForm.php new file mode 100644 index 0000000..572a0d9 --- /dev/null +++ b/Toolkit/Members/UserSearchForm.php @@ -0,0 +1,775 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: UserSearchForm.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Member Search Form + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Members_UserSearchForm + extends Toolkit_FormBuilder implements Toolkit_Form +{ + // {{{ properties + + + /** + * Description for protected + * @var array + * @access protected + */ + protected $memberCatsAssignedToPage = array(); + + /** + * The Table name used to store the data of the member record in the database. + * + * @var string + * @access public + */ + public $tableName = 'member'; + + /** + * Array of data that holds the meta data info on the table + * + * Contains information on the type of fields in the database. + * That way when we run our automated SQL queries with our PDO + * we can properly bind data to our SQL queries. This will + * allow for one more layer of protection against any sql + * injection attempts. + * + * @var string + * @access public + */ + public $tableMetaData; + + /** + * Flexy options used in the renderer + * + * @var array + * @access protected + */ + protected $flexyOptions; + + /** + * The name of the template used to render the member info form + * + * @var string + * @access protected + */ + protected $formTemplate = 'memberSearchForm.tpl'; + + /** + * Form access from inside the template + * + * @var object + * @access protected + */ + protected $view; + + /** + * registered rules for the form + * + * @var array + * @access protected + */ + protected $registeredRules = array(); + + /** + * catid to use in the form + * + * @var integer + * @access private + */ + private $_catid; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param PDO $pdo PHP Data Object for DB calls + * @param string $formName Form's name. + * @param string $method (optional)Form's method defaults to 'POST' + * @param string $action (optional)Form's action + * @param string $target (optional)Form's target defaults to '_self' + * @param mixed $attributes (optional)Extra attributes for tag + * @param bool $trackSubmit (optional)Whether to track if the form was + * submitted by adding a special hidden field + * + * @access public + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + $this->flexyOptions = Toolkit_Members::getFlexyOptions(); + } + + // }}} + + // {{{ configureConstants() + + /** + * Sets the constants for the form + * + * The member category select list must always default + * to the -- Choose Category -- option + * + * @return void + * @access public + */ + public function configureConstants() + { + $c = array( + 'catid' => $this->_catid, + 'search' => 1, + ); + + $this->setupConstants($c); + } + + // }}} + // {{{ configureDefaults() + + /** + * Sets the defaults for the an existing member + * + * Populates data for the main member form. Also grabs + * data to populate the modules on the form if needed. + * + * @return array $defaults Returns the array of defaults + * so children who call this function + * can obtain a copy of these values. + * @access public + */ + public function configureDefaults() + { + $d = array(); + + $this->setupDefaults($d); + + return $d; + } + + // }}} + // {{{ configureElements() + + /** + * Setup the elements to use on the form. + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function configureElements(Config_Container $c) + { + $e = array(); + + // get reference to [listing type] section of config file + $config =& $c->getItem('section', 'listing type'); + $singularDirective =& $config->getItem('directive', 'singular'); + $singularType = $singularDirective->getContent(); + $pluralDirective =& $config->getItem('directive', 'plural'); + $pluralType = $pluralDirective->getContent(); + + $memberCategories = $this->getMemberCats(); + $memberSubCategories + = $this->getMemberSubCats($memberCategories, $_GET['category_id']); + $memberAmenities = $this->getMemberAmenities(); + + $cities = $this->getAvailableCities(); + $this->createAvailableMemberTypesFromCity($cities); + + // All Grouped Elements are created here. + foreach ($memberAmenities as $k => $v) { + $amenities[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => $v, + 'display' => $k + ); + } + + // All Elements are created here. This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'SearchForm_hdr' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'catid' + ); + $e[] = array( + 'type' => 'hidden', + 'req' => false, + 'name' => 'search' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'member_name', + 'display' => "$singular Name", + 'opts' => array('class' => 'text') + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'city_id', + 'display' => 'City', + 'opts' => array('' => '-- Select --') + $cities, + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'category_id', + 'display' => "$singular Type", + 'opts' => array('' => '-- Select --') + $memberCategories + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'sub_category_id', + 'display' => "$singular Sub Type", + 'opts' => array('' => '-- Select --') + $memberSubCategories + ); + // Only show do if we have amenities to show. + if (!empty($memberAmenities)) { + $e[] = array( + 'type' => 'group', + 'req' => false, + 'name' => 'amenities', + 'group' => $amenities, + 'seperator' => '', + 'appendName' => true + ); + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'search_all_amenity', + 'opts' => 'Only show members who offer all selected amenities' + ); + } + + $this->setupElements($e); + } + + // }}} + // {{{ configureFilters() + + /** + * Setup the filters to apply to the elements before we are + * handed the values submitted + * + * @return void + * @access public + */ + public function configureFilters() + { + $f = array(); + + $f[] = array( + 'element' => '__ALL__', + 'filter' => 'trim' + ); + + $this->setupFilters($f); + } + + // }}} + // {{{ configureForm() + + /** + * Helper method to configure the entire form + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function configureForm(Config_Container $c) + { + $this->configureElements($c); + $this->configureRules(); + $this->configureFilters(); + $this->configureDefaults(); + $this->configureConstants(); + } + + // }}} + // {{{ configureRules() + + /** + * Sets up all the rules to be used when the form is validated. + * + * @return void + * @access public + */ + public function configureRules() + { + $this->setupRules($rules); + } + + // }}} + // {{{ createAvailableMemberTypesFromCity() + + /** + * Get available categories from members assigned to cities + * + * @param array $cities Available cities to get members from + * + * @return void + * @access protected + */ + protected function createAvailableMemberTypesFromCity(array $cities) + { + try { + $cityCats = array(); + + $availCats = array(); + foreach ($this->memberCatsAssignedToPage as $i) { + $cats = Toolkit_Common::getHierarchicalTreeStructure( + 'category', + 'category_id', + 'parent_id', + 'pos', + $i, + 0, + false + ); + + $availCats = array_merge($availCats, array_keys($cats)); + } + $availCats = implode(', ', $availCats); + + $sql = " + SELECT distinct c.category_id, c.parent_id, p.name AS + parent, c.name AS category + FROM category c + JOIN category p + ON c.parent_id = p.category_id + JOIN member_category mc + ON c.category_id = mc.category_id + NATURAL JOIN member m + WHERE m.city_id = :cid + AND c.category_id in ($availCats) + ORDER BY c.name"; + $stmt = $this->dbh->prepare($sql); + foreach ($cities as $i => $j) { + if (is_numeric($i)) { + $stmt->bindParam(':cid', $i, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetchAll(PDO::FETCH_ASSOC); + foreach ($row as $x) { + $cityCats[$i][$x['parent_id']][$x['category_id']] = $x['category']; + $mainCats[$x['parent_id']] = $x['parent']; + } + + } + } + + $this->cityCategories = $cityCats; + $this->mainCats = $mainCats; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ getAvailableCities() + + /** + * Returns all available cities that derive from members assigned to + * this page + * + * @return array array of cities available to this page + * @access protected + */ + protected function getAvailableCities() + { + try { + $memCats = array(); + foreach ($this->memberCatsAssignedToPage as $i) { + $cats = Toolkit_Common::getHierarchicalTreeStructure( + 'category', + 'category_id', + 'parent_id', + 'pos', + $i, + 0, + false + ); + + $memCats = array_merge($memCats, array_keys($cats)); + } + $memCats = implode(', ', $memCats); + $sql = " + SELECT region + FROM bus_category + WHERE id = :catid"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':catid', $_GET['catid'], PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('region', $county); + $stmt->fetch(); + if (is_numeric($county)) { + $county = "AND region_id = $county"; + } + $sql = " + SELECT * + FROM city + WHERE city_id in ( + SELECT distinct(city_id) + FROM member + WHERE member_id in ( + SELECT distinct(member_id) + FROM member_category + WHERE category_id IN ($memCats) + ) + ) + $county + ORDER BY city_name"; + + $stmt = $this->dbh->prepare($sql); + $stmt->execute(); + $cities = array(); + while ($row = $stmt->fetch()) { + $cities[$row['city_id']] = $row['city_name']; + } + + asort($cities); + return $cities; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getMemberAmenities() + + /** + * Get all the amenities for the member + * + * @return array member amenities + * @access protected + */ + protected function getMemberAmenities() + { + try { + $amenities = array(); + + $sql = " + SELECT * + FROM amenity a + NATURAL JOIN member_amenity ma + NATURAL JOIN member_category mc + WHERE mc.category_id = :cid + OR mc.category_id in ( + SELECT category_id + FROM category + WHERE parent_id = :cid) + ORDER BY amenity_name"; + + $stmt = $this->dbh->prepare($sql); + foreach ($this->memberCatsAssignedToPage as $id) { + $stmt->bindParam(':cid', $id, PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch()) { + $amenities[$row['amenity_name']] = $row['amenity_id']; + } + } + + return $amenities; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getMemberCats() + + /** + * Get all the main categories available from the categories that + * are assigned to the page. + * + * If a main category is assigned to a page, then add to list. + * + * If a sub category is assgined to page, then add parent (main) category + * to the list. + * + * @return array Main categories available for page + * @access protected + */ + protected function getMemberCats() + { + try { + $sql = " + SELECT * + FROM category + WHERE category_id = :cid"; + + $stmt = $this->dbh->prepare($sql); + $categories = array(); + foreach ($this->memberCatsAssignedToPage as $id) { + $stmt->bindParam(':cid', $id, PDO::PARAM_INT); + $stmt->execute(); + if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + if ($row['parent_id'] == '0') { + $categories[$row['category_id']] = $row['name']; + } else { + $stmt->bindParam(':cid', $row['parent_id'], PDO::PARAM_INT); + $stmt->execute(); + if ($parRow = $stmt->fetch(PDO::FETCH_ASSOC)) { + $categories[$parRow['category_id']] = $parRow['name']; + } + } + } + } + asort($categories); + return $categories; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getMemberSubCats() + + /** + * Get all the sub categories available from the main categories that + * are available to the page. + * + * @param array $categories Main level categories to get sub levels for + * @param integer $parentIdKey (optional) Main level that was searched on + * + * @return array Sub categories available for page + * @access protected + */ + protected function getMemberSubCats(array $categories, $parentIdKey = null) + { + if (empty($categories)) { + return array(); + } + + try { + // Get the category information + $sql = " + SELECT * + FROM category + WHERE category_id = :cid"; + + $catStmt = $this->dbh->prepare($sql); + + // Get the sub-category information + $sql = " + SELECT * + FROM category + WHERE parent_id = :parent_id"; + $subCatStmt = $this->dbh->prepare($sql); + $subCategories = array(); + + while (list($id,) = each($categories)) { + $catStmt->bindParam(':cid', $id, PDO::PARAM_INT); + $catStmt->execute(); + $category = $catStmt->fetch(); + try { + $subCatStmt->bindParam( + ':parent_id', + $category['category_id'], + PDO::PARAM_INT + ); + $subCatStmt->execute(); + if ($subCatData = $subCatStmt->fetchAll()) { + foreach ($subCatData as $key => $val) { + $catStmt->bindParam( + ':cid', + $val['category_id'], + PDO::PARAM_INT + ); + $catStmt->execute(); + $subCat = $catStmt->fetch(); + if (in_array($subCat['category_id'], $this->memberCatsAssignedToPage)) { + // Subcat assgined to page, only assign + // child of parent cat that is assigned + // to page. + $subCategories[$subCat['parent_id']][$subCat['category_id']] = $subCat['name']; + } elseif (in_array($subCat['parent_id'], $this->memberCatsAssignedToPage)) { + // Parent category assigned to page, add all + // children found + $subCategories[$subCat['parent_id']][$subCat['category_id']] = $subCat['name']; + } + } + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + if ( is_numeric($parentIdKey) + && array_key_exists($parentIdKey, $subCategories) + ) { + return $subCategories[$parentIdKey]; + } else { + $subCategories + = Toolkit_Common::arrayFlatten($subCategories, 2); + asort($subCategories); + return $subCategories; + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ toHtml() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @return string The rendered form + * @access public + */ + public function toHtml() + { + // We need to validate (and freeze if needed) + // before we render the form. That way the + // template knows about any errors on the form. + $this->validated = $this->validate(); + + $this->legend + = GLM_TEMPLATE::get_catheader($this->_catid, new GLM_DB()); + + // ProcessData handles settingup the lat/lon coordinates if they were not entered + // into the form. these values ar calculated and then inserted into the forms + // element values. So we need to process the data first and then render the form. + $this->setupRenderers(); + + return $this->template->bufferedOutputObject($this->view); + } + + // }}} + + // {{{ setCatId() + + /** + * set the catid to use in the form + * + * @param integer $catid page catid + * + * @return PEAR Error return a PEAR error if an invalid catid is passed in + * @access public + */ + public function setCatId($catid) + { + if (is_numeric($catid) && ctype_digit((string) $catid)) { + $this->_catid = $catid; + } else { + return PEAR::raiseError('Invalid catid'); + } + } + + // }}} + // {{{ setPageMemberCategories() + + /** + * Relate toolbox categories with main member categories + * + * @return array toolbox -> category relations + * @access public + */ + public function setPageMemberCategories() + { + try { + $categoryToolbox = array(); + $sql = " + SELECT bcm.* + FROM bus_cat_member bcm, category c + WHERE bcm.catid = :catid + AND bcm.memb_type = c.category_id + ORDER BY c.name"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':catid', $this->_catid, PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch()) { + $categoryToolbox[] = $row['memb_type']; + } + + $this->memberCatsAssignedToPage = $categoryToolbox; + + return $categoryToolbox; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ setupRenderers() + + /** + * Sets up the Flexy template + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $renderer =& new HTML_QuickForm_Renderer_Object(true); + + $this->accept($renderer); + + $this->template =& new HTML_Template_Flexy($this->flexyOptions); + + // Make the view a copy of the $this object + // That way we have access to call functions in + // this class from within the template. + $this->view = $this; + $this->view->form = $renderer->toObject(); + $this->template->compile($this->formTemplate); + } + + // }}} +} +?> diff --git a/Toolkit/Members/addressHelp.html b/Toolkit/Members/addressHelp.html new file mode 100644 index 0000000..a143bb0 --- /dev/null +++ b/Toolkit/Members/addressHelp.html @@ -0,0 +1,10 @@ +

    My business is not in the correct spot in Google Maps.
    What can I do?

    + +

    Google provides the tools needed for placing your business correctly on their maps. +Visit this page: http://www.google.com/lbc

    +

    In addition to your correct location in their maps, you can also add other information pertaining +to your business such as opening hours, services, contact information etc.

    + +

    What is the Latitude/Longitude fields on this page.

    +

    You can use this option to set your lat/long information for the Google Maps on this site only.

    +

    Once your location is displaying right from the Google Local Business Center, you can remove numbers in these fields.

    diff --git a/Toolkit/Members/export-images-is0.php b/Toolkit/Members/export-images-is0.php new file mode 100755 index 0000000..34bb34a --- /dev/null +++ b/Toolkit/Members/export-images-is0.php @@ -0,0 +1,81 @@ + + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: export-images-is0.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see References to other sections (if any)... + */ + +/** + * setup file + */ +require_once '../../setup.phtml'; + +/** + * Image Server API + */ +require_once BASE.'Toolkit/Image/Server.php'; + +$db = new PDO('pgsql:'.CONN_STR); + +/** + * Description for define + */ +define('OLDORG', 'http://demo.gaslightmedia.com/images/member_original/'); +$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); +$sql = " + SELECT member_id, logo + FROM member + WHERE logo != '' + AND logo not like 'is%' + ORDER BY member_id"; +try { + $stmt = $db->query($sql); + $data = $stmt->fetchAll(PDO::FETCH_ASSOC); + echo '
    ';
    +    print_r($data);
    +    echo '
    '; +} catch(PDOException $e) { + die($e->getMessage()); +} +$db->beginTransaction(); +$IServer = new Toolkit_Image_Server(); +if (is_array($data)) { + $prep2 = " + UPDATE member + SET logo = :image + WHERE member_id = :id"; + $stmt3 = $db->prepare($prep2); + + foreach ($data as &$row) { + $row['logo'] = trim($row['logo']); + var_dump(OLDORG.$row['logo']); + if (!ereg("^is", $row['logo'])) { + $image_URL = OLDORG.urlencode($row['logo']); + $image = $IServer->imageUpload($image_URL); + if ($image) { + try { + $stmt3->bindParam(":image", $image, PDO::PARAM_STR); + $stmt3->bindParam(":id", $row['member_id'], PDO::PARAM_INT); + $stmt3->execute(); + } catch(PDOException $e) { + die($e->getMessage()); + } + } + echo '
    Image Name Returned: '; + var_dump($image); + } + } +} +//$db->commit(); +$db->rollBack(); +?> diff --git a/Toolkit/Members/libjs/authorizeChanges.js b/Toolkit/Members/libjs/authorizeChanges.js new file mode 100644 index 0000000..9d545f3 --- /dev/null +++ b/Toolkit/Members/libjs/authorizeChanges.js @@ -0,0 +1,34 @@ +/** + * setup fckeditor for any textarea field that might exists on the page. + */ +var AuthorizeChanges = +{ + baseUrl: null, + + init: function() + { + AuthorizeChanges.baseUrl = location.protocol + '//' + location.hostname + '/'; + + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + AuthorizeChanges.baseUrl += urlParts[1] + '/'; + } else if (location.hostname == 'kanga.acrewoods.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + AuthorizeChanges.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } + + $('textarea').each(function(t) { + var id = $(this).attr('id'); + if (id != null) { + var oFCKeditor = new FCKeditor(id); + oFCKeditor.BasePath = AuthorizeChanges.baseUrl + 'fckeditor/'; + oFCKeditor.ToolbarSet = 'LimitedToolset'; + oFCKeditor.ReplaceTextarea(); + } + }); + } +} + +$(document).ready(AuthorizeChanges.init); diff --git a/Toolkit/Members/libjs/business-detail.js b/Toolkit/Members/libjs/business-detail.js new file mode 100755 index 0000000..d562cd1 --- /dev/null +++ b/Toolkit/Members/libjs/business-detail.js @@ -0,0 +1,80 @@ +var GDirs = +{ + baseUrl: null, + dBox: null, + originalText: null, + addyBox: null, + + init: function() + { + GDirs.baseUrl = location.protocol + '//' + location.hostname + '/'; + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + GDirs.baseUrl += urlParts[1] + '/'; + } else if (location.hostname == 'kanga.acrewoods.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + GDirs.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } + + GDirs.addyBox = $('#toaddress'); + GDirs.originalText = GDirs.addyBox.val(); + GDirs.dBox = $('#google-div'); + GDirs.dBox.before(' Directions '); + GDirs.dBox.hide(); + $('#google-map-link').bind('click', GDirs.toggleBox); + $('#GDirs').bind('submit', GDirs.submitForm); + GDirs.addyBox.bind('focus', GDirs.clearForm); + GDirs.addyBox.bind('blur', GDirs.fillForm); + }, + + toggleBox: function(event) + { + event.preventDefault(); + GDirs.dBox.slideToggle('normal'); + }, + + submitForm: function(event) + { + if (GDirs.addyBox.val() == GDirs.originalText || GDirs.addyBox.val() == '') { + event.preventDefault(); + alert('Please fill in your Address'); + } + }, + + clearForm: function(event) + { + if (GDirs.addyBox.val() == GDirs.originalText) { + GDirs.addyBox.val(''); + } + }, + + fillForm: function(event) + { + if (GDirs.addyBox.val() == '') { + GDirs.addyBox.val(GDirs.originalText); + } + } +}; + +var Imgs = +{ + init: function() + { + $('.member-img-s').bind('click', Imgs.updateImage); + }, + + updateImage: function(event) + { + $(this).effect('transfer', {to: "#member-img-1"}, 300); + $(this).queue(function() { + $('#member-img-1').attr('src', $(this).attr('id')); + $('#photo-caption').text($(this).attr('alt')); + $(this).dequeue(); + }); + } +}; + +$(document).ready(GDirs.init); +$(document).ready(Imgs.init); diff --git a/Toolkit/Members/libjs/business-search.js b/Toolkit/Members/libjs/business-search.js new file mode 100644 index 0000000..9135489 --- /dev/null +++ b/Toolkit/Members/libjs/business-search.js @@ -0,0 +1,208 @@ +var Search = +{ + // {{{ properties + + catSelected: false, + subCatSelected: false, + + // }}} + // {{{ init() + + init: function() + { + $(".t-list-link").bind("click", function(){ + var href = $(this).attr('href'); + $(this).attr('href', href + '&pageOffset=' + window.pageYOffset); + }); + + $('.search-result-item') + .bind('mouseover', Search.highlightMember) + .bind('mouseout', Search.lowlightMember) + .bind('click', Search.goToMember); + + $("select[name='category_id']") + .bind('change', Search.populateMemberSubType); + $("select[name='city_id']") + .bind('change', Search.repopulateCategories); + + Search.setGET(); + if (window.location.GET["_qf__SearchForm"] == '') { + Search.repopulateCategories(); + Search.populateMemberSubType(); + } + }, + + // }}} + // {{{ setGET() + + setGET: function() + { + var get=(""+location.search).substring(1).split("&"); + window.location.GET = new Array(); + for (var i in get) { + var temp = get[i].split("="); + window.location.GET[temp[0]]=temp.splice(1, temp.length-1).join("="); + } + }, + + // }}} + // {{{ highlightMember() + + highlightMember: function(event) + { + if ($(this).find("a[title='More Info']").length) { + $(this).addClass('search-result-item-on'); + } + }, + + // }}} + // {{{ lowlightMember() + + lowlightMember: function(event) + { + if ($(this).find("a[title='More Info']").length) { + $(this).removeClass('search-result-item-on'); + } + }, + + // }}} + // {{{ goToMember() + + goToMember: function(event) + { + if ($(this).find("a[title='More Info']").length) { + var link = $(this).find("a[title='More Info']"); + document.location.href = link.attr('href'); + } + }, + + // }}} + // {{{ repopulateCategories() + + /** + * repopulate the sub category box based on the the value + * selected in the city box + * + * if no city was selected, then get all main categories available + * + * if a city was selected, then get all main categories available in that + * city. + */ + repopulateCategories: function(event) + { + var city = $("select[name='city_id'] option:selected").val(); + + $("select[name='category_id'], select[name='sub_category_id']") + .empty() + .append(''); + + if (city == '') { + var usedValues = Array(); + jQuery.each(CityCats, function(id, obj) { + if (CityCats[id]) { + jQuery.each(CityCats[id], function(i, j) { + if (!usedValues[i]) { + usedValues[i] = true; + var cat = mainCats[i]; + $("select[name='category_id']") + .append(''); + } + }); + } + }); + } else { + jQuery.each(CityCats[city], function(id, obj) { + if (CityCats[city]) { + var cat = mainCats[id]; + $("select[name='category_id']") + .append(''); + } + }); + } + + // If only one option is available, default to have it selected. + if ($("select[name='category_id'] option").length == 2) { + $("select[name='category_id'] option:last-child") + .attr('selected', 'selected'); + // need to repopulate the sub cats, b/c we already know what + // the selected cat is. + Search.populateMemberSubType(false); + } + + // Figure out wich category we need to set as the selected value + var category_id = window.location.GET['category_id']; + if (parseInt(category_id) != 'NaN') { + if (!Search.catSelected) { + Search.catSelected = true; + $("select[name='category_id'] option[value='"+category_id+"']").attr('selected', 'selected'); + } + } + }, + + // }}} + // {{{ populateMemberSubType() + + /** + * repopulate the sub category box based on the the value + * selected in the main category box + * + * if no city was selected, then get all sub categories available + * under the main category selected + * + * if a city was selected, then get all sub categories available in that + * city under the main category selected. + */ + populateMemberSubType: function(event) + { + var city = $("select[name='city_id'] option:selected").val(); + var cat = $("select[name='category_id'] option:selected").val(); + + $("select[name='sub_category_id']") + .empty() + .append(''); + + var usedValues = Array(); + if (city == '') { + jQuery.each(CityCats, function(id, obj) { + if (CityCats[id][cat]) { + jQuery.each(CityCats[id][cat], function(i, j) { + if (!usedValues[i]) { + usedValues[i] = true; + $("select[name='sub_category_id']") + .append(''); + } + }); + } + }); + } else { + jQuery.each(CityCats[city], function(key, obj) { + jQuery.each(CityCats[city][cat], function(i, j) { + if (!usedValues[i]) { + usedValues[i] = true; + $("select[name='sub_category_id']") + .append(''); + } + }); + }); + } + + // If only one option is available, default to have it selected. + if ($("select[name='sub_category_id'] option").length == 2) { + $("select[name='sub_category_id'] option:last-child") + .attr('selected', 'selected'); + } + + // Figure out wich sub category we need to set as the selected value + var sub_category_id = window.location.GET['sub_category_id']; + if (parseInt(sub_category_id) != 'NaN') { + if (!Search.subCatSelected && event != false) { + Search.subCatSelected = true; + $("select[name='sub_category_id'] option[value='"+sub_category_id+"']").attr('selected', 'selected'); + } + } + } + + // }}} +}; + +$(document).ready(Search.init); diff --git a/Toolkit/Members/libjs/edit-amenity.js b/Toolkit/Members/libjs/edit-amenity.js new file mode 100644 index 0000000..6aa77e4 --- /dev/null +++ b/Toolkit/Members/libjs/edit-amenity.js @@ -0,0 +1,19 @@ +/** + * When we are adding an amenity we want to focus on the first text field + * of the form. + */ +var MemberAmenity = +{ + init: function() + { + // Find a member id in the search params, this will let us know we + // are editing a member and then we don't want to focus on the + // the first field. + var idRegExp = /.*(\?|&)id=\d+.*$/g; + if (!idRegExp.test(location.search)) { + $('form :input:text:visible:enabled:first').focus(); + } + } +} + +$(document).ready(MemberAmenity.init); diff --git a/Toolkit/Members/libjs/edit-category.js b/Toolkit/Members/libjs/edit-category.js new file mode 100644 index 0000000..5a3a83b --- /dev/null +++ b/Toolkit/Members/libjs/edit-category.js @@ -0,0 +1,19 @@ +/** + * When we are adding a category we want to focus on the first text field + * of the form. + */ +var MemberCategory = +{ + init: function() + { + // Find a member id in the search params, this will let us know we + // are editing a member and then we don't want to focus on the + // the first field. + var idRegExp = /.*(\?|&)id=\d+.*$/g; + if (!idRegExp.test(location.search)) { + $('form :input:text:visible:enabled:first').focus(); + } + } +} + +$(document).ready(MemberCategory.init); diff --git a/Toolkit/Members/libjs/edit-city.js b/Toolkit/Members/libjs/edit-city.js new file mode 100644 index 0000000..98c9fc9 --- /dev/null +++ b/Toolkit/Members/libjs/edit-city.js @@ -0,0 +1,43 @@ +/** + * When adding a city, set the focus to the first text field in the form + * after the page loads. + * + * setup the fckeditor for the textarea fields + */ +var MemberCity = +{ + baseUrl: null, + + init: function() + { + // Find a member id in the search params, this will let us know we + // are editing a member and then we don't want to focus on the + // the first field. + var idRegExp = /.*(\?|&)id=\d+.*$/g; + if (!idRegExp.test(location.search)) { + $(":text:visible:enabled:first").focus(); + } + + MemberCity.baseUrl = location.protocol + '//' + location.hostname + '/'; + + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + MemberCity.baseUrl += urlParts[1] + '/'; + } else if (location.hostname == 'kanga.acrewoods.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + MemberCity.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } + if ($('#description')) { + var oFCKeditor = new FCKeditor('description'); + oFCKeditor.BasePath = MemberCity.baseUrl + 'fckeditor/'; + oFCKeditor.ToolbarSet = 'LimitedToolset'; + oFCKeditor.Width = 367; + oFCKeditor.Height = 250; + oFCKeditor.ReplaceTextarea(); + } + } +} + +$(document).ready(MemberCity.init); \ No newline at end of file diff --git a/Toolkit/Members/libjs/edit-html-email.js b/Toolkit/Members/libjs/edit-html-email.js new file mode 100644 index 0000000..ff921eb --- /dev/null +++ b/Toolkit/Members/libjs/edit-html-email.js @@ -0,0 +1,47 @@ +/** + * When adding a city, set the focus to the first text field in the form + * after the page loads. + * + * setup the fckeditor for the textarea fields + */ +var HtmlEmail = +{ + baseUrl: null, + + init: function() + { + // Find a member id in the search params, this will let us know we + // are editing a member and then we don't want to focus on the + // the first field. + var idRegExp = /.*(\?|&)id=\d+.*$/g; + if (!idRegExp.test(location.search)) { + $(":text:visible:enabled:first").focus(); + } + + HtmlEmail.baseUrl = location.protocol + '//' + location.hostname + '/'; + + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + HtmlEmail.baseUrl += urlParts[1] + '/'; + } else if (location.hostname == 'steve.gaslightmedia.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + HtmlEmail.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } else if (location.hostname == 'kanga.acrewoods.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + HtmlEmail.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } + if ($('#response')) { + var oFCKeditor = new FCKeditor('response'); + oFCKeditor.BasePath = HtmlEmail.baseUrl + 'fckeditor/'; + oFCKeditor.ToolbarSet = 'Default'; + oFCKeditor.Width = 600; + oFCKeditor.Height = 500; + oFCKeditor.ReplaceTextarea(); + } + } +} + +$(document).ready(HtmlEmail.init); diff --git a/Toolkit/Members/libjs/edit-member-amenities.js b/Toolkit/Members/libjs/edit-member-amenities.js new file mode 100644 index 0000000..f696ac5 --- /dev/null +++ b/Toolkit/Members/libjs/edit-member-amenities.js @@ -0,0 +1,21 @@ +var MemberAmenity = +{ + init: function() + { + $('label').each(function() { + $(this).hover(MemberAmenity.highlight, MemberAmenity.lowlight); + }); + }, + + highlight: function(event) + { + $(this).addClass('amenityOn'); + }, + + lowlight: function(event) + { + $(this).removeClass('amenityOn'); + } +} + +$(document).ready(MemberAmenity.init); diff --git a/Toolkit/Members/libjs/edit-member-contacts.js b/Toolkit/Members/libjs/edit-member-contacts.js new file mode 100644 index 0000000..fdafd2b --- /dev/null +++ b/Toolkit/Members/libjs/edit-member-contacts.js @@ -0,0 +1,67 @@ +var MemberContacts= +{ + baseUrl: null, + + init: function() + { + + MemberContacts.baseUrl = location.protocol + '//' + location.hostname + '/'; + + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + MemberContacts.baseUrl += urlParts[1] + '/'; + } else if (location.hostname == 'kanga.acrewoods.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + MemberContacts.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } + $('.remove').each(function() { + $(this).click(MemberContacts.remove); + $(this).hover(MemberContacts.click, MemberContacts.release); + }); + + $('.contactList').each(function() { + $(this).hover(MemberContacts.mouseOn, MemberContacts.mouseOff); + $(this).click(MemberContacts.goToContact); + }); + }, + + mouseOn: function(event) + { + $(this).addClass('contactListOn'); + }, + + mouseOff: function(event) + { + $(this).removeClass('contactListOn'); + }, + + goToContact: function(event) + { + document.location.href = $(this).find('h3 a').attr('href'); + return false; + }, + + remove: function(event) + { + if (!confirm('Are you sure you wish to remove this contact?\nThis is not reversible!')) { + event.preventDefault(); + } + // Don't propagate so we won't go into the member record + event.stopImmediatePropagation(); + }, + + click: function(event) + { + $(this).children().attr('src', MemberContacts.baseUrl + 'assets/remove_clicked.png'); + }, + + release: function(event) + { + $(this).children().attr('src', MemberContacts.baseUrl + 'assets/remove.png'); + } + +} + +$(document).ready(MemberContacts.init); diff --git a/Toolkit/Members/libjs/edit-member-files.js b/Toolkit/Members/libjs/edit-member-files.js new file mode 100644 index 0000000..87086e5 --- /dev/null +++ b/Toolkit/Members/libjs/edit-member-files.js @@ -0,0 +1,18 @@ +var MemberFiles = +{ + init: function() + { + $('.fileDelete').each(function() { + $(this).click(MemberFiles.remove); + }); + }, + + remove: function(event) + { + if (!confirm('Are you sure you wish to remove this file?\nThis is not reversible!')) { + event.preventDefault(); + } + } +} + +$(document).ready(MemberFiles.init); diff --git a/Toolkit/Members/libjs/edit-member-packages.js b/Toolkit/Members/libjs/edit-member-packages.js new file mode 100755 index 0000000..8f22e5e --- /dev/null +++ b/Toolkit/Members/libjs/edit-member-packages.js @@ -0,0 +1,39 @@ +var MemberPackages = +{ + baseUrl: null, + + init: function() + { + MemberPackages.baseUrl = location.protocol + '//' + location.hostname + '/'; + + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + MemberPackages.baseUrl += urlParts[1] + '/'; + } else if (location.hostname == 'kanga.acrewoods.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + MemberPackages.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } + + if ($('spdescription')) { + var oFCKeditor = new FCKeditor('spdescription'); + oFCKeditor.BasePath = MemberPackages.baseUrl + 'fckeditor/'; + oFCKeditor.ToolbarSet = 'LimitedToolset'; + oFCKeditor.Width = 367; + oFCKeditor.Height = 250; + oFCKeditor.ReplaceTextarea(); + } + + if ($('gdescription')) { + var oFCKeditor = new FCKeditor('gdescription'); + oFCKeditor.BasePath = MemberPackages.baseUrl + 'fckeditor/'; + oFCKeditor.ToolbarSet = 'LimitedToolset'; + oFCKeditor.Width = 367; + oFCKeditor.Height = 250; + oFCKeditor.ReplaceTextarea(); + } + } +} + +Event.observe(window, 'load', MemberPackages.init); diff --git a/Toolkit/Members/libjs/edit-member-photos.js b/Toolkit/Members/libjs/edit-member-photos.js new file mode 100755 index 0000000..7382937 --- /dev/null +++ b/Toolkit/Members/libjs/edit-member-photos.js @@ -0,0 +1,78 @@ +var MemberPhotos = +{ + baseUrl: null, + + init: function() + { + $('.photoDelete').click(MemberPhotos.remove); + + // Get the url we are dealing w/. + MemberPhotos.baseUrl = location.protocol + '//' + location.hostname + '/'; + + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + MemberPhotos.baseUrl += urlParts[1] + '/'; + } else if (location.hostname == 'kanga.acrewoods.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + MemberPhotos.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } + + // Make just the photos uploaded have an additional class + // on them, so we can make them movable later. + $(".photoItem:not(.photoUploadForm)").addClass('movable'); + + // Update the text on the update button. + // Since they have javascript on, the only update + // they will actually do on the form is the caption. + // They won't be updating the position through the select list. + $(":submit[name='update']").val('Update Caption Text'); + + // Remove all the positioning select elemnts + // so they can't override any new position adjustments + // done through drag and drop. + $('.position').remove(); + + // Add a message for users to tell them how to + // reposition thier images. + $('#photoList').before('
    Click and drag images to reorder positions. Image positions are saved when the fields flash yellow
    '); + + $('div.container').sortable({ + placeholder: 'ui-state-highlight', + handle: 'img.thumb', + opacity: 0.6, + revert: true, + scroll: true, + tolerance: 'pointer', + zIndex: 5, +// containment: 'parent', + axis: 'y', + cursor: 'n-resize', + update: MemberPhotos.updatePos + }); + $('img.thumb').disableSelection(); + }, + + updatePos: function(event, ui) + { + // Update the photo positions through AJAX. + $.ajax({ + type: 'GET', + url: MemberPhotos.baseUrl + 'Toolkit/Members/sortPhotos.php', + data: $(this).sortable('serialize'), + success: function(transport) { + $('.movable').effect('highlight', {}, 700); + } + }); + }, + + remove: function(event) + { + if (!confirm('Are you sure you wish to remove this photo?\nThis is not reversible!')) { + event.preventDefault(); + } + } +}; + +$(document).ready(MemberPhotos.init); diff --git a/Toolkit/Members/libjs/edit-member.js b/Toolkit/Members/libjs/edit-member.js new file mode 100755 index 0000000..6e4b8b5 --- /dev/null +++ b/Toolkit/Members/libjs/edit-member.js @@ -0,0 +1,95 @@ +var Member = +{ + baseUrl: null, + categorySelectList: null, + + init: function() + { + // Find a member id in the search params, this will let us know we + // are editing a member and then we don't want to focus on the + // the first field. + var idRegExp = /.*(\?|&)id=\d+.*$/g; + if (!idRegExp.test(location.search)) { + $('form :input:text:visible:enabled:first').focus(); + } + + Member.baseUrl = location.protocol + '//' + location.hostname + '/'; + + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + Member.baseUrl += urlParts[1] + '/'; + } else if (location.hostname == 'kanga.acrewoods.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + Member.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } + + var meals = ['breakfast', 'brunch', 'lunch', 'dinner']; + jQuery.each(meals, function(i, j) { + $('#edit_member input[name='+j+']:checkbox').click(Member.toggleMealView); + $('#edit_member input[name='+j+']:checkbox:not(:checked)').parents('tr').next().toggle().next().toggle(); + }); + + $('.tooltip').cluetip({ + // character to split title text from body text + splitTitle: '`', + // show arrow on cluetip + arrows: true, + // hide cluetip on mouseout + mouseOutClose: true, + // track mouse movements + tracking: true, + // keep z index above all other elements on the page + cluezIndex: 10000, + // effect to open cluetip with + fx: {open: 'fadeIn'} + }); + + if (Member.categorySelectList = $('#categories')) { + Member.categorySelectList.after(''); + $('#addCat').click(Member.addCategory); + } + + if ($('#description')) { + var oFCKeditor = new FCKeditor('description'); + oFCKeditor.BasePath = Member.baseUrl + 'fckeditor/'; + oFCKeditor.ToolbarSet = 'LimitedToolset'; + oFCKeditor.ReplaceTextarea(); + } + }, + + addCategory: function(event) + { + // Don't allow insertion of the -- Choose Category -- option. + if (Member.categorySelectList.get(0).selectedIndex == 0) { + return; + } + var catid = Member.categorySelectList.get(0).value; + $('#edit_member').prepend(''); + + var index = Member.categorySelectList.get(0).selectedIndex; + var category = Member.categorySelectList.get(0).options[index].innerHTML; + var d = new Date(); + var id = d.getTime() + var i = '' + + category + ''; + $(this).parents('i').before(i); + Member.categorySelectList.get(0).selectedIndex = 0; + }, + + removeCategory: function(event) + { + event.stop(); + $('catid' + this.readAttribute('rel')).remove(); + this.up().remove(); + }, + + toggleMealView: function(event) + { + $(this).parents('tr').next().toggle().next().toggle(); + } +}; + +$(document).ready(Member.init); diff --git a/Toolkit/Members/libjs/edit-region.js b/Toolkit/Members/libjs/edit-region.js new file mode 100644 index 0000000..5c7f59a --- /dev/null +++ b/Toolkit/Members/libjs/edit-region.js @@ -0,0 +1,19 @@ +/** + * When we are adding an region we want to focus on the first text field + * of the form. + */ +var MemberRegion = +{ + init: function() + { + // Find a member id in the search params, this will let us know we + // are editing a member and then we don't want to focus on the + // the first field. + var idRegExp = /.*(\?|&)id=\d+.*$/g; + if (!idRegExp.test(location.search)) { + $('form :input:text:visible:enabled:first').focus(); + } + } +} + +$(document).ready(MemberRegion.init); diff --git a/Toolkit/Members/libjs/list-categories.js b/Toolkit/Members/libjs/list-categories.js new file mode 100644 index 0000000..97e3bb8 --- /dev/null +++ b/Toolkit/Members/libjs/list-categories.js @@ -0,0 +1,50 @@ +var Tree = +{ + init: function() + { + Tree.insertGlobalFunctions(); + + tree1 = new tree_component(); + tree1.init($("#categoryTree"), { + cookies : { + prefix : "tree1", + opts : { path : '/' } + }, + ui : { + animation : 500 + } + }); + + $('#categoryTree a').bind('click', Tree.editNode); + }, + + insertGlobalFunctions: function() + { + $('#categoryTree').before('
    ' + + '' + + '' + + '
    '); + + $('.expandAll').bind('click', Tree.expandAll); + $('.collapseAll').bind('click', Tree.collapseAll); + }, + + expandAll: function(event) + { + $('li.closed').toggleClass('open'); + $('li.closed').toggleClass('closed'); + }, + + collapseAll: function (event) + { + $('li.open').toggleClass('closed'); + $('li.open').toggleClass('open'); + }, + + editNode: function(event) + { + location.href = $(this).attr('href'); + } +}; + +$(document).ready(Tree.init); diff --git a/Toolkit/Members/libjs/member-list.js b/Toolkit/Members/libjs/member-list.js new file mode 100644 index 0000000..76d727d --- /dev/null +++ b/Toolkit/Members/libjs/member-list.js @@ -0,0 +1,76 @@ +var MemberList = +{ + baseUrl: null, + + init: function() + { + $('.searchResult').each(function() { + $(this).hover(MemberList.mouseOn, MemberList.mouseOff); + $(this).click(MemberList.goToMember); + }); + + $('.remove').each(function() { + $(this).click(MemberList.remove); + $(this).hover(MemberList.click, MemberList.release); + }); + + MemberList.baseUrl = location.protocol + '//' + location.hostname + '/'; + + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + MemberList.baseUrl += urlParts[1] + '/'; + } else if (location.hostname == 'kanga.acrewoods.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + MemberList.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } + + $('#record_search').after('Advanced Search'); + $('#advanced_search').click(MemberList.toggleAdvancedSearch); + $('#advanced_search').trigger('click'); + }, + + toggleAdvancedSearch: function(event) + { + event.preventDefault(); + $('#record_search tr').slice(4,8).toggle(); + }, + + mouseOn: function(event) + { + $(this).addClass('searchResultOn'); + }, + + mouseOff: function(event) + { + $(this).removeClass('searchResultOn'); + }, + + goToMember: function(event) + { + document.location.href = $(this).find('h3 a').attr('href'); + return false; + }, + + remove: function(event) + { + if (!confirm('Are you sure you wish to remove this business?\nThis is not reversible!')) { + event.preventDefault(); + } + // Don't propagate so we won't go into the member record + event.stopImmediatePropagation(); + }, + + click: function(event) + { + $(this).children().attr('src', MemberList.baseUrl + 'assets/remove_clicked.png'); + }, + + release: function(event) + { + $(this).children().attr('src', MemberList.baseUrl + 'assets/remove.png'); + } +}; + +$(document).ready(MemberList.init); diff --git a/Toolkit/Members/libjs/member-pending-list.js b/Toolkit/Members/libjs/member-pending-list.js new file mode 100644 index 0000000..2f0789a --- /dev/null +++ b/Toolkit/Members/libjs/member-pending-list.js @@ -0,0 +1,42 @@ +var MemberPendingList = +{ + baseUrl : null, + + init: function() + { + $('.searchResult').each(function() { + $(this).hover(MemberPendingList.mouseOn, MemberPendingList.mouseOff); + $(this).click(MemberPendingList.goToMember); + }); + + MemberPendingList.baseUrl = location.protocol + '//' + location.hostname + '/'; + + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + MemberPendingList.baseUrl += urlParts[1] + '/'; + } else if (location.hostname == 'kanga.acrewoods.com') { + var site = location.pathname.split('/'); + var urlParts = url.split('/'); + MemberPendingList.baseUrl += urlParts[1] + '/' + site[2] + '/'; + } + }, + + mouseOn: function(event) + { + $(this).addClass('searchResultOn'); + }, + + mouseOff: function(event) + { + $(this).removeClass('searchResultOn'); + }, + + goToMember: function(event) + { + document.location.href = $(this).find('h3 a').attr('href'); + return false; + } +} + +$(document).ready(MemberPendingList.init); diff --git a/Toolkit/Members/memberClickThru.php b/Toolkit/Members/memberClickThru.php new file mode 100644 index 0000000..7b9f5d7 --- /dev/null +++ b/Toolkit/Members/memberClickThru.php @@ -0,0 +1,29 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: memberClickThru.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link <> + */ + +$dont_include_functions = true; +/** + * Description for require_once + */ +require_once '../../setup.phtml'; +if (is_numeric($_GET['member_id'])) { + $exposure = new Toolkit_Members_Exposure($_GET['member_id'], 'click'); +} +if ($_GET['href']) { + $href = str_replace("http://", "", $_GET['href']); + header("Location: http://" . $href); +} +?> diff --git a/Toolkit/Members/memberFileDownload.php b/Toolkit/Members/memberFileDownload.php new file mode 100644 index 0000000..a594e26 --- /dev/null +++ b/Toolkit/Members/memberFileDownload.php @@ -0,0 +1,32 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: memberFileDownload.php,v 1.2 2009/12/15 20:18:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ +$dont_include_functions = true; + +/** + * Description for require_once + */ +require_once '../../setup.phtml'; + +$download = new Toolkit_Members_FileDownload( + Toolkit_Database::getInstance() +); +$file = $download->getFile($_GET['mid'], $_GET['fid']); + +if (!PEAR::isError($file)) { + $download->sendFileToBrowser($file); +} else { + exit(); +} +?> diff --git a/Toolkit/Members/memberdb-session.sql b/Toolkit/Members/memberdb-session.sql new file mode 100644 index 0000000..5d159b0 --- /dev/null +++ b/Toolkit/Members/memberdb-session.sql @@ -0,0 +1,8 @@ +CREATE TABLE member_session( +id SERIAL PRIMARY KEY, +member_id int REFERENCES member ON DELETE CASCADE, +contact_id int REFERENCES contact ON DELETE CASCADE, +catid int REFERENCES bus_category ON DELETE CASCADE +); + +GRANT ALL ON member_session to nobody; diff --git a/Toolkit/Members/memberdb.css b/Toolkit/Members/memberdb.css new file mode 100644 index 0000000..3ef3869 --- /dev/null +++ b/Toolkit/Members/memberdb.css @@ -0,0 +1,410 @@ +/* + +h1 { + font-size: 16px; + } +#content { + margin: 0px; +} +#subnavcontainer, #navcontainer, +#top { + margin-right: 0px; +} +#wrapper { + width: 700px; + margin: 0 auto; + text-align: left; + background: white; + padding: 20px; + height: 1%; + overflow: hidden; + } +Above is only for template , DISREGARD :) */ +#advanced-search { + text-align: right; + cursor: pointer; + color: blue; +} +.req { + color: red; +} +#form-warning-top { + color: black; + font-size: 110%; + font-weight: bold; + margin: 10px; + padding: 7px; + border: 1px solid red; + background-color: #FFCCCC; +} +#form-success-top { + color: black; + font-size: 110%; + font-weight: bold; + margin: 10px; + padding: 7px; + border: 1px solid green; + background-color: #CCFFCC; +} + +img { + border: 0; + display: block; + } +/* --------------- */ +/* NAVIGATION */ +/* --------------- */ +#nav-detail { + margin-top: 12px; + height: 1%; + overflow: hidden; + clear: left; + } +#nav-detail ul { + padding: 0px 0; + padding-bottom: 3px; + margin: 0; + margin-top: 10px; + border-bottom: 1px solid #666; + font-weight: bold; +} +#nav-detail ul li { + list-style: none; + margin: 0; + display: inline; +} +#nav-detail ul li a { + padding: 3px 0.5em; + margin-left: 3px; + border: 1px solid #666; + border-bottom: none; + background: #E6EFD1; + text-decoration: none; +} +#nav-detail ul li a:link { color: #666; } +#nav-detail ul li a:visited { color: #666; } +#nav-detail ul li a:hover { + color: #666; + background: #ccc; + background: #FFFBDF; + border-color: #666; +} +#nav-detail ul li a.current { + background: white; + border-bottom: 1px solid white; + color: #000; +} + +/* Member Box */ +#member-info { + margin: 0; + border: 1px solid #666; + border-top: 0; + padding: 10px; + position: relative; + height: 1%; + overflow: hidden; + clear: left; + } + +#mRow1 { + float: left; + position: relative; + margin: 0 0 0 10px; + display: inline; + width: 380px; + } +#mRow2 { + float: right; + position: relative; + } +#mRow1 .text { + width: 180px; + } +#mRow2 .text { + width: 150px; + } +.form { + clear: left; + display: block; + position: relative; + margin: 0 0 1em 0; + padding: 0; + border: 0; + } +/* narrower column */ +.formNarrow { + clear: right; + margin: 0 0 1em 0; + } +.form legend { + font-size: 1.2em; + font-weight: bold; + margin: 0; + padding: 0 0 0.4em 0; + color: #000; + } +.form table, +.form td { + border-collapse: collapse; + border: 1px solid #fff; + padding: 0; + background: #D6DFC3; + } +.form td { + padding: 4px 6px; + } +.form label { + display: block; + } +.labelcell { + text-align: right; + width: 120px; + } +.formNarrow .labelcell { + width: 110px; + } +.fieldcell { + text-align: left; + width: 220px; + } +.formNarrow .fieldcell { + width: 150px; + } + +/* Multiple rows in one cell */ +.fieldcell i { + display: block; + font-style: normal; + padding: 5px; + text-align: left; + background-color: #eee; + margin-bottom: 1px; + } +.fieldcell i img { + margin-right: 6px;} + +/* Small graphics */ +.remove { + float: right; + clear: right;} +.add { + display: block; + /* float: right; */ + display: block; + font-style: normal; + padding: 5px; + text-align: left; + background-color: #eee; + margin-bottom: 1px; + } +.add img {float: left; margin-right: 10px;} +.info { + float: right; + } + +.priceFrom, +.priceTo { + width: 4em; + } +.submit {display: block;} + +/* Submit */ +.submitArea { + background: #D6DFC3; + text-align: center; + padding: 10px; + clear: both; + } +.submitArea input { + margin: 0 auto; + display: block; + } + + +/* --------------- */ +/* PHOTOS */ +/* --------------- */ +.photoItem { + margin-top: 1em; + padding: 20px; + border: 1px solid #ccc; + height: 1%; + overflow: hidden; + position: relative; + background: #D6DFC3; + } +.photoItem .thumb { + float: left; + position: relative; + margin-right: 20px; + } +.photoItem i { + font-style: normal; + font-weight: bold; + display: block; + } +.photoItem input {margin-top: 0.5em;} +.photoItem input.text { + width: 400px; + display: block; + } +.photoItem .photoDelete { +/* display: block; + margin-top: 1em; + border: 1px solid #ccc; + background: #FFEFEF; + width: 130px; + padding: 3px; + color: #000; +*/ + position: absolute; + bottom: 20px; + right: 20px; + + } +.photoDelete:hover {background: #EFD1D1;} +.photoItem .photoDelete img { + float: left; + margin-right: 6px; + } +.photoOptions {float: left;} + + +/* --------------- */ +/* PACKAGES */ +/* --------------- */ + +.packageItem { + margin-top: 1em; + padding: 20px; + border: 1px solid #96A379; + height: 1%; + overflow: hidden; + position: relative; + background: #D6DFC3; + } + +.packageItem .thumb { + position: relative; + margin-bottom: 1em; + } +.packageText { + float: left; + width: 350px; + padding-bottom: 1em; + } +.packageItem i { + font-style: normal; + font-weight: bold; + display: block; + padding-top: 1em; + + } +.packageItem input {margin-top: 0.5em;} +.packageItem input.text { + width: 200px; + display: block; + } +.packageItem textarea { + width: 300px; + height: 150px; + } +.packageItem .packageDelete { + display: block; + margin-top: 1em; + border: 1px solid #ccc; + background: #FFEFEF; + width: 140px; + padding: 3px; + position: absolute; + bottom: 20px; + right: 20px; + color: #000; + } +.packageDelete:hover {background: #EFD1D1;} +.packageItem .packageDelete img { + float: left; + margin-right: 6px; + } +.packageOptions {float: left;} + + + +/* --------------- */ +/* AMENITIES */ +/* --------------- */ +.amenityList { + list-style-type: none; + float: left; + position: relative; + margin-right: 50px; + zoom: 1; + width: 200px; + } +.amenityList input { + /* No Luck, see http://meyerweb.com/eric/thoughts/2007/05/15/formal-weirdness/ */ +} +.amenityList li { + vertical-align: middle; + height: 1%; + overflow: hidden; + font-size: 1.2em; + } +.amenityList label { + padding: 4px; + display: block; + background: #D6DFC3; + margin-bottom: 1px; +} +.amenityList label.amenityOn { + background-color: #E6EFD1; + cursor: hand; + cursor: pointer; + } + +/* SPECIFIC TO SEARCH RESULT HERE */ +.searchResult { + border: 1px solid #96A379; + padding: 10px 20px; + margin: 5px 0; + background-color: #D6DFC3; + height: 1%; + overflow: hidden; + position: relative; +} +.searchResultOn { + background: url(../../assets/searchResultOn.gif) no-repeat 95% center #E6EFD1; + cursor: hand; + cursor: pointer; +} +.searchResult h3 { + font-size: 15px; + color: #333; + margin: 0; + float: left; +} +.searchResultOn h3 { + color: #000; +} +.searchResult .phone { + position: absolute; + bottom: 10px; + right: 300px; +} +.searchResult a.email { + position: absolute; + bottom: 10px; + right: 150px; +} +.searchResult a { + color: #96A379; + text-decoration: none; +} +.searchResult a.email { + text-decoration: underline; +} +.searchResult a:link {color: #585F47;} +.searchResult a:visited {color: #585F47;} +.searchResult a:hover {color: #585F47;} +.searchResult a:active {color: #585F47;} diff --git a/Toolkit/Members/memberdb.sql b/Toolkit/Members/memberdb.sql new file mode 100644 index 0000000..0374988 --- /dev/null +++ b/Toolkit/Members/memberdb.sql @@ -0,0 +1,390 @@ +CREATE TABLE state ( +state_id serial PRIMARY KEY, +state_name text, +state_abb varchar(2), +us_state boolean default false +); + +DELETE FROM state; +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Alabama', 'AL'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Alaska', 'AK'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Arizona', 'AZ'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Arkansas', 'AR'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'California', 'CA'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Colorado', 'CO'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Connecticut', 'CT'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Delaware', 'DE'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'District of Columbia', 'DC'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Florida', 'FL'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Georgia', 'GA'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Hawaii', 'HI'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Idaho', 'ID'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Illinois', 'IL'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Indiana', 'IN'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Iowa', 'IA'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Kansas', 'KS'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Kentucky', 'KY'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Louisiana', 'LA'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Maine', 'ME'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Maryland', 'MD'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Massachusetts', 'MA'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Michigan', 'MI'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Minnesota', 'MN'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Mississppi', 'MS'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Missouri', 'MO'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Montana', 'MT'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Nebraska', 'NE'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Nevada', 'NV'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'New Hampshire', 'NH'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'New Jersey', 'NJ'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'New Mexico', 'NM'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'New York', 'NY'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'North Carolina', 'NC'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'North Dakota', 'ND'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Ohio', 'OH'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Oklahoma', 'OK'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Oregon', 'OR'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Pennsylvania', 'PA'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Rhode Island', 'RI'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'South Carolina', 'SC'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'South Dakota', 'SD'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Tennessee', 'TN'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Texas', 'TX'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Utah', 'UT'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Vermont', 'VT'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Virginia', 'VA'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Washington', 'WA'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'West Virginia', 'WV'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Wisconsin', 'WI'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (true, 'Wyoming', 'WY'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Alberta', 'AB'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'American Samoa', 'AS'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'British Columbia', 'BC'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Federated States of Micronesia', 'FM'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Guam', 'GU'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Manitoba', 'MB'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Marshall Islands', 'MH'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'New Brunswick', 'NB'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Newfoundland', 'NF'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Northern Mariana Islands', 'MP'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Northwest Territories', 'NT'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Nova Scotia', 'NS'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Ontario', 'ON'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Palau', 'PW'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Prince Edward Island', 'PE'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Puerto Rico', 'PR'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Quebec', 'QC'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Saskatchewan', 'SK'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Virgin Islands', 'VI'); +INSERT INTO state (us_state, state_name, state_abb) VALUES (false, 'Yukon', 'YT'); + +GRANT ALL ON state_state_id_seq TO nobody; +GRANT ALL ON state TO nobody; + +CREATE TABLE region ( +region_id serial PRIMARY KEY, +region_name text UNIQUE +); + +DELETE FROM region; +ALTER SEQUENCE region_region_id_seq RESTART WITH 1; +INSERT INTO region (region_name) VALUES ('Temp Region'); + +GRANT ALL ON region_region_id_seq TO nobody; +GRANT ALL ON region TO nobody; + +CREATE TABLE county ( +county_id serial PRIMARY KEY, +state_id integer REFERENCES state(state_id) ON DELETE CASCADE, +county_name text, +region_id integer REFERENCES region(region_id) ON DELETE CASCADE +); + +DELETE FROM county; +ALTER SEQUENCE county_county_id_seq RESTART WITH 1; +INSERT INTO county(state_id, county_name, region_id) VALUES (1, 'Temp County', 1); + +GRANT ALL ON county_county_id_seq TO nobody; +GRANT ALL ON county TO nobody; + +CREATE TABLE city ( +city_id serial PRIMARY KEY, +state_id integer REFERENCES state(state_id) ON DELETE CASCADE, +city_name text, +county_id integer REFERENCES county(county_id) ON DELETE CASCADE, +region_id integer REFERENCES region(region_id) ON DELETE CASCADE, +description text, +image text +); + +DELETE FROM city; +ALTER SEQUENCE city_city_id_seq RESTART WITH 1; +INSERT INTO city (state_id, city_name, county_id, region_id) VALUES (1, 'Temp City', 1, 1); + +GRANT ALL ON city_city_id_seq TO nobody; +GRANT ALL ON city TO nobody; + +CREATE TABLE member ( +member_id serial primary key, +member_name text UNIQUE, +member_login text UNIQUE, +member_passwd text, +street text, +lat double precision, +lon double precision, +country text, +phone text, +fax text, +process_email text, +url text, +city text, +city_id integer references city(city_id) ON DELETE SET NULL, +state text, +state_id integer references state(state_id) ON DELETE SET NULL, +description text, +create_date date DEFAULT now(), +zip text, +toll_free text, +member_contact_email text, +spotlight boolean, +logo text, +mailing_address text, +primary_contact text, +primary_contact_fname text, +primary_contact_lname text, +active boolean default false, +mailing_city text, +mailing_city_id integer references city(city_id) ON DELETE SET NULL, +mailing_state_id integer references state(state_id) ON DELETE SET NULL, +mailing_zip text, +join_date date +region integer references region(region_id) ON DELETE SET NULL, +new_member boolean default false, +facebook text, +twitter text, +myspace text, +linkedin text, +blog text +); + +GRANT ALL ON member_member_id_seq TO nobody; +GRANT ALL ON member TO nobody; + +CREATE TABLE member_accommodations ( +id serial PRIMARY KEY, +reservation_id text, +num_rooms integer, +year_round boolean default false, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE +); + +GRANT ALL ON member_accommodations_id_seq TO nobody; +GRANT ALL ON member_accommodations TO nobody; + +CREATE TABLE amenity ( +amenity_id serial PRIMARY KEY, +amenity_name text, +amenity_icon text, +display_form boolean +); + +GRANT ALL ON amenity_amenity_id_seq TO nobody; +GRANT ALL ON amenity TO nobody; + +CREATE TABLE member_amenity ( +member_amenity_id serial PRIMARY KEY, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE, +amenity_id integer REFERENCES amenity(amenity_id) ON DELETE CASCADE +); + +GRANT ALL ON member_amenity_member_amenity_id_seq TO nobody; +GRANT ALL ON member_amenity TO nobody; + +CREATE TABLE category ( +category_id serial PRIMARY KEY, +name text NOT NULL, +parent_id integer DEFAULT 0, +pos integer DEFAULT 1, +accommodations boolean default false, +restaurant boolean default false, +golf boolean default false, +code integer +); + +DELETE FROM category; +ALTER SEQUENCE category_category_id_seq RESTART WITH 1; +INSERT INTO category (name, parent_id, pos, accommodations, restaurant, golf) VALUES ('Parent', 0, 1, true, true, true); +INSERT INTO category (name, parent_id, pos, accommodations, restaurant, golf) VALUES ('Child', 1, 1, false, false, false); +INSERT INTO category (name, parent_id, pos, accommodations, restaurant, golf) VALUES ('Sibling', 1, 2, false, true, false); +INSERT INTO category (name, parent_id, pos, accommodations, restaurant, golf) VALUES ('Grand Child', 2, 1, false, false, true); + +GRANT ALL ON category_category_id_seq TO nobody; +GRANT ALL ON category TO nobody; + +CREATE TABLE bus_cat_member( +id serial PRIMARY KEY, +catid integer REFERENCES bus_category(id) ON DELETE CASCADE, +memb_type integer REFERENCES category(id) ON DELETE CASCADE, +prop_type integer +); + +GRANT ALL on bus_cat_member_id_seq to nobody; +GRANT ALL on bus_cat_member to nobody; +CREATE UNIQUE INDEX bus_cat_member_id_index on bus_cat_member (id); +CREATE INDEX bus_cat_member_catid_memb_index on bus_cat_member (catid, memb_type); + +CREATE TABLE member_category ( +member_category_id serial PRIMARY KEY, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE, +category_id integer REFERENCES category(category_id) ON DELETE CASCADE +); + +GRANT ALL ON member_category_member_category_id_seq TO nobody; +GRANT ALL ON member_category TO nobody; + +CREATE TABLE member_ccard_type ( +member_ccard_type_id serial PRIMARY KEY, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE, +ccard_type_id integer REFERENCES ccard_type(ccard_type_id) ON DELETE CASCADE +); + +GRANT ALL ON member_ccard_type_member_ccard_type_id_seq TO nobody; +GRANT ALL ON member_ccard_type TO nobody; + +CREATE TABLE member_contacts ( +id serial PRIMARY KEY, +title text, +fname text NOT NULL, +lname text NOT NULL, +email text, +phone text, +send_mail boolean DEFAULT false, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE +); + +GRANT ALL ON member_contacts_id_seq TO nobody; +GRANT ALL ON member_contacts TO nobody; + +CREATE TABLE member_files ( +id serial PRIMARY KEY, +file_contents text, +create_date date DEFAULT now(), +original_name text NOT NULl, +size integer NOT NULL, +file_name text NOT NULL, +name_on_disk text NOT NULL, +pending boolean DEFAULT true, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE +); + +GRANT ALL ON member_files_id_seq TO nobody; +GRANT ALL ON member_files TO nobody; + +CREATE TABLE member_golf ( +id serial PRIMARY KEY, +par text, +yardage text, +course_rating text, +slope_rating text, +walking_course boolean DEFAULT false, +holes18 text, +holes9 text, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE +); + +GRANT ALL ON member_golf_id_seq TO nobody; +GRANT ALL ON member_golf TO nobody; + +CREATE TABLE member_packages ( +id serial PRIMARY KEY, +title text, +description text, +image text, +type text, +pending boolean DEFAULT true, +pos integer, +sdate date, +edate date, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE +); + +GRANT ALL ON member_packages_id_seq TO nobody; +GRANT ALL ON member_packages TO nobody; + +CREATE TABLE member_photos ( +id serial PRIMARY KEY, +image text NOT NULL, +caption text, +pending boolean DEFAULT true, +pos integer DEFAULT 1, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE +); + +GRANT ALL ON member_photos_id_seq TO nobody; +GRANT ALL ON member_photos TO nobody; + +CREATE TABLE member_restaurants ( +id serial PRIMARY KEY, +breakfast boolean DEFAULT false, +breakfast_from text, +breakfast_to text, +brunch boolean DEFAULT false, +brunch_from text, +brunch_to text, +lunch boolean DEFAULT false, +lunch_from text, +lunch_to text, +dinner boolean DEFAULT false, +dinner_from text, +dinner_to text, +alcohol boolean DEFAULT false, +non_smoking boolean DEFAULT false, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE +); + +GRANT ALL ON member_restaurants_id_seq TO nobody; +GRANT ALL ON member_restaurants TO nobody; + +CREATE TABLE member_updates ( +id serial PRIMARY KEY, +field text, +update text, +alter_time timestamp without time zone DEFAULT now(), +db_table text NOT NULL, +data_type text, +label text, +foreign_key integer, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE, +field_type text +); + +GRANT ALL ON member_updates_id_seq TO nobody; +GRANT ALL ON member_updates TO nobody; + +CREATE TABLE ccard_type ( +ccard_type_id serial PRIMARY KEY, +ccard_type_name text, +ccard_type_icon text +); + +DELETE FROM ccard_type; +ALTER SEQUENCE ccard_type_ccard_type_id_seq RESTART WITH 1; +INSERT INTO ccard_type(ccard_type_name, ccard_type_icon) VALUES ('Visa', 'cardvisa.gif'); +INSERT INTO ccard_type(ccard_type_name, ccard_type_icon) VALUES ('Master Card', 'cardmaster.gif'); +INSERT INTO ccard_type(ccard_type_name, ccard_type_icon) VALUES ('Discover', 'carddiscover.gif'); +INSERT INTO ccard_type(ccard_type_name, ccard_type_icon) VALUES ('American Express', 'cardamex.gif'); +INSERT INTO ccard_type(ccard_type_name, ccard_type_icon) VALUES ('Dinner', 'carddinner.gif'); + +GRANT ALL ON ccard_type_ccard_type_id_seq TO nobody; +GRANT ALL ON ccard_type TO nobody; + +CREATE TABLE member_ccard_type ( +member_ccard_type_id serial PRIMARY KEY, +member_id integer REFERENCES member(member_id) ON DELETE CASCADE, +ccard_type_id integer REFERENCES ccard_type(ccard_type_id) ON DELETE SET NULL +); + +GRANT ALL ON member_ccard_type_member_ccard_type_id_seq TO nobody; +GRANT ALL ON member_ccard_type TO nobody; + +\i /usr/share/postgresql/8.2/contrib/tablefunc.sql diff --git a/Toolkit/Members/members.ini b/Toolkit/Members/members.ini new file mode 100644 index 0000000..176f721 --- /dev/null +++ b/Toolkit/Members/members.ini @@ -0,0 +1,47 @@ +; Member Database configuration file +[conf] +; Allow members to have their own coupons. +coupons = On +; Allow regions in the application. +regions = On +; Only allow cities in member records that are added by an admin user. +; Turning on will provide admin with an extra form that will allow them +; to add/edit/remove cities. +; Turning off will allow any city name to be entered when editing member +; records. +controlledCities = On +amenities = On +counties = Off +newMemberRequests = On +; Determines if member changes must be first approved by admin +; before they will be written to their actual record. +strictPending = Off +; Allow duplicate member names in the database +duplicateMembers = Off + +[photos] +; Maximum number of photos a member is allowed to upload per record +maxPhotos = 100 +; Maximum length allowed in text fields for photo captions +maxCaptionLength = 60 +; This is the template when editing / adding photos to a members gallery +; Not to be confused w/ the templates for the add / edit photo forms. +editGalleryTemplate = "editPhotoGallery.tpl" + +; How the app should be displayed (Business, Members, Users, etc...) +; [List Businesses] [Add Business Listing] [Pending Business Listing Update] +; [List Members] [Add Member Listing] [Pending Member Listing Update] +[listing type] +singular = "Member" +plural = "Members" + +; How the regions should be displayed (Regions, Counties, Areas, etc...) +; [Regions] [List Regions] [Add Regions] +; [Counties] [List Counties] [Add Counties] +[region type] +singular = "Regions" +plural = "Region" + +[tables] +pendingTable = "member_updates" +photosTable = "member_photos" diff --git a/Toolkit/Members/sortPhotos.php b/Toolkit/Members/sortPhotos.php new file mode 100644 index 0000000..0939dd1 --- /dev/null +++ b/Toolkit/Members/sortPhotos.php @@ -0,0 +1,54 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: sortPhotos.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +require_once '../../setup.phtml'; +// Make sure the users browser doesn't cache the result. + +// Time in the past. +header('Expires: Wed, 23 Dec 1980 00:30::00 GMT'); +header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); +header('Cache-Control: no-cache, must-revalidate'); +header('Pragma: no-cache'); + +if (!is_array($_GET['photos'])) { + return; +} +$newOrder = $_GET['photos']; + +try { + $dbh->beginTransaction(); + + $sql = " + UPDATE member_photos + SET pos = :pos + WHERE id = :id"; + $stmt = $dbh->prepare($sql); + foreach ($newOrder as $k => &$v) { + $pos = $k + 1; + $stmt->bindParam(':pos', $pos, PDO::PARAM_INT); + $stmt->bindParam(':id', $v, PDO::PARAM_INT); + $stmt->execute(); + } + $dbh->commit(); + echo true; +} catch (PDOException $e) { + $dbh->rollBack(); + echo 'PDO Exception Caught. '; + echo 'Error with the database:
    '; + echo 'Error: ' . $e->getMessage() . '
    '; + echo 'File: ' . $e->getFile() . '
    '; + echo 'Line: ' . $e->getLine() . '
    '; + print_r($dbh->errorInfo()); +} +?> diff --git a/Toolkit/Members/templates/addPackage.tpl b/Toolkit/Members/templates/addPackage.tpl new file mode 100644 index 0000000..aa40473 --- /dev/null +++ b/Toolkit/Members/templates/addPackage.tpl @@ -0,0 +1,41 @@ +
    + {form.javascript:h} + {form.outputHeader():h} + {form.hidden:h} +
    + {form.title.label:h} +
    {form.title.error:h}
    + {form.title.html:h} + {form.description.label:h} +
    {form.description.error:h}
    + {form.description.html:h} + + * + {form.sdate.label:h} + +
    {form.sdate.error:h}
    + {form.sdate.html:h} + + * + {form.edate.label:h} + +
    {form.edate.error:h}
    + {form.edate.html:h} +
    +
    +
    + + + {form.curr_image.label:h} + {form.curr_image.html:h} +
    + {form.image.label:h} +
    {form.image.error:h}
    + {form.image.html:h} +
    +
    {form.add_rmv.html:h}
    + +
    diff --git a/Toolkit/Members/templates/addPhoto.tpl b/Toolkit/Members/templates/addPhoto.tpl new file mode 100644 index 0000000..edad160 --- /dev/null +++ b/Toolkit/Members/templates/addPhoto.tpl @@ -0,0 +1,15 @@ +
    + {form.javascript:h} + {form.outputHeader():h} + {form.hidden:h} +
    + {form.file.label:h} +
    {form.file.error:h}
    + {form.file.html:h} + {form.caption.label:h} +
    {form.caption.error:h}
    + {form.caption.html:h} + {form.submit.html:h} +
    + +
    diff --git a/Toolkit/Members/templates/addYourBusinessAdminEmail.tpl b/Toolkit/Members/templates/addYourBusinessAdminEmail.tpl new file mode 100755 index 0000000..9cdaeb3 --- /dev/null +++ b/Toolkit/Members/templates/addYourBusinessAdminEmail.tpl @@ -0,0 +1,53 @@ + + + + + New Member Notification - {member_name:h} + + +
    + + + + + + + +
    + + + + +
    + + You have a new member + +

    + + {member_name:h} has joined {client_name:h} from your website + +

    + {if:approval_needed} + + Your approval is required to complete this process. +
    + Member administration area +
    + {end:} +
    +
    + + + + +
    + + Please do not reply to this email, it will not go anywhere. +

    + To ensure the delivery of these e-mails to your inbox, please add donotreply@gaslightmedia.com to your e-mail Address Book or Safe List. +
    +
    +
    +
    + + diff --git a/Toolkit/Members/templates/addYourBusinessMemberEmail.tpl b/Toolkit/Members/templates/addYourBusinessMemberEmail.tpl new file mode 100644 index 0000000..0e9e4a0 --- /dev/null +++ b/Toolkit/Members/templates/addYourBusinessMemberEmail.tpl @@ -0,0 +1,57 @@ + + + + + Registration - {client_name:h} + + +
    + + + + +
    + + + + +
    + {if:!approval_needed} + + Your registration is complete + +

    + + Dear {first_name:h},
    + Thanks for joining the {client_name:h} website.
    + Below is the username and password you selected. +

    + Username: {username:h} +
    + Password: {password:h} +

    + Use this to log into your members area. +

    + Sincerely,
    + {client_name:h} +
    + {else:} + + Your registration is pending. + +

    + + Dear {first_name:h},
    + Thanks for joining the {client_name:h} website. +

    + We need to approve your information first. As soon as this is done we will notify you by email. +

    + Sincerely,
    + {client_name:h} +
    + {end:} +
    +
    +
    + + diff --git a/Toolkit/Members/templates/admin.tpl b/Toolkit/Members/templates/admin.tpl new file mode 100644 index 0000000..b990aba --- /dev/null +++ b/Toolkit/Members/templates/admin.tpl @@ -0,0 +1,34 @@ + + + +{title:h} + + + +{foreach:styles,v} + +{end:} +{foreach:scripts,v} + +{end:} + + +
    +
    + + +
    {content:h}
    +
    +
    + + + diff --git a/Toolkit/Members/templates/advancedSearch.tpl b/Toolkit/Members/templates/advancedSearch.tpl new file mode 100644 index 0000000..bb11ae3 --- /dev/null +++ b/Toolkit/Members/templates/advancedSearch.tpl @@ -0,0 +1,44 @@ +
    + {form.javascript:h} + {form.outputHeader():h} + {form.hidden:h} + + {validated():h} +
    + {foreach:form.sections,sec} +
    + {sec.header} + + {foreach:sec.elements,elem} + + + {if:elem.isType(#checkbox#)} + + + {else:} + + + + {end:} + + {end:} +
    {elem.html:h} {elem.label:h} + {if:elem.required} + * + {end:} + {if:elem.error}{end:} + {elem.label} + {if:elem.error}{end:} + + {if:elem.error}
    {end:} + {elem.error} + {if:elem.error}
    {end:} + {elem.html:h} +
    +
    + {end:} +
    +
    + +
    +
    diff --git a/Toolkit/Members/templates/authorizeChanges.tpl b/Toolkit/Members/templates/authorizeChanges.tpl new file mode 100644 index 0000000..2467b32 --- /dev/null +++ b/Toolkit/Members/templates/authorizeChanges.tpl @@ -0,0 +1,46 @@ +
    +

    + Remember to click on the Submit button on the + bottom of the page after doing any changes. +

    + {form.javascript:h} + + {form.outputHeader():h} + {form.hidden:h} + + + {validated():h} +
    +
    + {sec.header} + + + + + + + +
    + {elem.label:h} + +
    {gitem.html:h}
    +
    + + +
    +
    +
    +
    +
    + +
    + +
    diff --git a/Toolkit/Members/templates/currentTables/Element.tpl b/Toolkit/Members/templates/currentTables/Element.tpl new file mode 100644 index 0000000..595457b --- /dev/null +++ b/Toolkit/Members/templates/currentTables/Element.tpl @@ -0,0 +1,14 @@ + + + + * + + + + + +
    {error}
    + + {element} + + diff --git a/Toolkit/Members/templates/currentTables/Form.tpl b/Toolkit/Members/templates/currentTables/Form.tpl new file mode 100644 index 0000000..f59286a --- /dev/null +++ b/Toolkit/Members/templates/currentTables/Form.tpl @@ -0,0 +1,7 @@ +
    + + + {content} +
    + +
    diff --git a/Toolkit/Members/templates/currentTables/Group.tpl b/Toolkit/Members/templates/currentTables/Group.tpl new file mode 100644 index 0000000..cdd24cf --- /dev/null +++ b/Toolkit/Members/templates/currentTables/Group.tpl @@ -0,0 +1,5 @@ + + + {content} + +
    diff --git a/Toolkit/Members/templates/currentTables/GroupElement.tpl b/Toolkit/Members/templates/currentTables/GroupElement.tpl new file mode 100644 index 0000000..1a4ba27 --- /dev/null +++ b/Toolkit/Members/templates/currentTables/GroupElement.tpl @@ -0,0 +1,9 @@ + + + {element} + + * + + {label} + + diff --git a/Toolkit/Members/templates/currentTables/Header.tpl b/Toolkit/Members/templates/currentTables/Header.tpl new file mode 100644 index 0000000..64ac244 --- /dev/null +++ b/Toolkit/Members/templates/currentTables/Header.tpl @@ -0,0 +1,5 @@ + + + {header} + + diff --git a/Toolkit/Members/templates/currentTables/RequiredNote.tpl b/Toolkit/Members/templates/currentTables/RequiredNote.tpl new file mode 100644 index 0000000..525ef33 --- /dev/null +++ b/Toolkit/Members/templates/currentTables/RequiredNote.tpl @@ -0,0 +1 @@ +* Denotes required field diff --git a/Toolkit/Members/templates/editAmenities.tpl b/Toolkit/Members/templates/editAmenities.tpl new file mode 100644 index 0000000..bc6d893 --- /dev/null +++ b/Toolkit/Members/templates/editAmenities.tpl @@ -0,0 +1,42 @@ + +
    + {if:pending} +
    + The yellow colored items are pending approval from the website + administrator.
    Upon approval, your changes will be visible on + the website. +
    + {end:} + {form.javascript:h} + + {form.outputHeader():h} + {form.hidden:h} + + + {validated():h} +

    Edit Amenities

    +

    + Check off any available amenities and click + the submit button on the bottom of the page. +

    + {foreach:form.sections,sec} +
      + {foreach:sec.elements,elem} + {if:fieldPending(elem)} +
    • + {else:} +
    • + {end:} + +
    • + {end:} +
    + {end:} +
    + +
    + +
    diff --git a/Toolkit/Members/templates/editAmenity.tpl b/Toolkit/Members/templates/editAmenity.tpl new file mode 100644 index 0000000..bbea016 --- /dev/null +++ b/Toolkit/Members/templates/editAmenity.tpl @@ -0,0 +1,42 @@ +
    + {form.javascript:h} + {form.outputHeader():h} + {form.hidden:h} + + {validated():h} +
    +
    + {sec.header} + + + + {if:elem.isType(#checkbox#)} + + + {else:} + + + + {end:} + +
    {elem.html:h} {elem.label:h} + * + {if:elem.error}{end:} + {elem.label} + {if:elem.error}{end:} + +
    + {elem.error} +
    + {elem.html:h} +
    +
    +
    +
    + + {if:isEdit()} + + {end:} +
    + +
    diff --git a/Toolkit/Members/templates/editCategory.tpl b/Toolkit/Members/templates/editCategory.tpl new file mode 100644 index 0000000..0ec0eba --- /dev/null +++ b/Toolkit/Members/templates/editCategory.tpl @@ -0,0 +1,42 @@ +
    + {form.javascript:h} + {form.outputHeader():h} + {form.hidden:h} + + {validated():h} +
    +
    + {sec.header} + + + + {if:elem.isType(#checkbox#)} + + + {else:} + + + + {end:} + +
    {elem.html:h} {elem.label:h} + * + {if:elem.error}{end:} + {elem.label} + {if:elem.error}{end:} + + + {elem.error} + + {elem.html:h} +
    +
    +
    +
    + + {if:isEdit()} + + {end:} +
    + +
    diff --git a/Toolkit/Members/templates/editCity.tpl b/Toolkit/Members/templates/editCity.tpl new file mode 100644 index 0000000..f4e975f --- /dev/null +++ b/Toolkit/Members/templates/editCity.tpl @@ -0,0 +1,42 @@ +
    + {form.javascript:h} + {form.outputHeader():h} + {form.hidden:h} + + {validated():h} +
    +
    + {sec.header} + + + + {if:elem.isType(#checkbox#)} + + + {else:} + + + + {end:} + +
    {elem.html:h} {elem.label:h} + * + {if:elem.error}{end:} + {elem.label} + {if:elem.error}{end:} + +
    + {elem.error} +
    + {elem.html:h} +
    +
    +
    +
    + + {if:isEdit()} + + {end:} +
    + +
    diff --git a/Toolkit/Members/templates/editContacts.tpl b/Toolkit/Members/templates/editContacts.tpl new file mode 100644 index 0000000..0fb20fe --- /dev/null +++ b/Toolkit/Members/templates/editContacts.tpl @@ -0,0 +1,56 @@ + +
    +

    Contacts

    + {form.javascript:h} + + {validated():h} + {foreach:form.sections,k,sec} + {if:isForm(k)} +
    + + + {form.outputHeader():h} + {form.hidden:h} + + + + + + + +
    + * + {if:elem.error}{end:} + {elem.label:h} + {if:elem.error}{end:} + + + {elem.error} + + {elem.html:h} +
    +
    + {else:} +
    + + remove + + {foreach:sec.elements,elem} +

    + {elem.html:h} +

    +
    + {elem.html:h} +
    +
    + {elem.html:h} +
    + + {end:} + {getMailIcon(sec):h} +
    + {end:} + {end:} +
    diff --git a/Toolkit/Members/templates/editFile.tpl b/Toolkit/Members/templates/editFile.tpl new file mode 100644 index 0000000..21efdc9 --- /dev/null +++ b/Toolkit/Members/templates/editFile.tpl @@ -0,0 +1,45 @@ + +
    + {if:pending} +
    + The yellow colored items are pending approval from the website + administrator.
    Upon approval, your changes will be visible on + the website. +
    + {end:} +

    Files

    + {form.javascript:h} + + {validated():h} +
    + {form.outputHeader():h} + {form.hidden:h} + + {if:showFile(sec.elements[0])} + {sec.elements[0].html:h} + {end:} +
    + {foreach:sec.elements,elem} + + {if:!elem.isType(#static#)} + {if:elem.isType(#text#)} + {elem.label} + {end:} +
    + {elem.error:h} +
    + {elem.html:h} + {end:} + {end:} +
    + +
    +
    diff --git a/Toolkit/Members/templates/editHtmlEmail.tpl b/Toolkit/Members/templates/editHtmlEmail.tpl new file mode 100644 index 0000000..0c6feef --- /dev/null +++ b/Toolkit/Members/templates/editHtmlEmail.tpl @@ -0,0 +1,42 @@ +
    + {form.javascript:h} + {form.outputHeader():h} + {form.hidden:h} + + {validated():h} +
    +
    + {sec.header} + + + + {if:elem.isType(#checkbox#)} + + + {else:} + + + + {end:} + +
    {elem.html:h} {elem.label:h} + * + {if:elem.error}{end:} + {elem.label} + {if:elem.error}{end:} + +
    + {elem.error} +
    + {elem.html:h} +
    +
    +
    +
    + + {if:isEdit()} + + {end:} +
    + +
    diff --git a/Toolkit/Members/templates/editMember.tpl b/Toolkit/Members/templates/editMember.tpl new file mode 100644 index 0000000..e5b65c4 --- /dev/null +++ b/Toolkit/Members/templates/editMember.tpl @@ -0,0 +1,142 @@ + +
    +
    + The yellow colored items are pending approval from the website + administrator.
    Upon approval, your changes will be visible on + the website. +
    +

    + Remember to click on the Submit button on the + bottom of the page after doing any changes. +

    + {form.javascript:h} + {form.outputHeader():h} + {form.hidden:h} + + + {validated():h} +
    + {foreach:form.sections,sec} + {if:newColumn(sec.header)} +
    +
    + {end:} + {if:inColumn2(sec.header)} +
    + {else:} +
    + {end:} + + {sec.header} + + header == 'Street Address') :?> + Need help with my address + + + {foreach:sec.elements,elem} + {if:fieldPending(elem)} + + {else:} + + {end:} + {if:elem.isType(#textarea#)} + + {else:} + + {if:elem.isType(#checkbox#)} + {if:elem.isName(#active#)} + + + {else:} + + + {end:} + {else:} + + {if:elem.isType(#group#)} + + + {else:} + + + + {end:} + {end:} + {end:} + + {end:} +
    +
    + {elem.error:h} +
    + {elem.html:h} +
    {elem.label:h} {elem.html:h} {elem.html:h} {elem.label:h} + {if:elem.error}{end:} + {elem.label:h} + {if:elem.error}{end:} + +
    + {elem.error:h} +
    + {foreach:elem.elements,gitem} + {if:elem.isName(#city#)} + {gitem.label:h}
    + {end:} + {gitem.html:h} + {if:elem.separator}{elem.separator:h}{end:} + {end:} +
    + * + {if:elem.error}{end:} + {elem.label} + {if:elem.error}{end:} + +
    + {elem.error:h} +
    + {if:addInfoElement(elem.name)} + {if:elem.isName(#street#)} + + {end:} + {if:elem.isName(#member_contact_email#)} + + {end:} + + + + + {end:} + + {if:elem.isName(#member_cats[]#)} + {showCategories():h} + + {end:} + {elem.html:h} + + {if:isCategory(elem.label)} + + {end:} + {if:addInfoElement(elem.label)} + + {end:} +
    +
    + {end:} +
    +
    + +
    + +
    diff --git a/Toolkit/Members/templates/editPackage.tpl b/Toolkit/Members/templates/editPackage.tpl new file mode 100644 index 0000000..712206a --- /dev/null +++ b/Toolkit/Members/templates/editPackage.tpl @@ -0,0 +1,44 @@ +
    + {form.javascript:h} + {form.outputHeader():h} + {form.hidden:h} +
    + {form.title.label:h} +
    {form.title.error:h}
    + {form.title.html:h} + {form.description.label:h} +
    {form.description.error:h}
    + {form.description.html:h} + + * + {form.sdate.label:h} + +
    {form.sdate.error:h}
    + {form.sdate.html:h} + + * + {form.edate.label:h} + +
    {form.edate.error:h}
    + {form.edate.html:h} +
    +
    +
    + + + {form.curr_image.label:h} + {form.curr_image.html:h} +
    + {form.image.label:h} +
    {form.image.error:h}
    + {form.image.html:h} +
    +
    + {form.add_rmv.html:h} + {form.remove_rmv.html:h} +
    + +
    diff --git a/Toolkit/Members/templates/editPackages.tpl b/Toolkit/Members/templates/editPackages.tpl new file mode 100644 index 0000000..a3f41c3 --- /dev/null +++ b/Toolkit/Members/templates/editPackages.tpl @@ -0,0 +1,27 @@ + + +
    + {if:hasPendingPackages} +
    + The yellow colored items are pending approval from the website + administrator.
    Upon approval, your changes will be visible on + the website. +
    + {end:} +

    Packages

    + {uploadForm:h} +
    + {foreach:editForm,i} + {i:h} + {end:} +
    +
    diff --git a/Toolkit/Members/templates/editPhoto.tpl b/Toolkit/Members/templates/editPhoto.tpl new file mode 100644 index 0000000..c71b76e --- /dev/null +++ b/Toolkit/Members/templates/editPhoto.tpl @@ -0,0 +1,24 @@ +{if:pending} +
    +{else:} +
    +{end:} + {form.javascript:h} + {form.outputHeader():h} + {form.hidden:h} +
    + {img_alt:h} +
    +
    + {form.caption.label:h} +
    {form.caption.error:h}
    + {form.caption.html:h} +
    + {form.pos.label:h} + {form.pos.html:h} +
    + {form.update.html:h} + {form.delete.html:h} +
    + +
    diff --git a/Toolkit/Members/templates/editPhotoGallery.tpl b/Toolkit/Members/templates/editPhotoGallery.tpl new file mode 100644 index 0000000..0cae10a --- /dev/null +++ b/Toolkit/Members/templates/editPhotoGallery.tpl @@ -0,0 +1,27 @@ + + +
    + {if:hasPendingPhotos} +
    + The yellow colored items are pending approval from the website + administrator.
    Upon approval, your changes will be visible on + the website. +
    + {end:} +

    Photos

    + {uploadForm:h} +
    + {foreach:editForms,i} + {i:h} + {end:} +
    +
    diff --git a/Toolkit/Members/templates/editRegion.tpl b/Toolkit/Members/templates/editRegion.tpl new file mode 100644 index 0000000..5e35a1b --- /dev/null +++ b/Toolkit/Members/templates/editRegion.tpl @@ -0,0 +1,36 @@ +
    + {form.javascript:h} + {form.outputHeader():h} + {form.hidden:h} + + {validated():h} +
    +
    + {sec.header} + + + + + + +
    + * + {if:elem.error}{end:} + {elem.label} + {if:elem.error}{end:} + + + {elem.error} + + {elem.html:h} +
    +
    +
    +
    + + {if:isEdit()} + + {end:} +
    + +
    diff --git a/Toolkit/Members/templates/emailOwner.tpl b/Toolkit/Members/templates/emailOwner.tpl new file mode 100644 index 0000000..c02814e --- /dev/null +++ b/Toolkit/Members/templates/emailOwner.tpl @@ -0,0 +1,51 @@ + + + + + Member Record update + + +
    + + + + + + + +
    + + + + +
    + + You have a pending member record + +

    + + {member:h} has updated their member record and the changes are waiting your approval. + +

    + + Your approval is required to complete this process. +
    + Member administration area +
    +
    +
    + + + + +
    + + Please do not reply to this email, it will not go anywhere. +

    + To ensure the delivery of these e-mails to your inbox, please add {email:h} to your e-mail Address Book or Safe List. +
    +
    +
    +
    + + diff --git a/Toolkit/Members/templates/exposureDetail.tpl b/Toolkit/Members/templates/exposureDetail.tpl new file mode 100755 index 0000000..de72ffe --- /dev/null +++ b/Toolkit/Members/templates/exposureDetail.tpl @@ -0,0 +1,41 @@ +{if:numberedSet} + +

    {recordSet[0][member_name]}

    + + + + + + + + + + + + + +
    + Month + + Listed + + Details + + Clicks +
    + {row[month]} + + {row[list]} + + {row[detail]} + + {row[click]} +
    +{else:} +
    No reports are available at this time.
    +{end:} diff --git a/Toolkit/Members/templates/exposureList.tpl b/Toolkit/Members/templates/exposureList.tpl new file mode 100755 index 0000000..ed7b253 --- /dev/null +++ b/Toolkit/Members/templates/exposureList.tpl @@ -0,0 +1,51 @@ +

    Exposure Reports

    + Exposure Reports - check the statistics being compiled that include: +

      +
    • Listed - number of times your member record was viewed in search result page
    • +
    • Details - number of time your member profile page was visited
    • +
    • Clicks - number of times your Web site address was clicked on
    • +
    +

    +

    + {exposureForm:h} +{if:numberedSet} + + + + + + + + + + + + + + +
    + Member Name + + Listed + + Details + + Clicks +
    + {row[member_name]:h} + + {row[list]} + + {row[detail]} + + {row[click]} +
    +{else:} +
    No Data For this Month!
    +{end:} diff --git a/Toolkit/Members/templates/listAmenities.tpl b/Toolkit/Members/templates/listAmenities.tpl new file mode 100644 index 0000000..7ad7de1 --- /dev/null +++ b/Toolkit/Members/templates/listAmenities.tpl @@ -0,0 +1,21 @@ + + + + + + + + + + + + + +
    Amenity Name
    + + {v:h}
    diff --git a/Toolkit/Members/templates/listCategories.tpl b/Toolkit/Members/templates/listCategories.tpl new file mode 100644 index 0000000..febf544 --- /dev/null +++ b/Toolkit/Members/templates/listCategories.tpl @@ -0,0 +1,10 @@ + +
    +{tree:h} +
    diff --git a/Toolkit/Members/templates/listCities.tpl b/Toolkit/Members/templates/listCities.tpl new file mode 100644 index 0000000..695c025 --- /dev/null +++ b/Toolkit/Members/templates/listCities.tpl @@ -0,0 +1,21 @@ + + + + + + + + + + + + + +
    City Name
    + + {v:h}
    diff --git a/Toolkit/Members/templates/listHtmlEmails.tpl b/Toolkit/Members/templates/listHtmlEmails.tpl new file mode 100644 index 0000000..e9afa78 --- /dev/null +++ b/Toolkit/Members/templates/listHtmlEmails.tpl @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + +
    SubjectLast Updated
    + + {v[subject]:h}{v[last_update]:h}
    diff --git a/Toolkit/Members/templates/listMembers.tpl b/Toolkit/Members/templates/listMembers.tpl new file mode 100644 index 0000000..2e4b211 --- /dev/null +++ b/Toolkit/Members/templates/listMembers.tpl @@ -0,0 +1,34 @@ +{if:numberedSet} + {showLetters():h} + +
    +
    Sort Alphabetically:
    + {k} +
    + +
    {getResults(#Found %s Businesses in %s pages#):h}
    + {getPaging():h} +

    Showing records {firstRecord} to {lastRecord}

    +
    +
    +
    +
    + + remove + +
    +
    +
    +

    + {row[member_name]:h} +

    +
    P: {row[phone]:h}
    + +
    + {getPaging():h} +{else:} +
    No Members Found!
    +{end:} diff --git a/Toolkit/Members/templates/listNewMembers.tpl b/Toolkit/Members/templates/listNewMembers.tpl new file mode 100644 index 0000000..fc122f0 --- /dev/null +++ b/Toolkit/Members/templates/listNewMembers.tpl @@ -0,0 +1,18 @@ +{if:numberedSet} + {showLetters():h} +
    {getResults(#Found %s Businesses in %s pages#):h}
    + {getPaging():h} +

    Showing records {firstRecord} to {lastRecord}

    + + {getPaging():h} +{else:} +
    No New Members Found!
    +{end:} diff --git a/Toolkit/Members/templates/listPendingMembers.tpl b/Toolkit/Members/templates/listPendingMembers.tpl new file mode 100644 index 0000000..3a530b1 --- /dev/null +++ b/Toolkit/Members/templates/listPendingMembers.tpl @@ -0,0 +1,11 @@ +{if:numberedSet} + +{else:} +
    No Approvals Needed!
    +{end:} diff --git a/Toolkit/Members/templates/listRegions.tpl b/Toolkit/Members/templates/listRegions.tpl new file mode 100644 index 0000000..ba1be3d --- /dev/null +++ b/Toolkit/Members/templates/listRegions.tpl @@ -0,0 +1,21 @@ + + + + + + + + + + + + + +
    Region Name
    + + {v:h}
    diff --git a/Toolkit/Members/templates/memberContactsList.tpl b/Toolkit/Members/templates/memberContactsList.tpl new file mode 100644 index 0000000..6becd04 --- /dev/null +++ b/Toolkit/Members/templates/memberContactsList.tpl @@ -0,0 +1,46 @@ +
    +{memberContactSearchForm:h} +
    +{memberSendForm:h} +{if:numberedSet} +
    {getResults(#Found %s Contacts in %s pages#):h}
    +
    + {getPaging():h} +
    +

    Showing records {firstRecord} to {lastRecord}

    + + + + + + + + + + + + + +
    +   + + Member Name + + First Name + + Last Name +
    + [Edit] + + {row[member_name]:h} + + {row[fname]} + + {row[lname]} +
    +
    + {getPaging():h} +
    +{else:} +
    No Members Found!
    +{end:} diff --git a/Toolkit/Members/templates/memberDetail.tpl b/Toolkit/Members/templates/memberDetail.tpl new file mode 100644 index 0000000..fc2c6e0 --- /dev/null +++ b/Toolkit/Members/templates/memberDetail.tpl @@ -0,0 +1,181 @@ +
    +
    +
    + +
    +
    + + {memberSince:h} + +
    +

    {member_name:h}

    +
    +
    {street:h}
    +
    + {city:h}, + {state_abbr:h} + {zip:h} +
    Phone: {phone:h}
    +
    Toll Free: {toll_free:h}
    +
    Fax: {fax:h}
    + +
    +
    +
    +

    Get Driving Directions:

    + + + +
    +
    +
    +
    +
    +
    + +
    +

    Accommodations Info

    +
      +
    • +
        +
      • Open Year Round
      • +
      • + {num_rooms:h} Rooms +
      • +
      • + Reservations +
      • +
      +
    • +
    +

    Social Media Links

    + +

    Payment Types Accepted

    +
      +
    • +
        +
      • {v:h}
      • +
      +
    • +
    +
    + + + {if:addToLink} + Add to Your Travel List + {else:} + Remove From Your Travel List + {end:} + + +
    {description:h}
    + +
    +
      +
    • {v:h}
    • +
    +
    + +
    +

    Files Available for Download

    + {v[name]:h} +
    + +
    +

    Packages

    + {foreach:packages,v} +

    {v[title]:h}

    + {if:v[image]} + {v[image]:h} + {end:} + + {if:v[description]} + {v[description]:h} + {end:} + {end:} +
    + + + +
    +

    Course Information

    + + + + + + + + + + + + + + + +
    ParYardageCourse RatingSlope Rating
    {par:h}{yardage:h}{course_rating:h}{slope_rating:h}
    +
    + Walking Course: + {walking_course:h} +
    +
    + +
    +

    Restaurant Information

    + + + + + + + + + + + + + + + + + +
    BreakfastBrunchLunchDinnerAlcohol
    {breakfast:h}{brunch:h}{lunch:h}{dinner:h}{alcohol:h}
    +
    +
    diff --git a/Toolkit/Members/templates/memberSearchForm.tpl b/Toolkit/Members/templates/memberSearchForm.tpl new file mode 100644 index 0000000..f3d1c10 --- /dev/null +++ b/Toolkit/Members/templates/memberSearchForm.tpl @@ -0,0 +1,49 @@ + diff --git a/Toolkit/Members/templates/membersList.tpl b/Toolkit/Members/templates/membersList.tpl new file mode 100644 index 0000000..88d949c --- /dev/null +++ b/Toolkit/Members/templates/membersList.tpl @@ -0,0 +1,63 @@ +
    {member_search_form:h}
    + +
    +
    Sort Alphabetically:
    + {k} +
    + +{if:numberedSet} +
    {getResults(#Found %s Businesses in %s page(s)#):h}
    + {getPaging():h} +

    Showing records {firstRecord} to {lastRecord}

    +
    + {if:row[logo]} + {row[logo]} + {end:} + {if:row[addToLink]} + + Add to Your Travel List + + {else:} + + Remove From Your Travel List + + {end:} +

    {row[member_name]:h}

    +
    +
    +
    +
    {row[street]:h}
    + {row[city]:h}, + {row[state_abbr]:h} + {row[zip]:h} +
    +
    +
    Phone: {row[phone]:h}
    +
    +
    +
    + + Online Reservations + + {if:row[num_rooms]} + Number of Rooms: {row[num_rooms]:h} + {end:} +
    + Open Year Round: {row[year_round]:h} +
    + + More Info + +
    +
    + {getPaging():h} + +
    +
    Sort Alphabetically:
    + {k} +
    +{else:} +
    No Members matched your search criteria!
    +{end:} diff --git a/Toolkit/Members/templates/newMemberApproval.tpl b/Toolkit/Members/templates/newMemberApproval.tpl new file mode 100755 index 0000000..e05ca6d --- /dev/null +++ b/Toolkit/Members/templates/newMemberApproval.tpl @@ -0,0 +1,40 @@ + + + + + Registration Complete - {client_name:h} + + +
    + + + + +
    + + + + +
    + + Your registration is complete + +

    + + Dear {first_name:h},
    + Your registration is approved. Below is the username and password you selected. +

    + Username: {member_login:h} +
    + Password: {member_passwd:h} +

    + Use this to log into your members area. +

    + Sincerely,
    + {client_name:h} +
    +
    +
    +
    + + diff --git a/Toolkit/Members/templates/newMemberDenial.tpl b/Toolkit/Members/templates/newMemberDenial.tpl new file mode 100755 index 0000000..fc060c8 --- /dev/null +++ b/Toolkit/Members/templates/newMemberDenial.tpl @@ -0,0 +1,36 @@ + + + + + Registration not completed - {client_name:h} + + +
    + + + + +
    + + + + +
    + + We were unable to complete your registration + +

    + + Dear {first_name:h},
    + Unfortunately, we were not able to complete your registration. +

    + If you think there has been an error, please contact us. +

    + Sincerely,
    + {client_name:h} +
    +
    +
    +
    + + diff --git a/Toolkit/Members/templates/search.tpl b/Toolkit/Members/templates/search.tpl new file mode 100755 index 0000000..b516981 --- /dev/null +++ b/Toolkit/Members/templates/search.tpl @@ -0,0 +1,39 @@ + + + + +{form.javascript:h} +{form.outputHeader():h} +{form.hidden:h} + + {validated():h} +
    + {sec.header} + + + + {if:elem.isType(#checkbox#)} + + + {else:} + + + + {end:} + +
    {elem.html:h} {elem.label:h} + * + {if:elem.error}{end:} + {elem.label} + {if:elem.error}{end:} + +
    + {elem.error} +
    + {elem.html:h} +
    +
    +
    + +
    + diff --git a/Toolkit/Members/templates/tripPlannerList.tpl b/Toolkit/Members/templates/tripPlannerList.tpl new file mode 100644 index 0000000..2f09a07 --- /dev/null +++ b/Toolkit/Members/templates/tripPlannerList.tpl @@ -0,0 +1,61 @@ +{if:numberedSet} +
    +
    +
    +

    Sign In

    +

    Email:

    +

    Password:

    +

    +

    {loginStat}

    +

    Forgot your Password?

    +

    - or -

    + +
    +

    + Logged in as {username} + Log Out +

    +
    + + + + +
    + + +{foreach:recordSet,k,row} +
    +

    {row[breadCrumbs]:h}

    +

    {row[member_name]:h}

    +
    +

    {row[street]:h}

    +

    {row[city]:h}, {row[state_abbr]:h} {row[zip]:h}

    +

    Time you should plan to spend here: {row[time_allocated]}

    +
    +
    +

    Phone: {row[phone]:h}

    +

    Email: {row[member_contact_email]:h}

    +

    Web: {row[urlText]:h}

    + Remove +
    +
    +
    '; +} +?> +{end:} + +
    +{end:} diff --git a/Toolkit/Members/templates/tripPlannerNoList.tpl b/Toolkit/Members/templates/tripPlannerNoList.tpl new file mode 100644 index 0000000..3177473 --- /dev/null +++ b/Toolkit/Members/templates/tripPlannerNoList.tpl @@ -0,0 +1,31 @@ + +
    +
    +

    Sign In

    +

    Email:

    +

    Password:

    +

    +

    {loginStat}

    +

    Forgot your Password?

    +

    - or -

    + +
    +

    + Logged in as {username} + Log Out +

    +
    diff --git a/Toolkit/Membersonly.php b/Toolkit/Membersonly.php new file mode 100644 index 0000000..4844e45 --- /dev/null +++ b/Toolkit/Membersonly.php @@ -0,0 +1,337 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Membersonly.php,v 1.2 2009/12/15 20:18:15 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Base class for the memberdb + * + * @category MembersDB + * @package Toolkit_Members + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Membersonly +{ + // {{{ properties + + /** + * Strict pending for member updates + */ + const STRICT_PENDING = true; + + /** + * Table that holds the member update requests + */ + const PENDING_TABLE = 'member_updates'; + + // }}} + + // {{{ __construct() + + /** + * Constructor + * + * @access public + */ + public function __construct() + { + } + + // }}} + + // {{{ toHtml() + + /** + * Determine which form to show to the user + * + * When editing a member the (a)ction in the URL controls + * which form is displayed to the user. Member Id's from + * the database should be passed along as the ID in the $_GET array. + * + * @return void + * @access public + */ + public function toHtml() + { + $mid = $GLOBALS['memberAuth']->getAuthData('member_id'); + // application configuration + $conf = new Config; + $root =& $conf->parseConfig(BASE . 'Toolkit/Members/members.ini', 'IniFile'); + + $nav =& new Toolkit_Members_RecordNavigation($root); + $nav->setupUserNavStructure(); + + $tplOpts = Toolkit_Members::getFlexyOptions(); + $tEngine = new HTML_Template_Flexy($tplOpts); + + switch ($_GET['tab']) { + case 6 : + $mc =& new Toolkit_Members_EditMemberOnlyContacts( + Toolkit_Database::getInstance(), + 'edit_contacts', + 'post', + null, + null, + null, + true + ); + if ($_GET['d'] == 't' && is_numeric($_GET['cid'])) { + $mc->removeContact($_GET['cid'], $_GET['id']); + } + $mc->setConfig($root); + $mc->configureForm(); + $out = $mc->toHtml(); + break; + + case 5 : + $mf =& new Toolkit_Members_EditMemberOnlyFile( + Toolkit_Database::getInstance(), + 'edit_files' + ); + $mf->setConfig($root); + $mf->configureForm(); + $out = $mf->toHtml(); + break; + + case 4 : + $ma =& new Toolkit_Members_EditMemberOnlyAmenities( + Toolkit_Database::getInstance(), + 'edit_amenities', + 'post', + null, + null, + null, + true + ); + $ma->setConfig($root); + $ma->configureForm(); + $out = $ma->toHtml(); + break; + + case 3 : + $mp = new Toolkit_Members_EditPackages( + Toolkit_Database::getInstance(), + $tEngine + ); + $mp->setupPage(); + $out = $mp->getPage($nav); + break; + + case 2 : + // Object to use when rendering the page template + $page = new stdClass(); + // Page navigation + $page->nav = $nav->getPageNav(); + + // Linked List of member photos + $linkedList = new Toolkit_Members_Photos(null, $mid); + $linkedList->createMemberList( + Toolkit_Database::getInstance(), + $root + ); + // Member Object to get calculate attributes about a member + $member = new Toolkit_Members_Member( + Toolkit_Database::getInstance(), + $root + ); + // Server side caching + $cache = new Cache_Lite(Toolkit_Members::getCacheOptions()); + // Image server for processing uploaded images + $is = new Toolkit_Image_Server(); + + if ($member->canAddPhotos($linkedList, $root)) { + $aForm = new Toolkit_Members_AddPhoto( + Toolkit_Database::getInstance(), + 'new_member_photo', + 'post', + BASE_URL . "memberdb/index.php?Option=Member&Action=Edit&tab=2", + '', + null, + true + ); + $aForm->configureForm($root); + $page->uploadForm = $aForm->toHtml( + $tEngine, + $cache, + $root, + $is, + $linkedList + ); + } + + if ($member->hasUploadedPhotos($linkedList)) { + $editForms = array(); + $linkedList->rewind(); + + foreach ($linkedList as $i) { + $id = $i->getId(); + $eForm = new Toolkit_Members_EditPhoto( + Toolkit_Database::getInstance(), + $linkedList, + "edit_member_photo_$id", + 'post', + BASE_URL . "memberdb/index.php?Option=Member&Action=Edit&tab=2", + '', + array('id' => $id), + true + ); + $eForm->configureForm($root); + $page->editForms[$id] = $eForm->toHtml( + $tEngine, + $cache, + $is, + $root + ); + } + } + + // get reference to [photos] section of config file + $config =& $root->getItem('section', 'photos'); + $template =& $config->getItem('directive', 'editGalleryTemplate'); + + $tEngine->compile($template->getContent()); + $out = $tEngine->bufferedOutputObject($page); + break; + + case 1 : + default : + $mr =& new Toolkit_Members_EditMemberOnlyInfo( + Toolkit_Database::getInstance(), + 'edit_member', + 'post', + null, + null, + null, + true + ); + $mr->setStates( + Toolkit_Common::getStates( + Toolkit_Database::getInstance() + ) + ); + $mr->setConfig($root); + $mr->configureForm(); + $out = $mr->toHtml(); + break; + } + + return $out; + } + + // }}} + + // {{{ show() + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access public + */ + public function show() + { + echo $this->toHtml(); + } + + // }}} + + // {{{ updateNotificationEmail() + + /** + * Emails the owner and anyone else who wants to be advised of updates + * + * A false value in the MEMBER_RECORD_UPDATES_ADVISOR will cause no email + * to be sent. all secondary advisees listed in the constructor are carbon + * copied in the email. + * + * Emails are sent out in both HTML and TXT forms. + * + * @param Config_Container $c Configuration object + * @param HTML_Template_Flexy $tEngine Flexy Templating Engine + * @param Mail $mail Mail object + * + * @return boolean result of mailing + * @access protected + * @since Method available since Release 1.5 + */ + static public function updateNotificationEmail( + Config_Container $c, + HTML_Template_Flexy $tEngine, + Mail $mail + ) { + if (MEMBER_RECORD_UPDATES_ADVISOR === false) { + return; + } else { + try { + $sql = " + SELECT member_name + FROM member + WHERE member_id = :member_id"; + $dbh = Toolkit_Database::getInstance(); + $stmt = $dbh->prepare($sql); + $stmt->bindParam(':member_id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $memberName = $row['member_name']; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + $page = new StdClass; + + $page->member = $memberName; + $page->url = ($_SERVER['HTTPS'] == 'on') ? BASE_SECURE_URL : BASE_URL; + $page->email = OWNER_EMAIL; + $page->siteName = SITENAME; + $page->link = 'link'; + + $tEngine->compile('emailOwner.tpl'); + // Merge the compiled template with the $page object. + $htmlMsg = $tEngine->bufferedOutputObject($page); + + $msg = " +

    $memberName

    +

    + Has updated thier business record and is now in a pending + state. To approve / reject thier changes you can either log + into your {$page->siteName} admin area or follow this + {$page->link} +

    "; + $crlf = "\n"; + $mimeMail = new Mail_mime($crlf); + $from = ereg_replace("[^A-Za-z ]", "", SITENAME) . ' '; + $mimeMail->setFrom($from); + $mimeMail->setSubject(Toolkit_Members_Admin_Controller::$listingType['singular'] . 'Record Update'); + $mimeMail->setHTMLBody($htmlMsg); + $mimeMail->setTXTBody($msg); + + $body = $mimeMail->get(); + $headers = $mimeMail->headers($hdrs); + + $res = $mail->send(MEMBER_RECORD_UPDATES_ADVISOR, $headers, $body); + if (PEAR::isError($res)) { + return Toolkit_Common::handleError($res); + } else { + return $res; + } + } + } + + // }}} +} +?> diff --git a/Toolkit/PHPImageEditor/classes/phpimageeditor.php b/Toolkit/PHPImageEditor/classes/phpimageeditor.php new file mode 100644 index 0000000..3972e79 --- /dev/null +++ b/Toolkit/PHPImageEditor/classes/phpimageeditor.php @@ -0,0 +1,818 @@ +. + */ + + + //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 + */ + + class PHPImageEditor + { + var $srcEdit = ""; + var $srcOriginal = ""; + var $srcPng = ""; + var $srcWorkWith = ""; + var $resourceWorkWith = false; + var $mimeType = ""; + var $actionSaveAndClose = "save"; + var $actionRotateLeft = "rotate:90"; + var $actionRotateRight = "rotate:-90"; + var $actionGrayscale = "grayscale"; + var $actionContrast = "contrast"; + var $actionBrightness = "brightness"; + var $actionUndo = "undo"; + var $actionUpdate = "update"; + var $actionRotateIsSelected = false; + var $actionRotate = ""; + var $actionSeparatorSign = "#"; + var $fieldNameKeepProportions = "keepproportions"; + var $errorMessages = array(); + var $formName = "phpimageeditor"; + var $inputImageName = ''; + var $inputWidth = -1; + var $inputHeight = -1; + var $inputCropLeft = 0; + var $inputCropRight = 0; + var $inputCropTop = 0; + var $inputCropBottom = 0; + var $inputKeepProportions = true; + var $inputCropKeepProportions = false; + var $inputCropKeepProportionsRatio = 1; + var $inputPanel = MENU_RESIZE; + var $inputLanguage = DEFUALT_LANGUAGE; + var $inputContrast = 0; + var $inputBrightness = 0; + var $inputContrastLast = 0; + var $inputBrightnessLast = 0; + var $inputGrayscale = false; + var $httpImageKey = "imagesrc"; + var $texts = array(); + var $actions = ""; + var $isPostBack = false; + var $isAjaxPost = false; + var $finalWidth = -1; + var $finalHeight = -1; + var $widthKeepProportions = -1; + var $heightKeepProportions = -1; + var $userId = ""; + + var $contrastMax = 100; + var $brightnessMax = 255; + + + function PHPImageEditor() + { + $this->LoadLanguage(); + + if (version_compare(phpversion(), PHP_VERSION_MINIMUM, "<")) + { + $this->errorMessages[] = phpversion()." ".$this->texts["OLD PHP VERSION"]." ".PHP_VERSION_MINIMUM; + return; + } + + $this->isPostBack = isset($_POST["actiontype"]); + + $srcEdit = ""; + + if ($_GET[$this->httpImageKey] != NULL) + { + $srcEdit = $_GET[$this->httpImageKey]; + } + + if ($srcEdit == "") + { + $this->errorMessages[] = $this->texts["NO PROVIDED IMAGE"]; + return; + } + + $this->srcEdit = urldecode($srcEdit); + $this->inputImageName = urlencode($_GET['image_name']); + + if (isset($_POST["userid"])) + $this->userId = $_POST["userid"]; + else + $this->userId = "_".time()."_".str_replace(".", "_", $_SERVER['REMOTE_ADDR']); + + $this->SetSrcOriginal(); + $this->SetSrcPng(); + $this->SetSrcWorkWith(); + + if (!file_exists($this->srcEdit)) + { + $this->errorMessages[] = $this->texts["IMAGE DOES NOT EXIST"]; + return; + } + + $info = getimagesize($this->srcEdit); + + if (!$info) + { + $this->errorMessages[] = $this->texts["INVALID IMAGE TYPE"]; + return; + } + + $this->mimeType = image_type_to_mime_type($info[2]); + + if ($this->mimeType == image_type_to_mime_type(IMAGETYPE_JPEG) || $this->mimeType == image_type_to_mime_type(IMAGETYPE_GIF) || $this->mimeType == image_type_to_mime_type(IMAGETYPE_PNG)) + { + if (!$this->isPostBack) + $this->SaveOriginal(); + + $this->resourceWorkWith = $this->CreateImage($this->srcOriginal); + $this->SavePng(); + copy($this->srcPng, $this->srcWorkWith); + + $this->resourceWorkWith = $this->CreateImage($this->srcPng); + } + else + { + $this->errorMessages[] = $this->texts["INVALID IMAGE TYPE"]; + return; + } + + $this->finalWidth = $this->GetWidth(); + $this->finalHeight = $this->GetHeight(); + $this->widthKeepProportions = $this->GetWidth(); + $this->heightKeepProportions = $this->GetHeight(); + + $this->GrantAllAccess($this->srcOriginal); + $this->GrantAllAccess($this->srcPng); + $this->GrantAllAccess($this->srcWorkWith); + + if ($this->isPostBack) + { + $this->actionRotateIsSelected = ($_POST["rotate"] != "-1"); + $this->actionRotate = $_POST["rotate"]; + $this->actions = $_POST["actions"]; + $this->isAjaxPost = ($_POST["isajaxpost"] == "true"); + +// $this->inputImageName = $_POST['image_name']; + $this->inputWidth = (int)$_POST["width"]; + $this->inputHeight = (int)$_POST["height"]; + $this->inputCropLeft = (int)$_POST["cropleft"]; + $this->inputCropRight = (int)$_POST["cropright"]; + $this->inputCropTop = (int)$_POST["croptop"]; + $this->inputCropBottom = (int)$_POST["cropbottom"]; + $this->inputPanel = (int)$_POST["panel"]; + $this->inputLanguage = $_POST["language"]; + $this->inputKeepProportions = ($_POST["keepproportionsval"] == "1"); + $this->inputCropKeepProportions = ($_POST["cropkeepproportionsval"] == "1"); + $this->inputCropKeepProportionsRatio = (float)$_POST["cropkeepproportionsratio"]; + $this->inputGrayscale = ($_POST["grayscaleval"] == "1"); + $this->inputBrightness = (int)$_POST["brightness"]; + $this->inputContrast = (int)$_POST["contrast"]; + $this->inputBrightnessLast = (int)$_POST["brightnesslast"]; + $this->inputContrastLast = (int)$_POST["contrastlast"]; + + $this->Action($_POST["actiontype"]); + } + } + + function LoadLanguage() + { + $language = ""; + + if (isset($_POST["language"])) + { + $this->inputLanguage = $_POST["language"]; + $language = $this->inputLanguage; + } + else if (isset($_GET["language"])) + { + $this->inputLanguage = $_GET["language"]; + $language = $this->inputLanguage; + } + else + $language = DEFUALT_LANGUAGE; + + $tryLanguage = "language/".$language."/".$language.".com_admin.ini"; + if (file_exists($tryLanguage)) + $this->texts = PIE_GetTexts("language/".$language."/".$language.".com_admin.ini"); + else + $this->texts = PIE_GetTexts("language/".DEFUALT_LANGUAGE."/".DEFUALT_LANGUAGE.".com_admin.ini"); + } + + function SetSrcOriginal() + { + $arr = explode("/", $this->srcEdit); + $this->srcOriginal = IMAGE_ORIGINAL_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]); + } + + function SetSrcWorkWith() + { + $arr = explode("/", $this->srcEdit); + $srcWorkWith = IMAGE_WORK_WITH_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]); + $srcWorkWith = substr($srcWorkWith, 0, strripos($srcWorkWith, ".")).".png"; + $this->srcWorkWith = $srcWorkWith; + } + + function SetSrcPng() + { + $arr = explode("/", $this->srcEdit); + $srcPng = IMAGE_PNG_PATH.$this->AddUserIdToImageSrc($arr[count($arr)-1]); + $srcPng = substr($srcPng, 0, strripos($srcPng, ".")).".png"; + $this->srcPng = $srcPng; + } + + function SaveOriginal() + { + copy($this->srcEdit, $this->srcOriginal); + + //Resize to fit in max width/height. + $imageTmp = $this->CreateImage($this->srcOriginal); + $finalWidth = $this->GetWidthFromImage($imageTmp); + $finalHeight = $this->GetHeightFromImage($imageTmp); + + $doSave = false; + + if ($finalWidth > IMAGE_MAX_WIDTH) + { + $widthProp = IMAGE_MAX_WIDTH/$finalWidth; + $finalWidth = IMAGE_MAX_WIDTH; + $finalHeight = round($finalHeight*$widthProp); + $doSave = true; + } + + if ($finalHeight > IMAGE_MAX_HEIGHT) + { + $heightProp = IMAGE_MAX_HEIGHT/$finalHeight; + $finalHeight = IMAGE_MAX_HEIGHT; + $finalWidth = round($finalWidth*$heightProp); + $doSave = true; + } + + if ($doSave) + { + $imageTmp = $this->ActionResize($finalWidth, $finalHeight, $imageTmp); + $this->SaveImage($imageTmp, $this->srcOriginal); + } + } + + function SavePng() + { + $this->SaveImage($this->resourceWorkWith, $this->srcPng, image_type_to_mime_type(IMAGETYPE_PNG)); + } + + function ErrorHasOccurred() + { + return (count($this->errorMessages) > 0); + } + + function GetWidthFinal() + { + return $this->finalWidth; + } + + function GetHeightFinal() + { + return $this->finalHeight; + } + + function GetWidth() + { + return $this->GetWidthFromImage($this->resourceWorkWith); + } + + function GetWidthLast() + { + if ($this->isPostBack) + return (int)$_POST["widthlast"]; + + return $this->GetWidth(); + } + + function GetHeight() + { + return $this->GetHeightFromImage($this->resourceWorkWith); + } + + function GetHeightLast() + { + if ($this->isPostBack) + return (int)$_POST["heightlast"]; + + return $this->GetWidth(); + } + + function GetImageNameFinal() + { + if ($this->isPostBack) + return $_POST["image_name"]; + + return $this->inputImageName; + } + + function getImageName() + { + return $this->inputImageName; + } + + function GetWidthFromImage($image) + { + return imagesx($image); + } + + function GetHeightFromImage($image) + { + return imagesy($image); + } + + function Action($actionType) + { + $doSave = false; + + if ($actionType == $this->actionUndo) { + $this->ActionUndo(); + $doSave = true; + } + + if ( $actionType == $this->actionUpdate + || $actionType == $this->actionSaveAndClose) { + if ( $this->inputWidth != $this->GetWidthLast() + || $this->inputHeight != $this->GetHeightLast()) { + $this->actions .= $this->GetActionSeparator()."resize:".$this->inputWidth.",".$this->inputHeight; + } + + if ( $this->inputCropLeft != 0 || $this->inputCropRight != 0 + || $this->inputCropTop != 0 || $this->inputCropBottom != 0) { + $this->actions + .= $this->GetActionSeparator() + ."crop:".$this->inputCropLeft."," + .$this->inputCropRight."," + .$this->inputCropTop."," + .$this->inputCropBottom; + } +// var_dump($this->inputImageName); +// var_dump($this->getImageNameFinal()); +// var_dump($_POST); +// var_dump($_GET); +// exit; + if (urldecode($this->inputImageName) != $this->GetImageNameFinal()) { + $this->actions .= $this->GetActionSeparator ()."imageName:".$this->GetImageNameFinal(); + } + $doSave = true; + } + + if ($actionType == $this->actionUpdate && $this->inputGrayscale) { + if (strpos($this->actions, $this->actionGrayscale) === false) { + $this->actions .= $this->GetActionSeparator().$this->actionGrayscale.":0"; + $doSave = true; + } + } else if ($actionType == $this->actionUpdate && !$this->inputGrayscale) { + if (!(strpos($this->actions, $this->actionGrayscale) === false)) { + $this->actions = str_replace($this->actionGrayscale.":0".$this->GetActionSeparator(), "", $this->actions); + $this->actions = str_replace($this->GetActionSeparator().$this->actionGrayscale.":0", "", $this->actions); + $this->actions = str_replace($this->actionGrayscale.":0", "", $this->actions); + $doSave = true; + } + } + + if ($this->inputContrast != $this->inputContrastLast) { + $this->actions .= $this->GetActionSeparator().$this->actionContrast.":".$this->inputContrast; + $doSave = true; + } + + if ($this->inputBrightness != $this->inputBrightnessLast) { + $this->actions .= $this->GetActionSeparator().$this->actionBrightness.":".$this->inputBrightness; + $doSave = true; + } + + if ($this->actionRotateIsSelected) { + if ($this->actionRotate == $this->actionRotateLeft) { + $this->actions .= $this->GetActionSeparator().$this->actionRotateLeft; + $doSave = true; + } else if ($this->actionRotate == $this->actionRotateRight) { + $this->actions .= $this->GetActionSeparator().$this->actionRotateRight; + $doSave = true; + } + } + + $finalContrast = 0; + $finalBrightness = 0; + $finalContrastFound = false; + $finalBrightnessFound = false; + $finalGrayscale = false; + + if ($doSave && $this->actions != "") { + $allActions = explode($this->actionSeparatorSign, $this->actions); + + $finalRotate = 0; + $finalCropLeft = 0; + $finalCropRight = 0; + $finalCropTop = 0; + $finalCropBottom = 0; + + $doSwitch = false; + + foreach ($allActions as $loopAction) { + $actionDetail = explode(":", $loopAction); + $actionValues = explode(",", $actionDetail[1]); + + if ($actionDetail[0] == "resize") { + $this->finalWidth = (int)$actionValues[0]; + $this->finalHeight = (int)$actionValues[1]; + } else if ($actionDetail[0] == "crop") { + $actionValueLeft = (int)$actionValues[0]; + $actionValueRight = (int)$actionValues[1]; + $actionValueTop = (int)$actionValues[2]; + $actionValueBottom = (int)$actionValues[3]; + + $widthProp = 1; + $heightProp = 1; + + if ($doSwitch) { + $widthProp = (($this->GetHeight()-($finalCropTop + $finalCropBottom)) / $this->finalWidth); + $heightProp = (($this->GetWidth()-($finalCropLeft + $finalCropRight)) / $this->finalHeight); + } else { + $widthProp = (($this->GetWidth()-($finalCropLeft + $finalCropRight)) / $this->finalWidth); + $heightProp = (($this->GetHeight()-($finalCropTop + $finalCropBottom)) / $this->finalHeight); + } + + $cropLeft = $actionValueLeft * $widthProp; + $cropRight = $actionValueRight * $widthProp; + $cropTop = $actionValueTop * $heightProp; + $cropBottom = $actionValueBottom * $heightProp; + + $cropValues = array(); + $cropValues[] = $cropRight; + $cropValues[] = $cropBottom; + $cropValues[] = $cropLeft; + $cropValues[] = $cropTop; + + if ($finalRotate != 0) + $cropValues = $this->RotateArray(($finalRotate/-90), $cropValues); + + $finalCropRight += $cropValues[0]; + $finalCropBottom += $cropValues[1]; + $finalCropLeft += $cropValues[2]; + $finalCropTop += $cropValues[3]; + + $this->finalWidth -= ($actionValueLeft + $actionValueRight); + $this->finalHeight -= ($actionValueTop + $actionValueBottom); + } else if ($actionDetail[0] == $this->actionGrayscale && $this->inputGrayscale) { + $finalGrayscale = true; + } else if ($actionDetail[0] == "contrast") { + $finalContrastFound = true; + $finalContrast = $actionValues[0]; + } else if ($actionDetail[0] == "brightness") { + $finalBrightnessFound = true; + $finalBrightness = $actionValues[0]; + } else if ($actionDetail[0] == "rotate") { + $finalRotate += (int)$actionValues[0]; + $finalWidthTmp = $this->finalWidth; + $this->finalWidth = $this->finalHeight; + $this->finalHeight = $finalWidthTmp; + } + + if ($finalRotate == -360 || $finalRotate == 360) { + $finalRotate = 0; + } + + $doSwitch = ($finalRotate != 0 && ($finalRotate == 90 || $finalRotate == 270 || $finalRotate == -90 || $finalRotate == -270)); + } + + //1. All effects. + if ($finalGrayscale) { + $this->ActionGrayscale(); + } + + if ($finalBrightnessFound) { + $this->ActionBrightness($finalBrightness); + } + + if ($finalContrastFound) { + $this->ActionContrast($finalContrast*-1); + } + + //2. Do cropping. + $finalCropLeft = round($finalCropLeft); + $finalCropRight = round($finalCropRight); + $finalCropTop = round($finalCropTop); + $finalCropBottom = round($finalCropBottom); + if ($finalCropLeft != 0 || $finalCropRight != 0 || $finalCropTop != 0 || $finalCropBottom != 0) { + $this->ActionCrop($finalCropLeft, $finalCropRight, $finalCropTop, $finalCropBottom); + } + + //3. Rotate + if ($finalRotate != 0) { + $this->ActionRotate($finalRotate); + } + + //Calculate keep proportions values. + if (round($this->finalWidth/$this->finalHeight,1) == round($this->GetWidth()/$this->GetHeight(),1)) { + //It seems to have the same proportions as the original. Use the original proportions value. + $this->widthKeepProportions = $this->GetWidth(); + $this->heightKeepProportions = $this->GetHeight(); + } else { + //The proportions has been changed. Use the new width and height instead. + $this->widthKeepProportions = $this->finalWidth; + $this->heightKeepProportions = $this->finalHeight; + } + + //4. Resize + if ($this->finalWidth > 0 && $this->finalHeight > 0) + $this->resourceWorkWith = $this->ActionResize($this->finalWidth, $this->finalHeight, $this->resourceWorkWith); + + $this->SaveImage($this->resourceWorkWith, $this->srcWorkWith, image_type_to_mime_type(IMAGETYPE_PNG)); + } + + $this->inputBrightness = $finalBrightness; + $this->inputContrast = $finalContrast; + $this->inputGrayscale = $finalGrayscale; + + if ($actionType == $this->actionSaveAndClose) { + $this->SaveImage($this->resourceWorkWith, $this->srcEdit, $this->mimeType); + + /*** GLM stuff ***/ + require_once '../../setup.phtml'; + $CKUpdater = new Toolkit_CKImages_ImageUpdater(Toolkit_Database::getInstance()); + $CKUpdater->load(basename($_GET['imagesrc'])); + $CKUpdater->update(new Toolkit_FileServer_ImageAdapter()); + /*****************/ + + unlink($this->srcOriginal); + unlink($this->srcPng); + unlink($this->srcWorkWith); + $this->DeleteOldImages(IMAGE_ORIGINAL_PATH); + $this->DeleteOldImages(IMAGE_PNG_PATH); + $this->DeleteOldImages(IMAGE_WORK_WITH_PATH); + $reloadParentBrowser = RELOAD_PARENT_BROWSER_ON_SAVE ? 'window.opener.location.reload();' : ''; + PIE_Echo(''); + } + } + + function ActionResize($width, $height, $image) + { + $newImage = @imagecreatetruecolor($width, $height); + imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $this->GetWidthFromImage($image), $this->GetHeightFromImage($image)); + return $newImage; + } + + function ActionCrop($cropLeft, $cropRight, $cropTop, $cropBottom) + { + $cropWidth = $this->GetWidth() - $cropLeft - $cropRight; + $cropHeight = $this->GetHeight() - $cropTop - $cropBottom; + + $newImageCropped = @imagecreatetruecolor($cropWidth, $cropHeight); + imagecopy($newImageCropped, $this->resourceWorkWith, 0, 0, $cropLeft, $cropTop, $cropWidth, $cropHeight); + + $this->resourceWorkWith = $newImageCropped; + } + + function ActionUndo() + { + $separatorPos = strrpos($this->actions, $this->actionSeparatorSign); + if (!($separatorPos === false)) + { + $this->actions = substr($this->actions, 0, $separatorPos); + } + else + { + $this->actions = ""; + } + } + + function CreateImage($srcEdit) + { + $info = getimagesize($srcEdit); + + if (!$info) + return NULL; + + $mimeType = image_type_to_mime_type($info[2]); + + if ($mimeType == image_type_to_mime_type(IMAGETYPE_JPEG)) + { + return imagecreatefromjpeg($srcEdit); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_GIF)) + { + return imagecreatefromgif($srcEdit); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_PNG)) + { + return imagecreatefrompng($srcEdit); + } + + return NULL; + } + + function ActionRotate($Degrees) + { + $this->resourceWorkWith = imagerotate($this->resourceWorkWith, $Degrees, 0); + } + + function ActionGrayscale() + { + imagefilter($this->resourceWorkWith, IMG_FILTER_GRAYSCALE); + } + + function ActionContrast($contrast) + { + //-100 = max contrast, 0 = no change, +100 = min contrast + imagefilter($this->resourceWorkWith, IMG_FILTER_CONTRAST, $contrast); + } + + function ActionBrightness($light) + { + //-255 = min brightness, 0 = no change, +255 = max brightness + imagefilter($this->resourceWorkWith, IMG_FILTER_BRIGHTNESS, $light); + } + + function GetErrorMessages() + { + if (count($this->errorMessages)) + { + PIE_Echo('
    '); + PIE_Echo('
      '); + + foreach ($this->errorMessages as $errorMessage) + PIE_Echo ('
    • '.$errorMessage.'
    • '); + + PIE_Echo("
    "); + PIE_Echo('
    '); + } + } + + function GetActions() + { + PIE_Echo($this->actions); + } + + function GetActionSeparator() + { + if ($this->actions != "") + return $this->actionSeparatorSign; + + return ""; + } + + function SaveImage($image, $toSrc, $mimeType = -1) + { + if ($mimeType == -1) + $mimeType = $this->mimeType; + + if ($mimeType == image_type_to_mime_type(IMAGETYPE_JPEG)) + { + imagejpeg($image, $toSrc); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_GIF)) + { + imagegif($image, $toSrc); + } + else if ($mimeType == image_type_to_mime_type(IMAGETYPE_PNG)) + { + imagepng($image, $toSrc); + } + } + + function CleanUp() + { + if ($this->resourceWorkWith) + imagedestroy($this->resourceWorkWith); + } + + function RotateArray($numberOfSteps, $arr) + { + $finalArray = array(); + + //-3 to 3 + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 0)]; + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 1)]; + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 2)]; + $finalArray[] = $arr[$this->NumberOfStepsCalculator($numberOfSteps + 3)]; + + return $finalArray; + } + + function NumberOfStepsCalculator($sum) + { + $maxIndex = 3; + if ($sum > $maxIndex) + return ($sum-$maxIndex)-1; + else if ($sum < 0) + { + return ($sum+$maxIndex)+1; + } + + return $sum; + } + + function AddUserIdToImageSrc($imageSrc) + { + return str_replace(".", $this->userId.".", $imageSrc); + } + + function IsPHP5OrHigher() + { + return version_compare(phpversion(), "5", ">="); + } + + function GetFormAction() + { + return "index.php?" + . $this->httpImageKey . "=" . $this->srcEdit + . '&image_name=' . $this->inputImageName; + } + + function GetWidthKeepProportions() + { + return $this->widthKeepProportions; + } + + function GetHeightKeepProportions() + { + return $this->heightKeepProportions; + } + + function DeleteOldImages($srcdir) + { + if($curdir = opendir($srcdir)) + { + while($file = readdir($curdir)) + { + if($file != '.' && $file != '..') + { + //$srcfile = $srcdir . '\\' . $file; + //$srcfile = $srcdir.'/'.$file; + $srcfile = $srcdir.$file; + $srcfileLower = strtolower($srcfile); + + if (stripos($srcfile, ".svn") === false) + { + if(is_file($srcfile)) + { + $doDelete = true; + + if (substr_count($srcfile, "sample.jpg") > 0 || substr_count($srcfile, "sample.png") > 0 || (substr_count($srcfileLower, ".jpg") == 0 && substr_count($srcfileLower, ".gif") == 0 && substr_count($srcfileLower, ".png") == 0)) + $doDelete = false; + + if ($doDelete) + { + + $deleteTime = mktime(0, 0, 0, date("m"), date("d")-2, date("Y")); + if (fileatime($srcfile) < $deleteTime) + { + //Image is old and will be deleted. Or else the server space will be filled up with not needed images. + //echo "

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

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

    ";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="
    ";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("
    ").append(M.responseText.replace(//g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='
    ';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})(); \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/javascript/jquery.jcrop.js b/Toolkit/PHPImageEditor/javascript/jquery.jcrop.js new file mode 100644 index 0000000..ad261f9 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/jquery.jcrop.js @@ -0,0 +1,1197 @@ +/** + * jquery.Jcrop.js v0.9.8 + * jQuery Image Cropping Plugin + * @author Kelly Hallman + * Copyright (c) 2008-2009 Kelly Hallman - released under MIT License {{{ + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + + * }}} + */ + +(function($) { + +$.Jcrop = function(obj,opt) +{ + // Initialization {{{ + + // Sanitize some options {{{ + var obj = obj, opt = opt; + + if (typeof(obj) !== 'object') obj = $(obj)[0]; + if (typeof(opt) !== 'object') opt = { }; + + // Some on-the-fly fixes for MSIE...sigh + if (!('trackDocument' in opt)) + { + opt.trackDocument = $.browser.msie ? false : true; + if ($.browser.msie && $.browser.version.split('.')[0] == '8') + opt.trackDocument = true; + } + + if (!('keySupport' in opt)) + opt.keySupport = $.browser.msie ? false : true; + + // }}} + // Extend the default options {{{ + var defaults = { + + // Basic Settings + trackDocument: false, + baseClass: 'jcrop', + addClass: null, + + // Styling Options + bgColor: 'black', + bgOpacity: .6, + borderOpacity: .4, + handleOpacity: .5, + + handlePad: 5, + handleSize: 9, + handleOffset: 5, + edgeMargin: 14, + + aspectRatio: 0, + keySupport: true, + cornerHandles: true, + sideHandles: true, + drawBorders: true, + dragEdges: true, + + boxWidth: 0, + boxHeight: 0, + + boundary: 8, + animationDelay: 20, + swingSpeed: 3, + + allowSelect: true, + allowMove: true, + allowResize: true, + + minSelect: [ 0, 0 ], + maxSize: [ 0, 0 ], + minSize: [ 0, 0 ], + + // Callbacks / Event Handlers + onChange: function() { }, + onSelect: function() { } + + }; + var options = defaults; + setOptions(opt); + + // }}} + // Initialize some jQuery objects {{{ + + var $origimg = $(obj); + var $img = $origimg.clone().removeAttr('id').css({ position: 'absolute' }); + + $img.width($origimg.width()); + $img.height($origimg.height()); + $origimg.after($img).hide(); + + presize($img,options.boxWidth,options.boxHeight); + + var boundx = $img.width(), + boundy = $img.height(), + + $div = $('
    ') + .width(boundx).height(boundy) + .addClass(cssClass('holder')) + .css({ + position: 'relative', + backgroundColor: options.bgColor + }).insertAfter($origimg).append($img); + ; + + if (options.addClass) $div.addClass(options.addClass); + //$img.wrap($div); + + var $img2 = $('')/*{{{*/ + .attr('src',$img.attr('src')) + .css('position','absolute') + .width(boundx).height(boundy) + ;/*}}}*/ + var $img_holder = $('
    ')/*{{{*/ + .width(pct(100)).height(pct(100)) + .css({ + zIndex: 310, + position: 'absolute', + overflow: 'hidden' + }) + .append($img2) + ;/*}}}*/ + var $hdl_holder = $('
    ')/*{{{*/ + .width(pct(100)).height(pct(100)) + .css('zIndex',320); + /*}}}*/ + var $sel = $('
    ')/*{{{*/ + .css({ + position: 'absolute', + zIndex: 300 + }) + .insertBefore($img) + .append($img_holder,$hdl_holder) + ;/*}}}*/ + + var bound = options.boundary; + var $trk = newTracker().width(boundx+(bound*2)).height(boundy+(bound*2)) + .css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 }) + .mousedown(newSelection); + + /* }}} */ + // Set more variables {{{ + + var xlimit, ylimit, xmin, ymin; + var xscale, yscale, enabled = true; + var docOffset = getPos($img), + // Internal states + btndown, lastcurs, dimmed, animating, + shift_down; + + // }}} + + + // }}} + // Internal Modules {{{ + + var Coords = function()/*{{{*/ + { + var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy; + + function setPressed(pos)/*{{{*/ + { + var pos = rebound(pos); + x2 = x1 = pos[0]; + y2 = y1 = pos[1]; + }; + /*}}}*/ + function setCurrent(pos)/*{{{*/ + { + var pos = rebound(pos); + ox = pos[0] - x2; + oy = pos[1] - y2; + x2 = pos[0]; + y2 = pos[1]; + }; + /*}}}*/ + function getOffset()/*{{{*/ + { + return [ ox, oy ]; + }; + /*}}}*/ + function moveOffset(offset)/*{{{*/ + { + var ox = offset[0], oy = offset[1]; + + if (0 > x1 + ox) ox -= ox + x1; + if (0 > y1 + oy) oy -= oy + y1; + + if (boundy < y2 + oy) oy += boundy - (y2 + oy); + if (boundx < x2 + ox) ox += boundx - (x2 + ox); + + x1 += ox; + x2 += ox; + y1 += oy; + y2 += oy; + }; + /*}}}*/ + function getCorner(ord)/*{{{*/ + { + var c = getFixed(); + switch(ord) + { + case 'ne': return [ c.x2, c.y ]; + case 'nw': return [ c.x, c.y ]; + case 'se': return [ c.x2, c.y2 ]; + case 'sw': return [ c.x, c.y2 ]; + } + }; + /*}}}*/ + function getFixed()/*{{{*/ + { + if (!options.aspectRatio) return getRect(); + // This function could use some optimization I think... + var aspect = options.aspectRatio, + min_x = options.minSize[0]/xscale, + min_y = options.minSize[1]/yscale, + max_x = options.maxSize[0]/xscale, + max_y = options.maxSize[1]/yscale, + rw = x2 - x1, + rh = y2 - y1, + rwa = Math.abs(rw), + rha = Math.abs(rh), + real_ratio = rwa / rha, + xx, yy + ; + if (max_x == 0) { max_x = boundx * 10 } + if (max_y == 0) { max_y = boundy * 10 } + if (real_ratio < aspect) + { + yy = y2; + w = rha * aspect; + xx = rw < 0 ? x1 - w : w + x1; + + if (xx < 0) + { + xx = 0; + h = Math.abs((xx - x1) / aspect); + yy = rh < 0 ? y1 - h: h + y1; + } + else if (xx > boundx) + { + xx = boundx; + h = Math.abs((xx - x1) / aspect); + yy = rh < 0 ? y1 - h : h + y1; + } + } + else + { + xx = x2; + h = rwa / aspect; + yy = rh < 0 ? y1 - h : y1 + h; + if (yy < 0) + { + yy = 0; + w = Math.abs((yy - y1) * aspect); + xx = rw < 0 ? x1 - w : w + x1; + } + else if (yy > boundy) + { + yy = boundy; + w = Math.abs(yy - y1) * aspect; + xx = rw < 0 ? x1 - w : w + x1; + } + } + + // Magic %-) + if(xx > x1) { // right side + if(xx - x1 < min_x) { + xx = x1 + min_x; + } else if (xx - x1 > max_x) { + xx = x1 + max_x; + } + if(yy > y1) { + yy = y1 + (xx - x1)/aspect; + } else { + yy = y1 - (xx - x1)/aspect; + } + } else if (xx < x1) { // left side + if(x1 - xx < min_x) { + xx = x1 - min_x + } else if (x1 - xx > max_x) { + xx = x1 - max_x; + } + if(yy > y1) { + yy = y1 + (x1 - xx)/aspect; + } else { + yy = y1 - (x1 - xx)/aspect; + } + } + + if(xx < 0) { + x1 -= xx; + xx = 0; + } else if (xx > boundx) { + x1 -= xx - boundx; + xx = boundx; + } + + if(yy < 0) { + y1 -= yy; + yy = 0; + } else if (yy > boundy) { + y1 -= yy - boundy; + yy = boundy; + } + + return last = makeObj(flipCoords(x1,y1,xx,yy)); + }; + /*}}}*/ + function rebound(p)/*{{{*/ + { + if (p[0] < 0) p[0] = 0; + if (p[1] < 0) p[1] = 0; + + if (p[0] > boundx) p[0] = boundx; + if (p[1] > boundy) p[1] = boundy; + + return [ p[0], p[1] ]; + }; + /*}}}*/ + function flipCoords(x1,y1,x2,y2)/*{{{*/ + { + var xa = x1, xb = x2, ya = y1, yb = y2; + if (x2 < x1) + { + xa = x2; + xb = x1; + } + if (y2 < y1) + { + ya = y2; + yb = y1; + } + return [ Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb) ]; + }; + /*}}}*/ + function getRect()/*{{{*/ + { + var xsize = x2 - x1; + var ysize = y2 - y1; + + if (xlimit && (Math.abs(xsize) > xlimit)) + x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit); + if (ylimit && (Math.abs(ysize) > ylimit)) + y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit); + + if (ymin && (Math.abs(ysize) < ymin)) + y2 = (ysize > 0) ? (y1 + ymin) : (y1 - ymin); + if (xmin && (Math.abs(xsize) < xmin)) + x2 = (xsize > 0) ? (x1 + xmin) : (x1 - xmin); + + if (x1 < 0) { x2 -= x1; x1 -= x1; } + if (y1 < 0) { y2 -= y1; y1 -= y1; } + if (x2 < 0) { x1 -= x2; x2 -= x2; } + if (y2 < 0) { y1 -= y2; y2 -= y2; } + if (x2 > boundx) { var delta = x2 - boundx; x1 -= delta; x2 -= delta; } + if (y2 > boundy) { var delta = y2 - boundy; y1 -= delta; y2 -= delta; } + if (x1 > boundx) { var delta = x1 - boundy; y2 -= delta; y1 -= delta; } + if (y1 > boundy) { var delta = y1 - boundy; y2 -= delta; y1 -= delta; } + + return makeObj(flipCoords(x1,y1,x2,y2)); + }; + /*}}}*/ + function makeObj(a)/*{{{*/ + { + return { x: a[0], y: a[1], x2: a[2], y2: a[3], + w: a[2] - a[0], h: a[3] - a[1] }; + }; + /*}}}*/ + + return { + flipCoords: flipCoords, + setPressed: setPressed, + setCurrent: setCurrent, + getOffset: getOffset, + moveOffset: moveOffset, + getCorner: getCorner, + getFixed: getFixed + }; + }(); + + /*}}}*/ + var Selection = function()/*{{{*/ + { + var start, end, dragmode, awake, hdep = 370; + var borders = { }; + var handle = { }; + var seehandles = false; + var hhs = options.handleOffset; + + /* Insert draggable elements {{{*/ + + // Insert border divs for outline + if (options.drawBorders) { + borders = { + top: insertBorder('hline') + .css('top',$.browser.msie?px(-1):px(0)), + bottom: insertBorder('hline'), + left: insertBorder('vline'), + right: insertBorder('vline') + }; + } + + // Insert handles on edges + if (options.dragEdges) { + handle.t = insertDragbar('n'); + handle.b = insertDragbar('s'); + handle.r = insertDragbar('e'); + handle.l = insertDragbar('w'); + } + + // Insert side handles + options.sideHandles && + createHandles(['n','s','e','w']); + + // Insert corner handles + options.cornerHandles && + createHandles(['sw','nw','ne','se']); + + /*}}}*/ + // Private Methods + function insertBorder(type)/*{{{*/ + { + var jq = $('
    ') + .css({position: 'absolute', opacity: options.borderOpacity }) + .addClass(cssClass(type)); + $img_holder.append(jq); + return jq; + }; + /*}}}*/ + function dragDiv(ord,zi)/*{{{*/ + { + var jq = $('
    ') + .mousedown(createDragger(ord)) + .css({ + cursor: ord+'-resize', + position: 'absolute', + zIndex: zi + }) + ; + $hdl_holder.append(jq); + return jq; + }; + /*}}}*/ + function insertHandle(ord)/*{{{*/ + { + return dragDiv(ord,hdep++) + .css({ top: px(-hhs+1), left: px(-hhs+1), opacity: options.handleOpacity }) + .addClass(cssClass('handle')); + }; + /*}}}*/ + function insertDragbar(ord)/*{{{*/ + { + var s = options.handleSize, + o = hhs, + h = s, w = s, + t = o, l = o; + + switch(ord) + { + case 'n': case 's': w = pct(100); break; + case 'e': case 'w': h = pct(100); break; + } + + return dragDiv(ord,hdep++).width(w).height(h) + .css({ top: px(-t+1), left: px(-l+1)}); + }; + /*}}}*/ + function createHandles(li)/*{{{*/ + { + for(i in li) handle[li[i]] = insertHandle(li[i]); + }; + /*}}}*/ + function moveHandles(c)/*{{{*/ + { + var midvert = Math.round((c.h / 2) - hhs), + midhoriz = Math.round((c.w / 2) - hhs), + north = west = -hhs+1, + east = c.w - hhs, + south = c.h - hhs, + x, y; + + 'e' in handle && + handle.e.css({ top: px(midvert), left: px(east) }) && + handle.w.css({ top: px(midvert) }) && + handle.s.css({ top: px(south), left: px(midhoriz) }) && + handle.n.css({ left: px(midhoriz) }); + + 'ne' in handle && + handle.ne.css({ left: px(east) }) && + handle.se.css({ top: px(south), left: px(east) }) && + handle.sw.css({ top: px(south) }); + + 'b' in handle && + handle.b.css({ top: px(south) }) && + handle.r.css({ left: px(east) }); + }; + /*}}}*/ + function moveto(x,y)/*{{{*/ + { + $img2.css({ top: px(-y), left: px(-x) }); + $sel.css({ top: px(y), left: px(x) }); + }; + /*}}}*/ + function resize(w,h)/*{{{*/ + { + $sel.width(w).height(h); + }; + /*}}}*/ + function refresh()/*{{{*/ + { + var c = Coords.getFixed(); + + Coords.setPressed([c.x,c.y]); + Coords.setCurrent([c.x2,c.y2]); + + updateVisible(); + }; + /*}}}*/ + + // Internal Methods + function updateVisible()/*{{{*/ + { if (awake) return update(); }; + /*}}}*/ + function update()/*{{{*/ + { + var c = Coords.getFixed(); + + resize(c.w,c.h); + moveto(c.x,c.y); + + options.drawBorders && + borders['right'].css({ left: px(c.w-1) }) && + borders['bottom'].css({ top: px(c.h-1) }); + + seehandles && moveHandles(c); + awake || show(); + + options.onChange(unscale(c)); + }; + /*}}}*/ + function show()/*{{{*/ + { + $sel.show(); + $img.css('opacity',options.bgOpacity); + awake = true; + }; + /*}}}*/ + function release()/*{{{*/ + { + disableHandles(); + $sel.hide(); + $img.css('opacity',1); + awake = false; + }; + /*}}}*/ + function showHandles()//{{{ + { + if (seehandles) + { + moveHandles(Coords.getFixed()); + $hdl_holder.show(); + } + }; + //}}} + function enableHandles()/*{{{*/ + { + seehandles = true; + if (options.allowResize) + { + moveHandles(Coords.getFixed()); + $hdl_holder.show(); + return true; + } + }; + /*}}}*/ + function disableHandles()/*{{{*/ + { + seehandles = false; + $hdl_holder.hide(); + }; + /*}}}*/ + function animMode(v)/*{{{*/ + { + (animating = v) ? disableHandles(): enableHandles(); + }; + /*}}}*/ + function done()/*{{{*/ + { + animMode(false); + refresh(); + }; + /*}}}*/ + + var $track = newTracker().mousedown(createDragger('move')) + .css({ cursor: 'move', position: 'absolute', zIndex: 360 }) + + $img_holder.append($track); + disableHandles(); + + return { + updateVisible: updateVisible, + update: update, + release: release, + refresh: refresh, + setCursor: function (cursor) { $track.css('cursor',cursor); }, + enableHandles: enableHandles, + enableOnly: function() { seehandles = true; }, + showHandles: showHandles, + disableHandles: disableHandles, + animMode: animMode, + done: done + }; + }(); + /*}}}*/ + var Tracker = function()/*{{{*/ + { + var onMove = function() { }, + onDone = function() { }, + trackDoc = options.trackDocument; + + if (!trackDoc) + { + $trk + .mousemove(trackMove) + .mouseup(trackUp) + .mouseout(trackUp) + ; + } + + function toFront()/*{{{*/ + { + $trk.css({zIndex:450}); + if (trackDoc) + { + $(document) + .mousemove(trackMove) + .mouseup(trackUp) + ; + } + } + /*}}}*/ + function toBack()/*{{{*/ + { + $trk.css({zIndex:290}); + if (trackDoc) + { + $(document) + .unbind('mousemove',trackMove) + .unbind('mouseup',trackUp) + ; + } + } + /*}}}*/ + function trackMove(e)/*{{{*/ + { + onMove(mouseAbs(e)); + }; + /*}}}*/ + function trackUp(e)/*{{{*/ + { + e.preventDefault(); + e.stopPropagation(); + + if (btndown) + { + btndown = false; + + onDone(mouseAbs(e)); + options.onSelect(unscale(Coords.getFixed())); + toBack(); + onMove = function() { }; + onDone = function() { }; + } + + return false; + }; + /*}}}*/ + + function activateHandlers(move,done)/* {{{ */ + { + btndown = true; + onMove = move; + onDone = done; + toFront(); + return false; + }; + /* }}} */ + + function setCursor(t) { $trk.css('cursor',t); }; + + $img.before($trk); + return { + activateHandlers: activateHandlers, + setCursor: setCursor + }; + }(); + /*}}}*/ + var KeyManager = function()/*{{{*/ + { + var $keymgr = $('') + .css({ position: 'absolute', left: '-30px' }) + .keypress(parseKey) + .blur(onBlur), + + $keywrap = $('
    ') + .css({ + position: 'absolute', + overflow: 'hidden' + }) + .append($keymgr) + ; + + function watchKeys()/*{{{*/ + { + if (options.keySupport) + { + $keymgr.show(); + $keymgr.focus(); + } + }; + /*}}}*/ + function onBlur(e)/*{{{*/ + { + $keymgr.hide(); + }; + /*}}}*/ + function doNudge(e,x,y)/*{{{*/ + { + if (options.allowMove) { + Coords.moveOffset([x,y]); + Selection.updateVisible(); + }; + e.preventDefault(); + e.stopPropagation(); + }; + /*}}}*/ + function parseKey(e)/*{{{*/ + { + if (e.ctrlKey) return true; + shift_down = e.shiftKey ? true : false; + var nudge = shift_down ? 10 : 1; + switch(e.keyCode) + { + case 37: doNudge(e,-nudge,0); break; + case 39: doNudge(e,nudge,0); break; + case 38: doNudge(e,0,-nudge); break; + case 40: doNudge(e,0,nudge); break; + + case 27: Selection.release(); break; + + case 9: return true; + } + + return nothing(e); + }; + /*}}}*/ + + if (options.keySupport) $keywrap.insertBefore($img); + return { + watchKeys: watchKeys + }; + }(); + /*}}}*/ + + // }}} + // Internal Methods {{{ + + function px(n) { return '' + parseInt(n) + 'px'; }; + function pct(n) { return '' + parseInt(n) + '%'; }; + function cssClass(cl) { return options.baseClass + '-' + cl; }; + function getPos(obj)/*{{{*/ + { + // Updated in v0.9.4 to use built-in dimensions plugin + var pos = $(obj).offset(); + return [ pos.left, pos.top ]; + }; + /*}}}*/ + function mouseAbs(e)/*{{{*/ + { + return [ (e.pageX - docOffset[0]), (e.pageY - docOffset[1]) ]; + }; + /*}}}*/ + function myCursor(type)/*{{{*/ + { + if (type != lastcurs) + { + Tracker.setCursor(type); + //Handles.xsetCursor(type); + lastcurs = type; + } + }; + /*}}}*/ + function startDragMode(mode,pos)/*{{{*/ + { + docOffset = getPos($img); + Tracker.setCursor(mode=='move'?mode:mode+'-resize'); + + if (mode == 'move') + return Tracker.activateHandlers(createMover(pos), doneSelect); + + var fc = Coords.getFixed(); + var opp = oppLockCorner(mode); + var opc = Coords.getCorner(oppLockCorner(opp)); + + Coords.setPressed(Coords.getCorner(opp)); + Coords.setCurrent(opc); + + Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect); + }; + /*}}}*/ + function dragmodeHandler(mode,f)/*{{{*/ + { + return function(pos) { + if (!options.aspectRatio) switch(mode) + { + case 'e': pos[1] = f.y2; break; + case 'w': pos[1] = f.y2; break; + case 'n': pos[0] = f.x2; break; + case 's': pos[0] = f.x2; break; + } + else switch(mode) + { + case 'e': pos[1] = f.y+1; break; + case 'w': pos[1] = f.y+1; break; + case 'n': pos[0] = f.x+1; break; + case 's': pos[0] = f.x+1; break; + } + Coords.setCurrent(pos); + Selection.update(); + }; + }; + /*}}}*/ + function createMover(pos)/*{{{*/ + { + var lloc = pos; + KeyManager.watchKeys(); + + return function(pos) + { + Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]); + lloc = pos; + + Selection.update(); + }; + }; + /*}}}*/ + function oppLockCorner(ord)/*{{{*/ + { + switch(ord) + { + case 'n': return 'sw'; + case 's': return 'nw'; + case 'e': return 'nw'; + case 'w': return 'ne'; + case 'ne': return 'sw'; + case 'nw': return 'se'; + case 'se': return 'nw'; + case 'sw': return 'ne'; + }; + }; + /*}}}*/ + function createDragger(ord)/*{{{*/ + { + return function(e) { + if (options.disabled) return false; + if ((ord == 'move') && !options.allowMove) return false; + btndown = true; + startDragMode(ord,mouseAbs(e)); + e.stopPropagation(); + e.preventDefault(); + return false; + }; + }; + /*}}}*/ + function presize($obj,w,h)/*{{{*/ + { + var nw = $obj.width(), nh = $obj.height(); + if ((nw > w) && w > 0) + { + nw = w; + nh = (w/$obj.width()) * $obj.height(); + } + if ((nh > h) && h > 0) + { + nh = h; + nw = (h/$obj.height()) * $obj.width(); + } + xscale = $obj.width() / nw; + yscale = $obj.height() / nh; + $obj.width(nw).height(nh); + }; + /*}}}*/ + function unscale(c)/*{{{*/ + { + return { + x: parseInt(c.x * xscale), y: parseInt(c.y * yscale), + x2: parseInt(c.x2 * xscale), y2: parseInt(c.y2 * yscale), + w: parseInt(c.w * xscale), h: parseInt(c.h * yscale) + }; + }; + /*}}}*/ + function doneSelect(pos)/*{{{*/ + { + var c = Coords.getFixed(); + if (c.w > options.minSelect[0] && c.h > options.minSelect[1]) + { + Selection.enableHandles(); + Selection.done(); + } + else + { + Selection.release(); + } + Tracker.setCursor( options.allowSelect?'crosshair':'default' ); + }; + /*}}}*/ + function newSelection(e)/*{{{*/ + { + if (options.disabled) return false; + if (!options.allowSelect) return false; + btndown = true; + docOffset = getPos($img); + Selection.disableHandles(); + myCursor('crosshair'); + var pos = mouseAbs(e); + Coords.setPressed(pos); + Tracker.activateHandlers(selectDrag,doneSelect); + KeyManager.watchKeys(); + Selection.update(); + + e.stopPropagation(); + e.preventDefault(); + return false; + }; + /*}}}*/ + function selectDrag(pos)/*{{{*/ + { + Coords.setCurrent(pos); + Selection.update(); + }; + /*}}}*/ + function newTracker() + { + var trk = $('
    ').addClass(cssClass('tracker')); + $.browser.msie && trk.css({ opacity: 0, backgroundColor: 'white' }); + return trk; + }; + + // }}} + // API methods {{{ + + function animateTo(a)/*{{{*/ + { + var x1 = a[0] / xscale, + y1 = a[1] / yscale, + x2 = a[2] / xscale, + y2 = a[3] / yscale; + + if (animating) return; + + var animto = Coords.flipCoords(x1,y1,x2,y2); + var c = Coords.getFixed(); + var animat = initcr = [ c.x, c.y, c.x2, c.y2 ]; + var interv = options.animationDelay; + + var x = animat[0]; + var y = animat[1]; + var x2 = animat[2]; + var y2 = animat[3]; + var ix1 = animto[0] - initcr[0]; + var iy1 = animto[1] - initcr[1]; + var ix2 = animto[2] - initcr[2]; + var iy2 = animto[3] - initcr[3]; + var pcent = 0; + var velocity = options.swingSpeed; + + Selection.animMode(true); + + var animator = function() + { + return function() + { + pcent += (100 - pcent) / velocity; + + animat[0] = x + ((pcent / 100) * ix1); + animat[1] = y + ((pcent / 100) * iy1); + animat[2] = x2 + ((pcent / 100) * ix2); + animat[3] = y2 + ((pcent / 100) * iy2); + + if (pcent < 100) animateStart(); + else Selection.done(); + + if (pcent >= 99.8) pcent = 100; + + setSelectRaw(animat); + }; + }(); + + function animateStart() + { window.setTimeout(animator,interv); }; + + animateStart(); + }; + /*}}}*/ + function setSelect(rect)//{{{ + { + setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]); + }; + //}}} + function setSelectRaw(l) /*{{{*/ + { + Coords.setPressed([l[0],l[1]]); + Coords.setCurrent([l[2],l[3]]); + Selection.update(); + }; + /*}}}*/ + function setOptions(opt)/*{{{*/ + { + if (typeof(opt) != 'object') opt = { }; + options = $.extend(options,opt); + + if (typeof(options.onChange)!=='function') + options.onChange = function() { }; + + if (typeof(options.onSelect)!=='function') + options.onSelect = function() { }; + + }; + /*}}}*/ + function tellSelect()/*{{{*/ + { + return unscale(Coords.getFixed()); + }; + /*}}}*/ + function tellScaled()/*{{{*/ + { + return Coords.getFixed(); + }; + /*}}}*/ + function setOptionsNew(opt)/*{{{*/ + { + setOptions(opt); + interfaceUpdate(); + }; + /*}}}*/ + function disableCrop()//{{{ + { + options.disabled = true; + Selection.disableHandles(); + Selection.setCursor('default'); + Tracker.setCursor('default'); + }; + //}}} + function enableCrop()//{{{ + { + options.disabled = false; + interfaceUpdate(); + }; + //}}} + function cancelCrop()//{{{ + { + Selection.done(); + Tracker.activateHandlers(null,null); + }; + //}}} + function destroy()//{{{ + { + $div.remove(); + $origimg.show(); + }; + //}}} + + function interfaceUpdate(alt)//{{{ + // This method tweaks the interface based on options object. + // Called when options are changed and at end of initialization. + { + options.allowResize ? + alt?Selection.enableOnly():Selection.enableHandles(): + Selection.disableHandles(); + + Tracker.setCursor( options.allowSelect? 'crosshair': 'default' ); + Selection.setCursor( options.allowMove? 'move': 'default' ); + + $div.css('backgroundColor',options.bgColor); + + if ('setSelect' in options) { + setSelect(opt.setSelect); + Selection.done(); + delete(options.setSelect); + } + + if ('trueSize' in options) { + xscale = options.trueSize[0] / boundx; + yscale = options.trueSize[1] / boundy; + } + + xlimit = options.maxSize[0] || 0; + ylimit = options.maxSize[1] || 0; + xmin = options.minSize[0] || 0; + ymin = options.minSize[1] || 0; + + if ('outerImage' in options) + { + $img.attr('src',options.outerImage); + delete(options.outerImage); + } + + Selection.refresh(); + }; + //}}} + + // }}} + + $hdl_holder.hide(); + interfaceUpdate(true); + + var api = { + animateTo: animateTo, + setSelect: setSelect, + setOptions: setOptionsNew, + tellSelect: tellSelect, + tellScaled: tellScaled, + + disable: disableCrop, + enable: enableCrop, + cancel: cancelCrop, + + focus: KeyManager.watchKeys, + + getBounds: function() { return [ boundx * xscale, boundy * yscale ]; }, + getWidgetSize: function() { return [ boundx, boundy ]; }, + + release: Selection.release, + destroy: destroy + + }; + + $origimg.data('Jcrop',api); + return api; +}; + +$.fn.Jcrop = function(options)/*{{{*/ +{ + function attachWhenDone(from)/*{{{*/ + { + var loadsrc = options.useImg || from.src; + var img = new Image(); + img.onload = function() { $.Jcrop(from,options); }; + img.src = loadsrc; + }; + /*}}}*/ + if (typeof(options) !== 'object') options = { }; + + // Iterate over each object, attach Jcrop + this.each(function() + { + // If we've already attached to this object + if ($(this).data('Jcrop')) + { + // The API can be requested this way (undocumented) + if (options == 'api') return $(this).data('Jcrop'); + // Otherwise, we just reset the options... + else $(this).data('Jcrop').setOptions(options); + } + // If we haven't been attached, preload and attach + else attachWhenDone(this); + }); + + // Return "this" so we're chainable a la jQuery plugin-style! + return this; +}; +/*}}}*/ + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/javascript/jquery.numeric.js b/Toolkit/PHPImageEditor/javascript/jquery.numeric.js new file mode 100644 index 0000000..5c5aae7 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/jquery.numeric.js @@ -0,0 +1,127 @@ +/* + * + * Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk) + * Licensed under the MIT License: + * http://www.opensource.org/licenses/mit-license.php + * + * Version 1.0 + * Demo: http://www.texotela.co.uk/code/jquery/numeric/ + * + * $LastChangedDate: 2007-05-29 11:31:36 +0100 (Tue, 29 May 2007) $ + * $Rev: 2005 $ + */ + +/* + * Allows only valid characters to be entered into input boxes. + * Note: does not validate that the final text is a valid number + * (that could be done by another script, or server-side) + * + * @name numeric + * @param decimal Decimal separator (e.g. '.' or ',' - default is '.') + * @param callback A function that runs if the number is not valid (fires onblur) + * @author Sam Collett (http://www.texotela.co.uk) + * @example $(".numeric").numeric(); + * @example $(".numeric").numeric(","); + * @example $(".numeric").numeric(null, callback); + * + */ +jQuery.fn.numeric = function(decimal, callback) +{ + decimal = decimal || "."; + callback = typeof callback == "function" ? callback : function(){}; + this.keypress( + function(e) + { + var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; + // allow enter/return key (only when in an input box) + if(key == 13 && this.nodeName.toLowerCase() == "input") + { + return true; + } + else if(key == 13) + { + return false; + } + var allow = false; + // allow Ctrl+A + if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true; + // allow Ctrl+X (cut) + if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true; + // allow Ctrl+C (copy) + if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true; + // allow Ctrl+Z (undo) + if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true; + // allow or deny Ctrl+V (paste), Shift+Ins + if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */ + || (e.shiftKey && key == 45)) return true; + // if a number was not pressed + if(key < 48 || key > 57) + { + /* '-' only allowed at start */ + if(key == 45 && this.value.length == 0) return true; + /* only one decimal separator allowed */ + if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1) + { + allow = false; + } + // check for other keys that have special purposes + if( + key != 8 /* backspace */ && + key != 9 /* tab */ && + key != 13 /* enter */ && + key != 35 /* end */ && + key != 36 /* home */ && + key != 37 /* left */ && + key != 39 /* right */ && + key != 46 /* del */ + ) + { + allow = false; + } + else + { + // for detecting special keys (listed above) + // IE does not support 'charCode' and ignores them in keypress anyway + if(typeof e.charCode != "undefined") + { + // special keys have 'keyCode' and 'which' the same (e.g. backspace) + if(e.keyCode == e.which && e.which != 0) + { + allow = true; + } + // or keyCode != 0 and 'charCode'/'which' = 0 + else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0) + { + allow = true; + } + } + } + // if key pressed is the decimal and it is not already in the field + if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1) + { + allow = true; + } + } + else + { + allow = true; + } + return allow; + } + ) + .blur( + function() + { + var val = jQuery(this).val(); + if(val != "") + { + var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+"); + if(!re.exec(val)) + { + callback.apply(this); + } + } + } + ); + return this; +} \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/javascript/phpimageeditor.js b/Toolkit/PHPImageEditor/javascript/phpimageeditor.js new file mode 100644 index 0000000..bb37f83 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/phpimageeditor.js @@ -0,0 +1,711 @@ +var objCrop = null; + +function ajax_post() +{ + if ($('#loading').css('display') == 'none') { + $('#width').attr('disabled','disabled'); + $('#height').attr('disabled','disabled'); + $('#keepproportions').attr('disabled','disabled'); + $('#btnRotateLeft').attr('disabled','disabled'); + $('#btnRotateRight').attr('disabled','disabled'); + $('#croptop').attr('disabled','disabled'); + $('#cropbottom').attr('disabled','disabled'); + $('#cropleft').attr('disabled','disabled'); + $('#cropright').attr('disabled','disabled'); + $('#grayscale').attr('disabled','disabled'); + $('#btnupdate').attr('disabled','disabled'); + $('#btnsave').attr('disabled','disabled'); + $('#btnundo').attr('disabled','disabled'); + $('#brightness_slider_track').slider('disable'); + $('#contrast_slider_track').slider('disable'); + + $('#loading').css('display','block'); + $('#loading_bar').width(0); + $('#loading_bar').animate({width: document.getElementById('loading').offsetWidth-30}, document.getElementById('loading').offsetWidth*10); + + $.ajax({ + timeout: AjaxPostTimeoutMs, + type: "POST", + url: FormAction, + data: "grayscaleval="+$('#grayscaleval').val()+ + "&keepproportionsval="+$('#keepproportionsval').val()+ + "&image_name="+$('#image_name').val()+ + "&width="+$('#width').val()+ + "&widthoriginal="+$('#widthoriginal').val()+ + "&height="+$('#height').val()+ + "&heightoriginal="+$('#heightoriginal').val()+ + "&rotate="+$('#rotate').val()+ + "&croptop="+$('#croptop').val()+ + "&cropleft="+$('#cropleft').val()+ + "&cropright="+$('#cropright').val()+ + "&cropbottom="+$('#cropbottom').val()+ + "&contrast="+$('#contrast').val()+ + "&brightness="+$('#brightness').val()+ + "&actiontype="+$('#actiontype').val()+ + "&panel="+$('#panel').val()+ + "&language="+$('#language').val()+ + "&actions="+$('#actions').val()+ + "&widthlast="+$('#widthlast').val()+ + "&heightlast="+$('#heightlast').val()+ + "&userid="+$('#userid').val()+ + "&contrastlast="+$('#contrastlast').val()+ + "&brightnesslast="+$('#brightnesslast').val()+ + "&widthlastbeforeresize="+$('#widthlastbeforeresize').val()+ + "&heightlastbeforeresize="+$('#heightlastbeforeresize').val()+ + "&cropkeepproportionsval="+$('#cropkeepproportionsval').val()+ + "&cropkeepproportionsratio="+$('#cropkeepproportionsratio').val()+ + "&isajaxpost=true", + success: function(data) + { + $('#phpImageEditor').html(data); + activate_form(); + phpimageeditor_crop_activator(parseInt($('#panel').val())); + phpimageeditor_init(); + $('#loading_bar').stop(); + $('#loading').css('display','none'); + }, + error: function(XMLHttpRequest, textStatus, errorThrown) + { + activate_form(); + $('#ulJsErrors').html(""); + adderror(TextAnUnexpectedError); + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + phpimageeditor_crop_activator(parseInt($('#panel').val())); + $('#loading_bar').stop(); + $('#loading').css('display','none'); + } + }); + + } +} + +function isinteger(s) +{ + var i; + + if (isempty(s)) + if (isinteger.arguments.length == 1) return 0; + else return (isinteger.arguments[1] == true); + + for (i = 0; i < s.length; i++) + { + var c = s.charAt(i); + + if (!isdigit(c)) return false; + } + + return true; +} + +function focus_on_enter(element, event) +{ + if(event.keyCode == 13) + element.focus(); +} + +function reload_mouse_crop() +{ + objCrop.destroy(); + objCrop = $.Jcrop('#image',{onChange: set_crop_values,onSelect: set_crop_values, aspectRatio: $("input#cropkeepproportions").attr('checked') ? $("#cropkeepproportionsratio").val() : 0}); + $(".jcrop-holder").css("display", "none"); + $("#image").css("display", "block"); +} + +function update_width(InputWidth, EditForm) +{ + if (isinteger(InputWidth.val())) + { + var Width = parseInt($('#width').val()); + var Height = parseInt($('#height').val()); + + $('#image').css('width',Width+'px'); + + if ($("input#keepproportions").attr('checked')) + { + $('#image').css('height', get_proportional_height(Width, EditForm) + "px"); + $('#height').val(get_proportional_height(Width, EditForm)); + } + + update_mouse_resizer(); + reload_mouse_crop(); + } +} + +function update_mouse_resizer() +{ + $('#imageResizerKeepProportions').css('width',$('#width').val()+'px'); + $('#imageResizerKeepProportions').css('height',$('#height').val()+'px'); + $('#imageResizerNoProportions').css('width',$('#width').val()+'px'); + $('#imageResizerNoProportions').css('height',$('#height').val()+'px'); +} + +function update_height(InputHeight, EditForm) +{ + if (isinteger(InputHeight.val())) + { + var Height = parseInt($('#height').val()); + var Width = parseInt($('#width').val()); + + $('#image').css('height',$('#height').val()+'px'); + + if ($("input#keepproportions").attr('checked')) + { + $('#image').css('width',get_proportional_width(Height, EditForm)+'px'); + $('#width').val(get_proportional_width(Height, EditForm)); + } + + update_mouse_resizer(); + reload_mouse_crop(); + } +} + +function isempty(s) +{ + return ((s == null) || (s.length == 0)) +} + +function isdigit (c) +{ + return ((c >= "0") && (c <= "9")) +} + +function isintegerinrange(s, a, b) +{ + if (isempty(s)) + if (isintegerinrange.arguments.length == 1) return false; + else return (isintegerinrange.arguments[1] == true); + + // Catch non-integer strings to avoid creating a NaN below, + // which isn't available on JavaScript 1.0 for Windows. + if (!isinteger(s, false)) return false; + + // Now, explicitly change the type to integer via parseInt + // so that the comparison code below will work both on + // JavaScript 1.2 (which typechecks in equality comparisons) + // and JavaScript 1.1 and before (which doesn't). + var num = parseInt (s); + return ((num >= a) && (num <= b)); +} + +function validate_form() +{ + var sendForm = true; + + var width = $('#width').val(); + var height = $('#height').val(); + var cropleft = $('#cropleft').val(); + var cropright = $('#cropright').val(); + var croptop = $('#croptop').val(); + var cropbottom = $('#cropbottom').val(); + var imageName = $('#image_name').val(); + + $('#divJsErrors').css('display','none'); + $('#ulJsErrors').css('display','none'); + + $('#ulJsErrors').html(""); + + if (imageName == "") { + adderror("\"Image Name\" is Required!" ); + sendForm = false; + } + + if (width == "") + { + adderror("\"" + TextWidth + "\" " + TextIsRequired) + sendForm = false; + } + + if (height == "") + { + adderror("\"" + TextHeight + "\" " + TextIsRequired) + sendForm = false; + } + + if (!sendForm) + { + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + + return sendForm; + } + + if (!isinteger(width)) + { + adderror("\"" + TextWidth + "\" " + TextMustBeNumeric) + sendForm = false; + } + + if (!isinteger(height)) + { + adderror("\"" + TextHeight + "\" " + TextMustBeNumeric) + sendForm = false; + } + + if (!sendForm) + { + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + return sendForm; + } + + width = parseInt(width); + height = parseInt(height); + + if (!isintegerinrange(width, 1, ImageMaxWidth)) + { + adderror("\"" + TextWidth + "\" " + TextNotInRange + ": 1 - " + ImageMaxWidth) + sendForm = false; + } + + if (!isintegerinrange(height, 1, ImageMaxHeight)) + { + adderror("\"" + TextHeight + "\" " + TextNotInRange + ": 1 - " + ImageMaxHeight) + sendForm = false; + } + + if (!sendForm) + { + $('#divJsErrors').css('display','block'); + $('#ulJsErrors').css('display','block'); + } + + return sendForm; +} + +function adderror(ErrorText) +{ + $('#ulJsErrors').html($('#ulJsErrors').html()+'
  • '+ErrorText+'
  • '); +} + +function get_proportional_width(Height, EditForm) +{ + var HeightOriginal = parseInt($("#heightlastbeforeresize").val()); + var WidthOriginal = parseInt($("#widthlastbeforeresize").val()); + + return Math.round((WidthOriginal/HeightOriginal)*Height); +} + +function get_proportional_height(Width, EditForm) +{ + var HeightOriginal = parseInt($("#heightlastbeforeresize").val()); + var WidthOriginal = parseInt($("#widthlastbeforeresize").val()); + + return Math.round((HeightOriginal/WidthOriginal)*Width); +} + +function remove_px(Value) +{ + return Value.replace("px",""); +} + +function activate_form() +{ + $('#width').removeAttr('disabled'); + $('#height').removeAttr('disabled'); + $('#keepproportions').removeAttr('disabled'); + $('#btnRotateLeft').removeAttr('disabled'); + $('#btnRotateRight').removeAttr('disabled'); + $('#croptop').removeAttr('disabled'); + $('#cropbottom').removeAttr('disabled'); + $('#cropleft').removeAttr('disabled'); + $('#cropright').removeAttr('disabled'); + $('#grayscale').removeAttr('disabled'); + $('#btnupdate').removeAttr('disabled'); + $('#btnsave').removeAttr('disabled'); + $('#btnundo').removeAttr('disabled'); + $('#brightness_slider_track').slider('enable'); + $('#contrast_slider_track').slider('enable'); + + if ($('#actions').val() == '') + { + $('#btnundo').attr('disabled','disabled'); + $('#btnsave').attr('disabled','disabled'); + } + else + { + $('#btnundo').removeAttr('disabled'); + $('#btnsave').removeAttr('disabled'); + } +} + + +function set_crop_values(c) +{ + if (isinteger($("#height").val()) && isinteger($("#width").val())) + { + $("#croptop").val(c.y); + $("#cropbottom").val(parseInt($("#height").val()) - (c.y + c.h)); + $("#cropleft").val(c.x); + $("#cropright").val(parseInt($("#width").val()) - (c.x + c.w)); + $("#cropwidth").html(c.w); + $("#cropheight").html(c.h); + } +} + +function phpimageeditor_resize_activator(selectedIndex) +{ + if (selectedIndex == MenuResize) + { + if ($('#keepproportionsval').val() == "1") + { + $("#imageResizerKeepProportions").css("display", "block"); + $("#imageResizerNoProportions").css("display", "none"); + } + else + { + $("#imageResizerKeepProportions").css("display", "none"); + $("#imageResizerNoProportions").css("display", "block"); + } + } + else + { + $("#imageResizerKeepProportions").css("display", "none"); + $("#imageResizerNoProportions").css("display", "none"); + } +} + +function phpimageeditor_panelfade(selectedIndex) +{ + for (i = 0; i < 4; i++) + { + if ($('#panel_'+i) != null) + { + $("#panel_"+i).css('opacity','0.0'); + + if (i == selectedIndex) + { + $("#menuitem_"+i).removeClass("not-selected"); + $("#menuitem_"+i).addClass("selected"); + $("#panel_"+i).css('display','block'); + $("#panel_"+i).fadeTo("normal", 1.0); + } + else + { + $("#menuitem_"+i).removeClass("selected"); + $("#menuitem_"+i).addClass("not-selected"); + $("#panel_"+i).css('display','none'); + } + } + } + + if (selectedIndex != MenuCrop) + { + $("#cropleft").val("0"); + $("#cropright").val("0"); + $("#croptop").val("0"); + $("#cropbottom").val("0"); + $("#cropwidth").html("0"); + $("#cropheight").html("0"); + } + + phpimageeditor_resize_activator(selectedIndex); + phpimageeditor_crop_activator(selectedIndex); + + $("#panel").val(selectedIndex); +} + +function phpimageeditor_crop_activator(selectedIndex) +{ + if (objCrop != null) + { + if (selectedIndex != MenuCrop) + { + objCrop.release(); + objCrop.disable(); + $(".jcrop-holder").css("display", "none"); + $("#image").css("display", "block"); + } + else + { + objCrop.release(); + objCrop.enable(); + $(".jcrop-holder").css("display", "block"); + $("#image").css("display", "block"); + } + } +} + +function phpimageeditor_init() +{ + objCrop = $.Jcrop('#image',{onChange: set_crop_values,onSelect: set_crop_values, aspectRatio: $("input#cropkeepproportions").attr('checked') ? $("input#cropkeepproportionsratio").val() : 0}); + + $("#imageResizerKeepProportions").resizable( + { + aspectRatio: parseFloat($("input#widthlastbeforeresize").val()) / parseFloat($("input#heightlastbeforeresize").val()), + stop: function(event,ui) + { + var resize_width = parseInt(remove_px($("#imageResizerKeepProportions").css("width"))); + var resize_height = parseInt(remove_px($("#imageResizerKeepProportions").css("height"))); + + $("#image").css("width", resize_width+"px"); + $("#image").css("height", resize_height+"px"); + $("#width").val(resize_width); + $("#height").val(resize_height); + + update_mouse_resizer(); + + $("#imageResizerKeepProportions").css("opacity", "0.0"); + + reload_mouse_crop(); + }, + start: function(event,ui) + { + $("#imageResizerKeepProportions").css("opacity", "0.5"); + } + }); + + $("#imageResizerNoProportions").resizable( + { + aspectRatio: false, + stop: function(event,ui) + { + var resize_width = parseInt(remove_px($("#imageResizerNoProportions").css("width"))); + var resize_height = parseInt(remove_px($("#imageResizerNoProportions").css("height"))); + + $("#image").css("width", resize_width+"px"); + $("#image").css("height", resize_height+"px"); + $("#width").val(resize_width); + $("#height").val(resize_height); + + update_mouse_resizer(); + + $("#widthlastbeforeresize").val(resize_width); + $("#heightlastbeforeresize").val(resize_height); + $("#imageResizerKeepProportions").resizable('option','aspectRatio',parseFloat($('#widthlastbeforeresize').val())/parseFloat($('#heightlastbeforeresize').val())); + + $("#imageResizerNoProportions").css("opacity", "0.0"); + + reload_mouse_crop(); + }, + start: function(event,ui) + { + $("#imageResizerNoProportions").css("opacity", "0.5"); + } + }); + + $("#contrast_slider_track").slider({value: parseInt($("#contrast").val()) + ContrastMax, min: 1, max: ((ContrastMax*2)+1), step: 1, + stop: function(event,ui) + { + if (validate_form()) + ajax_post(); + }, + slide: function(event, ui) + { + $("#contrast").val(parseInt(ui.value)-((ContrastMax)+1)); + } + }); + + $("#brightness_slider_track").slider({value: (parseInt($("input#brightness").val())+BrightnessMax),min: 1,max: ((BrightnessMax*2)+1),step: 1, + stop: function(event,ui) + { + if (validate_form()) + ajax_post(); + }, + slide: function(event, ui) + { + $("#brightness").val(parseInt(ui.value)-(BrightnessMax+1)); + } + }); + + $("#grayscale").click(function() + { + if (validate_form()) + { + $("#grayscale").attr('checked') ? $('#grayscaleval').val('1') : $('#grayscaleval').val('0'); + ajax_post(); + } + }); + + $("#btnupdate").click(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionUpdate); + ajax_post(); + } + }); + + $("#btnundo").click(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionUndo); + ajax_post(); + } + }); + + $("#btnsave").click(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionSaveAndClose); + ajax_post(); + } + }); + + $("#btnRotateLeft").click(function() + { + if (validate_form()) + { + $("#rotate").val(ActionRotateLeft); + ajax_post(); + } + }); + + $("#btnRotateRight").click(function() + { + if (validate_form()) + { + $("#rotate").val(ActionRotateRight); + ajax_post(); + } + }); + + $("form#" + FormId).submit(function() + { + if (validate_form()) + { + $("#actiontype").val(ActionSaveAndClose); + return true; + } + return false; + }); + + $("#width").keydown(function(event) + { + focus_on_enter($("input#btnupdate"), event); + }); + + $("#width").keyup(function() + { + update_width($(this),$("form#" + FormId)); + }); + + $("#height").keydown(function(event) + { + focus_on_enter($("input#btnupdate"), event); + }); + + $("#height").keyup(function() + { + update_height($(this),$("form#" + FormId)); + }); + + $("#keepproportions").click(function() + { + if ($(this).attr('checked')) + { + $('#keepproportionsval').val('1'); + $('#imageResizerKeepProportions').css('display','block'); + $('#imageResizerNoProportions').css('display','none'); + } + else + { + $('#keepproportionsval').val('0'); + $('#imageResizerKeepProportions').css('display','none'); + $('#imageResizerNoProportions').css('display','block'); + } + }); + + + $("#cropkeepproportions").click(function() + { + if ($(this).attr('checked')) + { + $('#cropkeepproportionsval').val('1'); + } + else + { + $('#cropkeepproportionsval').val('0'); + } + }); + + $("#menuitem_" + MenuResize).click(function() + { + if ($('#panel').val() != MenuResize) + { + phpimageeditor_panelfade(MenuResize); + } + }); + + $("#menuitem_" + MenuRotate).click(function() + { + if ($('#panel').val() != MenuRotate) + { + phpimageeditor_panelfade(MenuRotate); + } + }); + + $("#menuitem_" + MenuCrop).click(function() + { + if ($('#panel').val() != MenuCrop) + { + phpimageeditor_panelfade(MenuCrop); + } + }); + + if ($("#menuitem_" + MenuEffects) != null) + { + $("#menuitem_" + MenuEffects).click(function() + { + if ($('#panel').val() != MenuEffects) + { + phpimageeditor_panelfade(MenuEffects); + } + }); + } + + $('#cropkeepproportions').change(function(e) + { + if (objCrop != null) + { + if (this.checked && parseFloat($("#cropwidth").html()) != 0 && parseFloat($("#cropheight").html()) != 0) + { + var aspectRatio = parseFloat($("#cropwidth").html()) / parseFloat($("#cropheight").html()); + objCrop.setOptions({ aspectRatio: aspectRatio }); + $("#cropkeepproportionsratio").val(aspectRatio); + } + else if (this.checked && parseFloat($("#cropwidth").html()) == 0 && parseFloat($("#cropheight").html()) == 0) + { + objCrop.setOptions({ aspectRatio: $("#cropkeepproportionsratio").val() }); + } + else + { + objCrop.setOptions({ aspectRatio: 0 }); + } + } + }); + + $("input#width").numeric(); + $("input#height").numeric(); + + var selectedIndex = parseInt($('#panel').val()); + for (i = 0; i < 4; i++) + { + if ($('#panel_'+i) != null) + { + if (i == selectedIndex) + { + $("#panel_"+i).css('opacity','1.0'); + $("#panel_"+i).css('display','block'); + } + else + { + $("#panel_"+i).css('opacity','0.0'); + $("#panel_"+i).css('display','none'); + } + } + } + + phpimageeditor_crop_activator(selectedIndex); + phpimageeditor_resize_activator(selectedIndex); +} + +$(document).ready(function() +{ + phpimageeditor_init(); +});define('CKIMAGE_ORIGINAL', TOOLBOX_ORIGINAL); +define('CKIMAGE_RESIZED', TOOLBOX_RESIZED); +define('CKIMAGE_MIDSIZED', TOOLBOX_MIDSIZED); +define('CKIMAGE_THUMB', TOOLBOX_THUMB); \ No newline at end of file diff --git a/Toolkit/PHPImageEditor/javascript/ui.core.js b/Toolkit/PHPImageEditor/javascript/ui.core.js new file mode 100644 index 0000000..89300d9 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/ui.core.js @@ -0,0 +1,519 @@ +/* + * jQuery UI 1.7 + * + * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI + */ +;jQuery.ui || (function($) { + +var _remove = $.fn.remove, + isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9); + +//Helper functions and ui object +$.ui = { + version: "1.7", + + // $.ui.plugin is deprecated. Use the proxy pattern instead. + plugin: { + add: function(module, option, set) { + var proto = $.ui[module].prototype; + for(var i in set) { + proto.plugins[i] = proto.plugins[i] || []; + proto.plugins[i].push([option, set[i]]); + } + }, + call: function(instance, name, args) { + var set = instance.plugins[name]; + if(!set || !instance.element[0].parentNode) { return; } + + for (var i = 0; i < set.length; i++) { + if (instance.options[set[i][0]]) { + set[i][1].apply(instance.element, args); + } + } + } + }, + + contains: function(a, b) { + return document.compareDocumentPosition + ? a.compareDocumentPosition(b) & 16 + : a !== b && a.contains(b); + }, + + hasScroll: function(el, a) { + + //If overflow is hidden, the element might have extra content, but the user wants to hide it + if ($(el).css('overflow') == 'hidden') { return false; } + + var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop', + has = false; + + if (el[scroll] > 0) { return true; } + + // TODO: determine which cases actually cause this to happen + // if the element doesn't have the scroll set, see if it's possible to + // set the scroll + el[scroll] = 1; + has = (el[scroll] > 0); + el[scroll] = 0; + return has; + }, + + isOverAxis: function(x, reference, size) { + //Determines when x coordinate is over "b" element axis + return (x > reference) && (x < (reference + size)); + }, + + isOver: function(y, x, top, left, height, width) { + //Determines when x, y coordinates is over "b" element + return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width); + }, + + keyCode: { + BACKSPACE: 8, + CAPS_LOCK: 20, + COMMA: 188, + CONTROL: 17, + DELETE: 46, + DOWN: 40, + END: 35, + ENTER: 13, + ESCAPE: 27, + HOME: 36, + INSERT: 45, + LEFT: 37, + NUMPAD_ADD: 107, + NUMPAD_DECIMAL: 110, + NUMPAD_DIVIDE: 111, + NUMPAD_ENTER: 108, + NUMPAD_MULTIPLY: 106, + NUMPAD_SUBTRACT: 109, + PAGE_DOWN: 34, + PAGE_UP: 33, + PERIOD: 190, + RIGHT: 39, + SHIFT: 16, + SPACE: 32, + TAB: 9, + UP: 38 + } +}; + +// WAI-ARIA normalization +if (isFF2) { + var attr = $.attr, + removeAttr = $.fn.removeAttr, + ariaNS = "http://www.w3.org/2005/07/aaa", + ariaState = /^aria-/, + ariaRole = /^wairole:/; + + $.attr = function(elem, name, value) { + var set = value !== undefined; + + return (name == 'role' + ? (set + ? attr.call(this, elem, name, "wairole:" + value) + : (attr.apply(this, arguments) || "").replace(ariaRole, "")) + : (ariaState.test(name) + ? (set + ? elem.setAttributeNS(ariaNS, + name.replace(ariaState, "aaa:"), value) + : attr.call(this, elem, name.replace(ariaState, "aaa:"))) + : attr.apply(this, arguments))); + }; + + $.fn.removeAttr = function(name) { + return (ariaState.test(name) + ? this.each(function() { + this.removeAttributeNS(ariaNS, name.replace(ariaState, "")); + }) : removeAttr.call(this, name)); + }; +} + +//jQuery plugins +$.fn.extend({ + remove: function() { + // Safari has a native remove event which actually removes DOM elements, + // so we have to use triggerHandler instead of trigger (#3037). + $("*", this).add(this).each(function() { + $(this).triggerHandler("remove"); + }); + return _remove.apply(this, arguments ); + }, + + enableSelection: function() { + return this + .attr('unselectable', 'off') + .css('MozUserSelect', '') + .unbind('selectstart.ui'); + }, + + disableSelection: function() { + return this + .attr('unselectable', 'on') + .css('MozUserSelect', 'none') + .bind('selectstart.ui', function() { return false; }); + }, + + scrollParent: function() { + var scrollParent; + if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) { + scrollParent = this.parents().filter(function() { + return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); + }).eq(0); + } else { + scrollParent = this.parents().filter(function() { + return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); + }).eq(0); + } + + return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent; + } +}); + + +//Additional selectors +$.extend($.expr[':'], { + data: function(elem, i, match) { + return !!$.data(elem, match[3]); + }, + + focusable: function(element) { + var nodeName = element.nodeName.toLowerCase(), + tabIndex = $.attr(element, 'tabindex'); + return (/input|select|textarea|button|object/.test(nodeName) + ? !element.disabled + : 'a' == nodeName || 'area' == nodeName + ? element.href || !isNaN(tabIndex) + : !isNaN(tabIndex)) + // the element and all of its ancestors must be visible + // the browser may report that the area is hidden + && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length; + }, + + tabbable: function(element) { + var tabIndex = $.attr(element, 'tabindex'); + return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable'); + } +}); + + +// $.widget is a factory to create jQuery plugins +// taking some boilerplate code out of the plugin code +function getter(namespace, plugin, method, args) { + function getMethods(type) { + var methods = $[namespace][plugin][type] || []; + return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods); + } + + var methods = getMethods('getter'); + if (args.length == 1 && typeof args[0] == 'string') { + methods = methods.concat(getMethods('getterSetter')); + } + return ($.inArray(method, methods) != -1); +} + +$.widget = function(name, prototype) { + var namespace = name.split(".")[0]; + name = name.split(".")[1]; + + // create plugin method + $.fn[name] = function(options) { + var isMethodCall = (typeof options == 'string'), + args = Array.prototype.slice.call(arguments, 1); + + // prevent calls to internal methods + if (isMethodCall && options.substring(0, 1) == '_') { + return this; + } + + // handle getter methods + if (isMethodCall && getter(namespace, name, options, args)) { + var instance = $.data(this[0], name); + return (instance ? instance[options].apply(instance, args) + : undefined); + } + + // handle initialization and non-getter methods + return this.each(function() { + var instance = $.data(this, name); + + // constructor + (!instance && !isMethodCall && + $.data(this, name, new $[namespace][name](this, options))._init()); + + // method call + (instance && isMethodCall && $.isFunction(instance[options]) && + instance[options].apply(instance, args)); + }); + }; + + // create widget constructor + $[namespace] = $[namespace] || {}; + $[namespace][name] = function(element, options) { + var self = this; + + this.namespace = namespace; + this.widgetName = name; + this.widgetEventPrefix = $[namespace][name].eventPrefix || name; + this.widgetBaseClass = namespace + '-' + name; + + this.options = $.extend({}, + $.widget.defaults, + $[namespace][name].defaults, + $.metadata && $.metadata.get(element)[name], + options); + + this.element = $(element) + .bind('setData.' + name, function(event, key, value) { + if (event.target == element) { + return self._setData(key, value); + } + }) + .bind('getData.' + name, function(event, key) { + if (event.target == element) { + return self._getData(key); + } + }) + .bind('remove', function() { + return self.destroy(); + }); + }; + + // add widget prototype + $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype); + + // TODO: merge getter and getterSetter properties from widget prototype + // and plugin prototype + $[namespace][name].getterSetter = 'option'; +}; + +$.widget.prototype = { + _init: function() {}, + destroy: function() { + this.element.removeData(this.widgetName) + .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') + .removeAttr('aria-disabled'); + }, + + option: function(key, value) { + var options = key, + self = this; + + if (typeof key == "string") { + if (value === undefined) { + return this._getData(key); + } + options = {}; + options[key] = value; + } + + $.each(options, function(key, value) { + self._setData(key, value); + }); + }, + _getData: function(key) { + return this.options[key]; + }, + _setData: function(key, value) { + this.options[key] = value; + + if (key == 'disabled') { + this.element + [value ? 'addClass' : 'removeClass']( + this.widgetBaseClass + '-disabled' + ' ' + + this.namespace + '-state-disabled') + .attr("aria-disabled", value); + } + }, + + enable: function() { + this._setData('disabled', false); + }, + disable: function() { + this._setData('disabled', true); + }, + + _trigger: function(type, event, data) { + var callback = this.options[type], + eventName = (type == this.widgetEventPrefix + ? type : this.widgetEventPrefix + type); + + event = $.Event(event); + event.type = eventName; + + // copy original event properties over to the new event + // this would happen if we could call $.event.fix instead of $.Event + // but we don't have a way to force an event to be fixed multiple times + if (event.originalEvent) { + for (var i = $.event.props.length, prop; i;) { + prop = $.event.props[--i]; + event[prop] = event.originalEvent[prop]; + } + } + + this.element.trigger(event, data); + + return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false + || event.isDefaultPrevented()); + } +}; + +$.widget.defaults = { + disabled: false +}; + + +/** Mouse Interaction Plugin **/ + +$.ui.mouse = { + _mouseInit: function() { + var self = this; + + this.element + .bind('mousedown.'+this.widgetName, function(event) { + return self._mouseDown(event); + }) + .bind('click.'+this.widgetName, function(event) { + if(self._preventClickEvent) { + self._preventClickEvent = false; + event.stopImmediatePropagation(); + return false; + } + }); + + // Prevent text selection in IE + if ($.browser.msie) { + this._mouseUnselectable = this.element.attr('unselectable'); + this.element.attr('unselectable', 'on'); + } + + this.started = false; + }, + + // TODO: make sure destroying one instance of mouse doesn't mess with + // other instances of mouse + _mouseDestroy: function() { + this.element.unbind('.'+this.widgetName); + + // Restore text selection in IE + ($.browser.msie + && this.element.attr('unselectable', this._mouseUnselectable)); + }, + + _mouseDown: function(event) { + // don't let more than one widget handle mouseStart + // TODO: figure out why we have to use originalEvent + event.originalEvent = event.originalEvent || {}; + if (event.originalEvent.mouseHandled) { return; } + + // we may have missed mouseup (out of window) + (this._mouseStarted && this._mouseUp(event)); + + this._mouseDownEvent = event; + + var self = this, + btnIsLeft = (event.which == 1), + elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false); + if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { + return true; + } + + this.mouseDelayMet = !this.options.delay; + if (!this.mouseDelayMet) { + this._mouseDelayTimer = setTimeout(function() { + self.mouseDelayMet = true; + }, this.options.delay); + } + + if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { + this._mouseStarted = (this._mouseStart(event) !== false); + if (!this._mouseStarted) { + event.preventDefault(); + return true; + } + } + + // these delegates are required to keep context + this._mouseMoveDelegate = function(event) { + return self._mouseMove(event); + }; + this._mouseUpDelegate = function(event) { + return self._mouseUp(event); + }; + $(document) + .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) + .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); + + // preventDefault() is used to prevent the selection of text here - + // however, in Safari, this causes select boxes not to be selectable + // anymore, so this fix is needed + ($.browser.safari || event.preventDefault()); + + event.originalEvent.mouseHandled = true; + return true; + }, + + _mouseMove: function(event) { + // IE mouseup check - mouseup happened when mouse was out of window + if ($.browser.msie && !event.button) { + return this._mouseUp(event); + } + + if (this._mouseStarted) { + this._mouseDrag(event); + return event.preventDefault(); + } + + if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { + this._mouseStarted = + (this._mouseStart(this._mouseDownEvent, event) !== false); + (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); + } + + return !this._mouseStarted; + }, + + _mouseUp: function(event) { + $(document) + .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) + .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); + + if (this._mouseStarted) { + this._mouseStarted = false; + this._preventClickEvent = (event.target == this._mouseDownEvent.target); + this._mouseStop(event); + } + + return false; + }, + + _mouseDistanceMet: function(event) { + return (Math.max( + Math.abs(this._mouseDownEvent.pageX - event.pageX), + Math.abs(this._mouseDownEvent.pageY - event.pageY) + ) >= this.options.distance + ); + }, + + _mouseDelayMet: function(event) { + return this.mouseDelayMet; + }, + + // These are placeholder methods, to be overriden by extending plugin + _mouseStart: function(event) {}, + _mouseDrag: function(event) {}, + _mouseStop: function(event) {}, + _mouseCapture: function(event) { return true; } +}; + +$.ui.mouse.defaults = { + cancel: null, + distance: 1, + delay: 0 +}; + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/javascript/ui.resizable.js b/Toolkit/PHPImageEditor/javascript/ui.resizable.js new file mode 100644 index 0000000..0e4b894 --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/ui.resizable.js @@ -0,0 +1,800 @@ +/* + * jQuery UI Resizable 1.7 + * + * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI/Resizables + * + * Depends: + * ui.core.js + */ +(function($) { + +$.widget("ui.resizable", $.extend({}, $.ui.mouse, { + + _init: function() { + + var self = this, o = this.options; + this.element.addClass("ui-resizable"); + + $.extend(this, { + _aspectRatio: !!(o.aspectRatio), + aspectRatio: o.aspectRatio, + originalElement: this.element, + _proportionallyResizeElements: [], + _helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null + }); + + //Wrap the element if it cannot hold child nodes + if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { + + //Opera fix for relative positioning + if (/relative/.test(this.element.css('position')) && $.browser.opera) + this.element.css({ position: 'relative', top: 'auto', left: 'auto' }); + + //Create a wrapper element and set the wrapper to the new current internal element + this.element.wrap( + $('
    ').css({ + position: this.element.css('position'), + width: this.element.outerWidth(), + height: this.element.outerHeight(), + top: this.element.css('top'), + left: this.element.css('left') + }) + ); + + //Overwrite the original this.element + this.element = this.element.parent().data( + "resizable", this.element.data('resizable') + ); + + this.elementIsWrapper = true; + + //Move margins to the wrapper + this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); + this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); + + //Prevent Safari textarea resize + this.originalResizeStyle = this.originalElement.css('resize'); + this.originalElement.css('resize', 'none'); + + //Push the actual element to our proportionallyResize internal array + this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' })); + + // avoid IE jump (hard set the margin) + this.originalElement.css({ margin: this.originalElement.css('margin') }); + + // fix handlers offset + this._proportionallyResize(); + + } + + this.handles = o.handles || (!$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' }); + if(this.handles.constructor == String) { + + if(this.handles == 'all') this.handles = 'n,e,s,w,se,sw,ne,nw'; + var n = this.handles.split(","); this.handles = {}; + + for(var i = 0; i < n.length; i++) { + + var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle; + var axis = $('
    '); + + // increase zIndex of sw, se, ne, nw axis + //TODO : this modifies original option + if(/sw|se|ne|nw/.test(handle)) axis.css({ zIndex: ++o.zIndex }); + + //TODO : What's going on here? + if ('se' == handle) { + axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se'); + }; + + //Insert into internal handles object and append to element + this.handles[handle] = '.ui-resizable-'+handle; + this.element.append(axis); + } + + } + + this._renderAxis = function(target) { + + target = target || this.element; + + for(var i in this.handles) { + + if(this.handles[i].constructor == String) + this.handles[i] = $(this.handles[i], this.element).show(); + + //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) + if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { + + var axis = $(this.handles[i], this.element), padWrapper = 0; + + //Checking the correct pad and border + padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); + + //The padding type i have to apply... + var padPos = [ 'padding', + /ne|nw|n/.test(i) ? 'Top' : + /se|sw|s/.test(i) ? 'Bottom' : + /^e$/.test(i) ? 'Right' : 'Left' ].join(""); + + target.css(padPos, padWrapper); + + this._proportionallyResize(); + + } + + //TODO: What's that good for? There's not anything to be executed left + if(!$(this.handles[i]).length) + continue; + + } + }; + + //TODO: make renderAxis a prototype function + this._renderAxis(this.element); + + this._handles = $('.ui-resizable-handle', this.element) + .disableSelection(); + + //Matching axis name + this._handles.mouseover(function() { + if (!self.resizing) { + if (this.className) + var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); + //Axis, default = se + self.axis = axis && axis[1] ? axis[1] : 'se'; + } + }); + + //If we want to auto hide the elements + if (o.autoHide) { + this._handles.hide(); + $(this.element) + .addClass("ui-resizable-autohide") + .hover(function() { + $(this).removeClass("ui-resizable-autohide"); + self._handles.show(); + }, + function(){ + if (!self.resizing) { + $(this).addClass("ui-resizable-autohide"); + self._handles.hide(); + } + }); + } + + //Initialize the mouse interaction + this._mouseInit(); + + }, + + destroy: function() { + + this._mouseDestroy(); + + var _destroy = function(exp) { + $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") + .removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove(); + }; + + //TODO: Unwrap at same DOM position + if (this.elementIsWrapper) { + _destroy(this.element); + var wrapper = this.element; + wrapper.parent().append( + this.originalElement.css({ + position: wrapper.css('position'), + width: wrapper.outerWidth(), + height: wrapper.outerHeight(), + top: wrapper.css('top'), + left: wrapper.css('left') + }) + ).end().remove(); + } + + this.originalElement.css('resize', this.originalResizeStyle); + _destroy(this.originalElement); + + }, + + _mouseCapture: function(event) { + + var handle = false; + for(var i in this.handles) { + if($(this.handles[i])[0] == event.target) handle = true; + } + + return this.options.disabled || !!handle; + + }, + + _mouseStart: function(event) { + + var o = this.options, iniPos = this.element.position(), el = this.element; + + this.resizing = true; + this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() }; + + // bugfix for http://dev.jquery.com/ticket/1749 + if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) { + el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left }); + } + + //Opera fixing relative position + if ($.browser.opera && (/relative/).test(el.css('position'))) + el.css({ position: 'relative', top: 'auto', left: 'auto' }); + + this._renderProxy(); + + var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top')); + + if (o.containment) { + curleft += $(o.containment).scrollLeft() || 0; + curtop += $(o.containment).scrollTop() || 0; + } + + //Store needed variables + this.offset = this.helper.offset(); + this.position = { left: curleft, top: curtop }; + this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; + this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; + this.originalPosition = { left: curleft, top: curtop }; + this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; + this.originalMousePosition = { left: event.pageX, top: event.pageY }; + + //Aspect Ratio + this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); + + var cursor = $('.ui-resizable-' + this.axis).css('cursor'); + $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor); + + el.addClass("ui-resizable-resizing"); + this._propagate("start", event); + return true; + }, + + _mouseDrag: function(event) { + + //Increase performance, avoid regex + var el = this.helper, o = this.options, props = {}, + self = this, smp = this.originalMousePosition, a = this.axis; + + var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0; + var trigger = this._change[a]; + if (!trigger) return false; + + // Calculate the attrs that will be change + var data = trigger.apply(this, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff; + + if (this._aspectRatio || event.shiftKey) + data = this._updateRatio(data, event); + + data = this._respectSize(data, event); + + // plugins callbacks need to be called first + this._propagate("resize", event); + + el.css({ + top: this.position.top + "px", left: this.position.left + "px", + width: this.size.width + "px", height: this.size.height + "px" + }); + + if (!this._helper && this._proportionallyResizeElements.length) + this._proportionallyResize(); + + this._updateCache(data); + + // calling the user callback at the end + this._trigger('resize', event, this.ui()); + + return false; + }, + + _mouseStop: function(event) { + + this.resizing = false; + var o = this.options, self = this; + + if(this._helper) { + var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), + soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, + soffsetw = ista ? 0 : self.sizeDiff.width; + + var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) }, + left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, + top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; + + if (!o.animate) + this.element.css($.extend(s, { top: top, left: left })); + + self.helper.height(self.size.height); + self.helper.width(self.size.width); + + if (this._helper && !o.animate) this._proportionallyResize(); + } + + $('body').css('cursor', 'auto'); + + this.element.removeClass("ui-resizable-resizing"); + + this._propagate("stop", event); + + if (this._helper) this.helper.remove(); + return false; + + }, + + _updateCache: function(data) { + var o = this.options; + this.offset = this.helper.offset(); + if (isNumber(data.left)) this.position.left = data.left; + if (isNumber(data.top)) this.position.top = data.top; + if (isNumber(data.height)) this.size.height = data.height; + if (isNumber(data.width)) this.size.width = data.width; + }, + + _updateRatio: function(data, event) { + + var o = this.options, cpos = this.position, csize = this.size, a = this.axis; + + if (data.height) data.width = (csize.height * this.aspectRatio); + else if (data.width) data.height = (csize.width / this.aspectRatio); + + if (a == 'sw') { + data.left = cpos.left + (csize.width - data.width); + data.top = null; + } + if (a == 'nw') { + data.top = cpos.top + (csize.height - data.height); + data.left = cpos.left + (csize.width - data.width); + } + + return data; + }, + + _respectSize: function(data, event) { + + var el = this.helper, o = this.options, pRatio = this._aspectRatio || event.shiftKey, a = this.axis, + ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), + isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height); + + if (isminw) data.width = o.minWidth; + if (isminh) data.height = o.minHeight; + if (ismaxw) data.width = o.maxWidth; + if (ismaxh) data.height = o.maxHeight; + + var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height; + var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); + + if (isminw && cw) data.left = dw - o.minWidth; + if (ismaxw && cw) data.left = dw - o.maxWidth; + if (isminh && ch) data.top = dh - o.minHeight; + if (ismaxh && ch) data.top = dh - o.maxHeight; + + // fixing jump error on top/left - bug #2330 + var isNotwh = !data.width && !data.height; + if (isNotwh && !data.left && data.top) data.top = null; + else if (isNotwh && !data.top && data.left) data.left = null; + + return data; + }, + + _proportionallyResize: function() { + + var o = this.options; + if (!this._proportionallyResizeElements.length) return; + var element = this.helper || this.element; + + for (var i=0; i < this._proportionallyResizeElements.length; i++) { + + var prel = this._proportionallyResizeElements[i]; + + if (!this.borderDif) { + var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')], + p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')]; + + this.borderDif = $.map(b, function(v, i) { + var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0; + return border + padding; + }); + } + + if ($.browser.msie && !(!($(element).is(':hidden') || $(element).parents(':hidden').length))) + continue; + + prel.css({ + height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, + width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 + }); + + }; + + }, + + _renderProxy: function() { + + var el = this.element, o = this.options; + this.elementOffset = el.offset(); + + if(this._helper) { + + this.helper = this.helper || $('
    '); + + // fix ie6 offset TODO: This seems broken + var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0), + pxyoffset = ( ie6 ? 2 : -1 ); + + this.helper.addClass(this._helper).css({ + width: this.element.outerWidth() + pxyoffset, + height: this.element.outerHeight() + pxyoffset, + position: 'absolute', + left: this.elementOffset.left - ie6offset +'px', + top: this.elementOffset.top - ie6offset +'px', + zIndex: ++o.zIndex //TODO: Don't modify option + }); + + this.helper + .appendTo("body") + .disableSelection(); + + } else { + this.helper = this.element; + } + + }, + + _change: { + e: function(event, dx, dy) { + return { width: this.originalSize.width + dx }; + }, + w: function(event, dx, dy) { + var o = this.options, cs = this.originalSize, sp = this.originalPosition; + return { left: sp.left + dx, width: cs.width - dx }; + }, + n: function(event, dx, dy) { + var o = this.options, cs = this.originalSize, sp = this.originalPosition; + return { top: sp.top + dy, height: cs.height - dy }; + }, + s: function(event, dx, dy) { + return { height: this.originalSize.height + dy }; + }, + se: function(event, dx, dy) { + return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); + }, + sw: function(event, dx, dy) { + return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); + }, + ne: function(event, dx, dy) { + return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); + }, + nw: function(event, dx, dy) { + return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); + } + }, + + _propagate: function(n, event) { + $.ui.plugin.call(this, n, [event, this.ui()]); + (n != "resize" && this._trigger(n, event, this.ui())); + }, + + plugins: {}, + + ui: function() { + return { + originalElement: this.originalElement, + element: this.element, + helper: this.helper, + position: this.position, + size: this.size, + originalSize: this.originalSize, + originalPosition: this.originalPosition + }; + } + +})); + +$.extend($.ui.resizable, { + version: "1.7", + eventPrefix: "resize", + defaults: { + alsoResize: false, + animate: false, + animateDuration: "slow", + animateEasing: "swing", + aspectRatio: false, + autoHide: false, + cancel: ":input,option", + containment: false, + delay: 0, + distance: 1, + ghost: false, + grid: false, + handles: "e,s,se", + helper: false, + maxHeight: null, + maxWidth: null, + minHeight: 10, + minWidth: 10, + zIndex: 1000 + } +}); + +/* + * Resizable Extensions + */ + +$.ui.plugin.add("resizable", "alsoResize", { + + start: function(event, ui) { + + var self = $(this).data("resizable"), o = self.options; + + _store = function(exp) { + $(exp).each(function() { + $(this).data("resizable-alsoresize", { + width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10), + left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10) + }); + }); + }; + + if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) { + if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } + else { $.each(o.alsoResize, function(exp, c) { _store(exp); }); } + }else{ + _store(o.alsoResize); + } + }, + + resize: function(event, ui){ + var self = $(this).data("resizable"), o = self.options, os = self.originalSize, op = self.originalPosition; + + var delta = { + height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0, + top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0 + }, + + _alsoResize = function(exp, c) { + $(exp).each(function() { + var el = $(this), start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left']; + + $.each(css || ['width', 'height', 'top', 'left'], function(i, prop) { + var sum = (start[prop]||0) + (delta[prop]||0); + if (sum && sum >= 0) + style[prop] = sum || null; + }); + + //Opera fixing relative position + if (/relative/.test(el.css('position')) && $.browser.opera) { + self._revertToRelativePosition = true; + el.css({ position: 'absolute', top: 'auto', left: 'auto' }); + } + + el.css(style); + }); + }; + + if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) { + $.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); }); + }else{ + _alsoResize(o.alsoResize); + } + }, + + stop: function(event, ui){ + var self = $(this).data("resizable"); + + //Opera fixing relative position + if (self._revertToRelativePosition && $.browser.opera) { + self._revertToRelativePosition = false; + el.css({ position: 'relative' }); + } + + $(this).removeData("resizable-alsoresize-start"); + } +}); + +$.ui.plugin.add("resizable", "animate", { + + stop: function(event, ui) { + var self = $(this).data("resizable"), o = self.options; + + var pr = self._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), + soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, + soffsetw = ista ? 0 : self.sizeDiff.width; + + var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) }, + left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, + top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; + + self.element.animate( + $.extend(style, top && left ? { top: top, left: left } : {}), { + duration: o.animateDuration, + easing: o.animateEasing, + step: function() { + + var data = { + width: parseInt(self.element.css('width'), 10), + height: parseInt(self.element.css('height'), 10), + top: parseInt(self.element.css('top'), 10), + left: parseInt(self.element.css('left'), 10) + }; + + if (pr && pr.length) $(pr[0]).css({ width: data.width, height: data.height }); + + // propagating resize, and updating values for each animation step + self._updateCache(data); + self._propagate("resize", event); + + } + } + ); + } + +}); + +$.ui.plugin.add("resizable", "containment", { + + start: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, el = self.element; + var oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc; + if (!ce) return; + + self.containerElement = $(ce); + + if (/document/.test(oc) || oc == document) { + self.containerOffset = { left: 0, top: 0 }; + self.containerPosition = { left: 0, top: 0 }; + + self.parentData = { + element: $(document), left: 0, top: 0, + width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight + }; + } + + // i'm a node, so compute top, left, right, bottom + else { + var element = $(ce), p = []; + $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); }); + + self.containerOffset = element.offset(); + self.containerPosition = element.position(); + self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) }; + + var co = self.containerOffset, ch = self.containerSize.height, cw = self.containerSize.width, + width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch); + + self.parentData = { + element: ce, left: co.left, top: co.top, width: width, height: height + }; + } + }, + + resize: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, + ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position, + pRatio = o._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement; + + if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co; + + if (cp.left < (self._helper ? co.left : 0)) { + self.size.width = self.size.width + (self._helper ? (self.position.left - co.left) : (self.position.left - cop.left)); + if (pRatio) self.size.height = self.size.width / o.aspectRatio; + self.position.left = o.helper ? co.left : 0; + } + + if (cp.top < (self._helper ? co.top : 0)) { + self.size.height = self.size.height + (self._helper ? (self.position.top - co.top) : self.position.top); + if (pRatio) self.size.width = self.size.height * o.aspectRatio; + self.position.top = self._helper ? co.top : 0; + } + + self.offset.left = self.parentData.left+self.position.left; + self.offset.top = self.parentData.top+self.position.top; + + var woset = Math.abs( (self._helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ), + hoset = Math.abs( (self._helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height ); + + var isParent = self.containerElement.get(0) == self.element.parent().get(0), + isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position')); + + if(isParent && isOffsetRelative) woset -= self.parentData.left; + + if (woset + self.size.width >= self.parentData.width) { + self.size.width = self.parentData.width - woset; + if (pRatio) self.size.height = self.size.width / o.aspectRatio; + } + + if (hoset + self.size.height >= self.parentData.height) { + self.size.height = self.parentData.height - hoset; + if (pRatio) self.size.width = self.size.height * o.aspectRatio; + } + }, + + stop: function(event, ui){ + var self = $(this).data("resizable"), o = self.options, cp = self.position, + co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement; + + var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height; + + if (self._helper && !o.animate && (/relative/).test(ce.css('position'))) + $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); + + if (self._helper && !o.animate && (/static/).test(ce.css('position'))) + $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); + + } +}); + +$.ui.plugin.add("resizable", "ghost", { + + start: function(event, ui) { + + var self = $(this).data("resizable"), o = self.options, cs = self.size; + + self.ghost = self.originalElement.clone(); + self.ghost + .css({ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) + .addClass('ui-resizable-ghost') + .addClass(typeof o.ghost == 'string' ? o.ghost : ''); + + self.ghost.appendTo(self.helper); + + }, + + resize: function(event, ui){ + var self = $(this).data("resizable"), o = self.options; + if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width }); + }, + + stop: function(event, ui){ + var self = $(this).data("resizable"), o = self.options; + if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0)); + } + +}); + +$.ui.plugin.add("resizable", "grid", { + + resize: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.shiftKey; + o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid; + var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1); + + if (/^(se|s|e)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + } + else if (/^(ne)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.top = op.top - oy; + } + else if (/^(sw)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.left = op.left - ox; + } + else { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.top = op.top - oy; + self.position.left = op.left - ox; + } + } + +}); + +var num = function(v) { + return parseInt(v, 10) || 0; +}; + +var isNumber = function(value) { + return !isNaN(parseInt(value, 10)); +}; + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/javascript/ui.slider.js b/Toolkit/PHPImageEditor/javascript/ui.slider.js new file mode 100644 index 0000000..a7b4d0c --- /dev/null +++ b/Toolkit/PHPImageEditor/javascript/ui.slider.js @@ -0,0 +1,511 @@ +/* + * jQuery UI Slider 1.7 + * + * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI/Slider + * + * Depends: + * ui.core.js + */ + +(function($) { + +$.widget("ui.slider", $.extend({}, $.ui.mouse, { + + _init: function() { + + var self = this, o = this.options; + this._keySliding = false; + this._handleIndex = null; + this._detectOrientation(); + this._mouseInit(); + + this.element + .addClass("ui-slider" + + " ui-slider-" + this.orientation + + " ui-widget" + + " ui-widget-content" + + " ui-corner-all"); + + this.range = $([]); + + if (o.range) { + + if (o.range === true) { + this.range = $('
    '); + if (!o.values) o.values = [this._valueMin(), this._valueMin()]; + if (o.values.length && o.values.length != 2) { + o.values = [o.values[0], o.values[0]]; + } + } else { + this.range = $('
    '); + } + + this.range + .appendTo(this.element) + .addClass("ui-slider-range"); + + if (o.range == "min" || o.range == "max") { + this.range.addClass("ui-slider-range-" + o.range); + } + + // note: this isn't the most fittingly semantic framework class for this element, + // but worked best visually with a variety of themes + this.range.addClass("ui-widget-header"); + + } + + if ($(".ui-slider-handle", this.element).length == 0) + $('') + .appendTo(this.element) + .addClass("ui-slider-handle"); + + if (o.values && o.values.length) { + while ($(".ui-slider-handle", this.element).length < o.values.length) + $('') + .appendTo(this.element) + .addClass("ui-slider-handle"); + } + + this.handles = $(".ui-slider-handle", this.element) + .addClass("ui-state-default" + + " ui-corner-all"); + + this.handle = this.handles.eq(0); + + this.handles.add(this.range).filter("a") + .click(function(event) { event.preventDefault(); }) + .hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); }) + .focus(function() { $(".ui-slider .ui-state-focus").removeClass('ui-state-focus'); $(this).addClass('ui-state-focus'); }) + .blur(function() { $(this).removeClass('ui-state-focus'); }); + + this.handles.each(function(i) { + $(this).data("index.ui-slider-handle", i); + }); + + this.handles.keydown(function(event) { + + var ret = true; + + var index = $(this).data("index.ui-slider-handle"); + + if (self.options.disabled) + return; + + switch (event.keyCode) { + case $.ui.keyCode.HOME: + case $.ui.keyCode.END: + case $.ui.keyCode.UP: + case $.ui.keyCode.RIGHT: + case $.ui.keyCode.DOWN: + case $.ui.keyCode.LEFT: + ret = false; + if (!self._keySliding) { + self._keySliding = true; + $(this).addClass("ui-state-active"); + self._start(event, index); + } + break; + } + + var curVal, newVal, step = self._step(); + if (self.options.values && self.options.values.length) { + curVal = newVal = self.values(index); + } else { + curVal = newVal = self.value(); + } + + switch (event.keyCode) { + case $.ui.keyCode.HOME: + newVal = self._valueMin(); + break; + case $.ui.keyCode.END: + newVal = self._valueMax(); + break; + case $.ui.keyCode.UP: + case $.ui.keyCode.RIGHT: + if(curVal == self._valueMax()) return; + newVal = curVal + step; + break; + case $.ui.keyCode.DOWN: + case $.ui.keyCode.LEFT: + if(curVal == self._valueMin()) return; + newVal = curVal - step; + break; + } + + self._slide(event, index, newVal); + + return ret; + + }).keyup(function(event) { + + var index = $(this).data("index.ui-slider-handle"); + + if (self._keySliding) { + self._stop(event, index); + self._change(event, index); + self._keySliding = false; + $(this).removeClass("ui-state-active"); + } + + }); + + this._refreshValue(); + + }, + + destroy: function() { + + this.handles.remove(); + + this.element + .removeClass("ui-slider" + + " ui-slider-horizontal" + + " ui-slider-vertical" + + " ui-slider-disabled" + + " ui-widget" + + " ui-widget-content" + + " ui-corner-all") + .removeData("slider") + .unbind(".slider"); + + this._mouseDestroy(); + + }, + + _mouseCapture: function(event) { + + var o = this.options; + + if (o.disabled) + return false; + + this.elementSize = { + width: this.element.outerWidth(), + height: this.element.outerHeight() + }; + this.elementOffset = this.element.offset(); + + var position = { x: event.pageX, y: event.pageY }; + var normValue = this._normValueFromMouse(position); + + var distance = this._valueMax() + 1, closestHandle; + var self = this, index; + this.handles.each(function(i) { + var thisDistance = Math.abs(normValue - self.values(i)); + if (distance > thisDistance) { + distance = thisDistance; + closestHandle = $(this); + index = i; + } + }); + + // workaround for bug #3736 (if both handles of a range are at 0, + // the first is always used as the one with least distance, + // and moving it is obviously prevented by preventing negative ranges) + if(o.range == true && this.values(1) == o.min) { + closestHandle = $(this.handles[++index]); + } + + this._start(event, index); + + self._handleIndex = index; + + closestHandle + .addClass("ui-state-active") + .focus(); + + var offset = closestHandle.offset(); + var mouseOverHandle = !$(event.target).parents().andSelf().is('.ui-slider-handle'); + this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { + left: event.pageX - offset.left - (closestHandle.width() / 2), + top: event.pageY - offset.top + - (closestHandle.height() / 2) + - (parseInt(closestHandle.css('borderTopWidth'),10) || 0) + - (parseInt(closestHandle.css('borderBottomWidth'),10) || 0) + + (parseInt(closestHandle.css('marginTop'),10) || 0) + }; + + normValue = this._normValueFromMouse(position); + this._slide(event, index, normValue); + return true; + + }, + + _mouseStart: function(event) { + return true; + }, + + _mouseDrag: function(event) { + + var position = { x: event.pageX, y: event.pageY }; + var normValue = this._normValueFromMouse(position); + + this._slide(event, this._handleIndex, normValue); + + return false; + + }, + + _mouseStop: function(event) { + + this.handles.removeClass("ui-state-active"); + this._stop(event, this._handleIndex); + this._change(event, this._handleIndex); + this._handleIndex = null; + this._clickOffset = null; + + return false; + + }, + + _detectOrientation: function() { + this.orientation = this.options.orientation == 'vertical' ? 'vertical' : 'horizontal'; + }, + + _normValueFromMouse: function(position) { + + var pixelTotal, pixelMouse; + if ('horizontal' == this.orientation) { + pixelTotal = this.elementSize.width; + pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0); + } else { + pixelTotal = this.elementSize.height; + pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0); + } + + var percentMouse = (pixelMouse / pixelTotal); + if (percentMouse > 1) percentMouse = 1; + if (percentMouse < 0) percentMouse = 0; + if ('vertical' == this.orientation) + percentMouse = 1 - percentMouse; + + var valueTotal = this._valueMax() - this._valueMin(), + valueMouse = percentMouse * valueTotal, + valueMouseModStep = valueMouse % this.options.step, + normValue = this._valueMin() + valueMouse - valueMouseModStep; + + if (valueMouseModStep > (this.options.step / 2)) + normValue += this.options.step; + + // Since JavaScript has problems with large floats, round + // the final value to 5 digits after the decimal point (see #4124) + return parseFloat(normValue.toFixed(5)); + + }, + + _start: function(event, index) { + this._trigger("start", event, this._uiHash(index)); + }, + + _slide: function(event, index, newVal) { + + var handle = this.handles[index]; + + if (this.options.values && this.options.values.length) { + + var otherVal = this.values(index ? 0 : 1); + + if ((index == 0 && newVal >= otherVal) || (index == 1 && newVal <= otherVal)) + newVal = otherVal; + + if (newVal != this.values(index)) { + var newValues = this.values(); + newValues[index] = newVal; + // A slide can be canceled by returning false from the slide callback + var allowed = this._trigger("slide", event, this._uiHash(index, newVal, newValues)); + var otherVal = this.values(index ? 0 : 1); + if (allowed !== false) { + this.values(index, newVal, ( event.type == 'mousedown' && this.options.animate ), true); + } + } + + } else { + + if (newVal != this.value()) { + // A slide can be canceled by returning false from the slide callback + var allowed = this._trigger("slide", event, this._uiHash(index, newVal)); + if (allowed !== false) { + this._setData('value', newVal, ( event.type == 'mousedown' && this.options.animate )); + } + + } + + } + + }, + + _stop: function(event, index) { + this._trigger("stop", event, this._uiHash(index)); + }, + + _change: function(event, index) { + this._trigger("change", event, this._uiHash(index)); + }, + + value: function(newValue) { + + if (arguments.length) { + this._setData("value", newValue); + this._change(null, 0); + } + + return this._value(); + + }, + + values: function(index, newValue, animated, noPropagation) { + + if (arguments.length > 1) { + this.options.values[index] = newValue; + this._refreshValue(animated); + if(!noPropagation) this._change(null, index); + } + + if (arguments.length) { + if (this.options.values && this.options.values.length) { + return this._values(index); + } else { + return this.value(); + } + } else { + return this._values(); + } + + }, + + _setData: function(key, value, animated) { + + $.widget.prototype._setData.apply(this, arguments); + + switch (key) { + case 'orientation': + + this._detectOrientation(); + + this.element + .removeClass("ui-slider-horizontal ui-slider-vertical") + .addClass("ui-slider-" + this.orientation); + this._refreshValue(animated); + break; + case 'value': + this._refreshValue(animated); + break; + } + + }, + + _step: function() { + var step = this.options.step; + return step; + }, + + _value: function() { + + var val = this.options.value; + if (val < this._valueMin()) val = this._valueMin(); + if (val > this._valueMax()) val = this._valueMax(); + + return val; + + }, + + _values: function(index) { + + if (arguments.length) { + var val = this.options.values[index]; + if (val < this._valueMin()) val = this._valueMin(); + if (val > this._valueMax()) val = this._valueMax(); + + return val; + } else { + return this.options.values; + } + + }, + + _valueMin: function() { + var valueMin = this.options.min; + return valueMin; + }, + + _valueMax: function() { + var valueMax = this.options.max; + return valueMax; + }, + + _refreshValue: function(animate) { + + var oRange = this.options.range, o = this.options, self = this; + + if (this.options.values && this.options.values.length) { + var vp0, vp1; + this.handles.each(function(i, j) { + var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100; + var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; + $(this).stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); + if (self.options.range === true) { + if (self.orientation == 'horizontal') { + (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ left: valPercent + '%' }, o.animate); + (i == 1) && self.range[animate ? 'animate' : 'css']({ width: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); + } else { + (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ bottom: (valPercent) + '%' }, o.animate); + (i == 1) && self.range[animate ? 'animate' : 'css']({ height: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); + } + } + lastValPercent = valPercent; + }); + } else { + var value = this.value(), + valueMin = this._valueMin(), + valueMax = this._valueMax(), + valPercent = valueMax != valueMin + ? (value - valueMin) / (valueMax - valueMin) * 100 + : 0; + var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; + this.handle.stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); + + (oRange == "min") && (this.orientation == "horizontal") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ width: valPercent + '%' }, o.animate); + (oRange == "max") && (this.orientation == "horizontal") && this.range[animate ? 'animate' : 'css']({ width: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); + (oRange == "min") && (this.orientation == "vertical") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ height: valPercent + '%' }, o.animate); + (oRange == "max") && (this.orientation == "vertical") && this.range[animate ? 'animate' : 'css']({ height: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); + } + + }, + + _uiHash: function(index, value, values) { + + var multiple = this.options.values && this.options.values.length; + return { + handle: this.handles[index], + value: value || (multiple ? this.values(index) : this.value()), + values: values || (multiple && this.values()) + }; + + } + +})); + +$.extend($.ui.slider, { + getter: "value values", + version: "1.7", + eventPrefix: "slide", + defaults: { + animate: false, + delay: 0, + distance: 0, + max: 100, + min: 0, + orientation: 'horizontal', + range: false, + step: 1, + value: 0, + values: null + } +}); + +})(jQuery); diff --git a/Toolkit/PHPImageEditor/language/en-GB/en-GB.com_admin.ini b/Toolkit/PHPImageEditor/language/en-GB/en-GB.com_admin.ini new file mode 100644 index 0000000..0217e7e --- /dev/null +++ b/Toolkit/PHPImageEditor/language/en-GB/en-GB.com_admin.ini @@ -0,0 +1,37 @@ +#PHP IMAGE EDITOR TEXTS +EDIT IMAGE=Edit Image +RESIZE IMAGE=Resize Image +WIDTH=Width +HEIGHT=Height +KEEP PROPORTIONS=Keep Proportions +ROTATE IMAGE=Rotate Image +LEFT 90 DEGREES=Left 90 Degrees +RIGHT 90 DEGREES=Right 90 Degrees +CROP IMAGE=Crop Image +EFFECTS=Effects +SELECT EFFECT=Select Effect +SAVE AND CLOSE=Save and Close +GRAYSCALE=Grayscale +CONTRAST=Contrast +BRIGHTNESS=Brightness +DARKER=Darker +IS REQUIRED=is required +MUST BE NUMERIC=must be numeric +NOT NEGATIVE=must be a positive number +NOT IN RANGE=is not in valid range +CANT BE LARGER THEN=can´t be larger then +NO PROVIDED IMAGE=No image has been provided. +IMAGE DOES NOT EXIST=The image doesn´t exist. +INVALID IMAGE TYPE=Image must be of type jpeg, png or gif. +OLD PHP VERSION=is too old php version. Minimum is: +OLD GD VERSION=is too old GD version. Minimum is: +UNDO=Undo +UPDATE=Update +LOADING=Loading +AN UNEXPECTED ERROR=An unexpected error has occured, please try again... +RESIZE HELP=Update Width and Height fields.
    Or drag and drop in the right or bottom side of the image. +CROP HELP=Drag and drop to create a crop area on the image. +CROP WIDTH=Crop Width +CROP HEIGHT=Crop Height +CROP KEEP PROPORTIONS=Keep Crop Proportions +INSTRUCTIONS=Instructions \ No newline at end of file diff --git a/Toolkit/Page.php b/Toolkit/Page.php new file mode 100755 index 0000000..4fa024e --- /dev/null +++ b/Toolkit/Page.php @@ -0,0 +1,662 @@ + + * @copyright 2009 Gaslight Media + * @license http://demo.gaslightmedia.com Gaslight Media + * @version CVS: $Id: Page.php,v 1.11 2009/12/28 21:03:21 matrix 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", "Gaslight Media"); + + +/** + * 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 Toolkit_Page + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license http://demo.gaslightmedia.com Gaslight Media + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Page +{ + // {{{ Properties + + /** + * used on img src and style href tags + * @var $baseURL + * @access public + */ + public $baseURL; + + /** + * meta tag description element + * @var $metaTags + * @access public + */ + public $metaTags; + + /** + * Array of scripts with absolute paths + * @var $scripts array + * @access public + */ + public $scripts = array(); + + /** + * Array of style sheet with absolute paths + * @var $styles array + * @access public + */ + public $styles = array(); + + /** + * title tag node + * @var $title + * @access public + */ + public $title; + + /** + * The main content of website + * @var $toolboxContent + * @access public + */ + public $toolboxContent; + + // }}} + // {{{ __construct() + + /** + * __construct + * + * @param object $toolbox An instance of a valid GLM_TOOLBOX Object + * + * @return void + * @access public + */ + public function __construct(GLM_TEMPLATE $toolbox) + { + // determine the base url to use (for images and stylesheet urls) + $this->baseURL + = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') + ? BASE_SECURE_URL + : BASE_URL; + + // set the title of the page + $this->title = ($toolbox->title()) ? $toolbox->title() + . 'Gaslight Media' : 'Gaslight Media'; + + // set the metaTags + $this->metaTags = $toolbox->meta_tags(); + + + // determine the base url to use (for GLM_APP_BASE_URL) + $this->glmAppBaseURL + = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') + ? BASE_SECURE_URL + : GLM_APP_BASE_URL; + + // used in class + $this->toolbox = $toolbox; + $this->dbh = Toolkit_Database::getInstance(); + $this->sitemapURL = $this->baseURL . 'site-map'; + + // get top parent id if needed + $topParent = $toolbox->get_top_parent($toolbox->catid); + + // true if on home page + $this->isHomePage = (HOME_ID == $toolbox->catid); + + // pageTitle + $this->pageTitle = $toolbox->get_catheader($topParent, $toolbox->DB); + + // styles sheets are added to an array + $this->styles = array($this->baseURL . 'styles.css'); + $this->styles[] = $this->baseURL . 'toolbox.css'; + $this->styles[] = $this->baseURL . 'contactform.css'; + $this->styles[] = $this->glmAppBaseURL . 'libjs/cluetip/jquery.cluetip.css'; + $this->scripts[] = $this->glmAppBaseURL . 'libjs/jquery-1.3.2.min.js'; + + if ($toolbox->catid == HOME_ID) { + $this->scripts[] = $this->baseURL . 'libjs/jquery.cycle.all.min.js'; + $this->scripts[] = $this->baseURL . 'libjs/homeFeaturedNav.js'; + + $this->scripts[] = $this->baseURL . 'libjs/jquery.timers.js'; +// $this->scripts[] = $this->baseURL . 'libjs/jquery.autoScroller.js'; + $this->scripts[] = $this->baseURL . 'libjs/testimonials.js'; + } + + // scripts are added to an array + $this->scripts[] = $this->glmAppBaseURL . 'libjs/contactform.js'; + $this->scripts[] = $this->glmAppBaseURL . 'libjs/cluetip/jquery.cluetip.js'; + $this->scripts[] = $this->glmAppBaseURL . 'libjs/cluetip/lib/jquery.hoverIntent.js'; + $this->scripts[] = $this->glmAppBaseURL . 'libjs/cluetip/lib/jquery.bgiframe.min.js'; + + // if PHOTO_GALLERY is defined as true + if ( defined("PHOTO_GALLERY") + && PHOTO_GALLERY + && $this->isPhotoGalleryPage() + || $toolbox->catid == MEMBER_SESSION_PAGE + ) { + $this->scripts[] = $this->glmAppBaseURL . 'gallery/thickbox-3.1.1.js'; + $this->styles[] = $this->glmAppBaseURL . 'gallery/gallery.css'; + $this->styles[] = $this->glmAppBaseURL . 'gallery/thickbox.css'; + } + + // bread crumb navigation + if ($_GET['catid'] == 56 && $_GET['pcatid']) { + include_once(BASE.'classes/class_portfolio.inc'); + $portfolio =& new portfolio($this->toolbox); + $this->breadCrumbs = $portfolio->get_bread_crumbs(); + } else { + $this->breadCrumbs = $toolbox->get_bread_crumbs($toolbox->catid); + } + + // main nav + $this->mainNav = $this->getMainNav(); + + // sideNav + if ($toolbox->catid != HOME_ID && $toolbox->has_subs($topParent, $toolbox->DB)) { + $this->sideNav = $toolbox->get_side_nav($topParent); + } else { + $this->sideNav = ''; + } + + // Making News + $this->news = $this->getNews(); + $this->hasNews = !empty($this->news) ? true : false; + + // Testimonials + $this->testimonials = $this->getTestimonials(104); + $this->hasTestimonials = !empty($this->testimonials) ? true : false; + + // check if define for HOME_EVENTS is set + if (defined("HOME_EVENTS") && HOME_EVENTS) { + $this->events($toolbox); + } + + // check if define for HOME_HEADLINES is set + if (defined("HOME_HEADLINES") && HOME_HEADLINES) { + $this->headlines($toolbox); + } + + // check if define for HOME_NEWS is set + if (defined("HOME_NEWS") && HOME_NEWS) { + $this->news($toolbox); + } + + // check if define for WEATHER is set + if (defined("WEATHER") && WEATHER) { + $this->hasWeather = true; + $this->weather(); + } + + // check if define for GOOGLE_SEARCH is set + if (defined("GOOGLE_SEARCH") && GOOGLE_SEARCH) { + $this->googleSearch(); + } + + // check if define for BANNERS is set + if (defined("BANNERS") && BANNERS) { + $this->banners(&$toolbox); + } + } + + // }}} + // {{{ banners() + + /** + * Add Banner module + * + * @param unknown &$toolbox Toolbox object + * + * @return void + * @access public + */ + public function banners(&$toolbox) + { + $banners =& Toolkit_Banners::factory('Display'); + $banners->setBannerType('Bottom'); + $banners->setAvailable(); + $banners->setBannersToDisplay('fading'); + $banners->addScriptsToPage($this->scripts); + $this->hasBanner = $banners->hasBannersAvailable(); + $this->bannerAds = $banners->bannerDisplay; + } + + // }}} + // {{{ createErrorDocument() + + /** + * Create the error document page + * + * @return void + * @access public + */ + function createErrorDocument() + { + $this->baseURL = BASE_URL; + $this->homeURL = $this->toolbox->get_seo_url(HOME_ID);; + // Initiate HTML_Template_Flexy. + $template = new HTML_Template_Flexy($GLOBALS['flexyOptions']); + + // Create a template object for the 404 content part + $errorDocumentTemplate = new HTML_Template_Flexy($GLOBALS['flexyOptions']); + $errorDocumentTemplate->compile(ERROR_DOCUMENT_TEMPLATE); + $errorDocumentContents = $errorDocumentTemplate->bufferedOutputObject($this); + + // set defaults + $this->toolboxContent = $errorDocumentContents; + $this->title = '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); + } + + // }}} + // {{{ events() + + /** + * Add Event module + * + * @param object $toolbox Toolbox object + * + * @return void + * @access public + */ + public function events($toolbox) + { + // home events + $this->events = $toolbox->get_home_events(); + // boolean for if events are flagged as home + $this->hasEvents = !empty($this->hasEvents); + if ($this->hasEvents) { + $this->styles[] = BASE_URL.'event.css'; + } + } + + // }}} + // {{{ generateSiteMap() + + /** + * Generate the site map page + * + * @return string HTML sitemap string + * @access public + */ + function generateSiteMap() + { + $WHERE = ''; + if (defined(MEMBERS_CATEGORY) && defined(MEMBERS_DB)) { + $WHERE = "AND id != ".MEMBERS_CATEGORY; + } + $sql = " + SELECT * + FROM bus_category + WHERE active = 't' + $WHERE + ORDER BY parent, pos"; + + $data = $this->toolbox->DB->db_auto_get_data($sql); + if (is_array($data)) { + foreach ($data as $key => $val) { + $threads[] = array( + "id" => $val['id'], + 'category' => strip_tags($val['category']), + 'type' => $val['type'], + 'parent' => $val['parent'], + 'closed' => false); + } + } + if (is_array($threads)) { + $myThread = new Toolkit_SiteMap($this->toolbox); + //sort threads by parent + $converted = $myThread->sortChilds($threads); + //print the threads + $out .= $myThread->convertToThread($converted, $converted[0]); + } + return '
    + '.$out.' +
    '; + } + + // }}} + // {{{ getMainNav() + + /** + * getMainNav + * + * @access public + * @return string + */ + function getMainNav() + { + // die('
    '.print_r($this->toolbox->cache, true).'
    '); + if ($bottomNav = $this->toolbox->cache->get('bottomNav', 'Toolbox')) { + //die('here'); + return $bottomNav; + } else { + $sql = " + SELECT id,category + FROM bus_category + WHERE parent = 0 + AND active = 't' + AND id NOT IN (".HOME_ID.",51) + ORDER BY pos"; + try { + $stmt = $this->dbh->prepare($sql); + $stmt->execute(); + while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $mainNav[$row['id']] = array( + 'name' => $row['category'], + 'link' => $this->getToolboxUrl($row['id']), + 'hasSubs' => $this->toolbox->has_subs($row['id'], $this->toolbox->DB), + 'subs' => $this->getSubNav($row['id']) + ); + /* + */ + } + $this->toolbox->cache->save($mainNav, 'bottomNav', 'Toolbox'); + return $mainNav; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + } + // }}} + // {{{ getNews() + function getNews() + { + $sql = " + SELECT id,title,intro + FROM pressnews + WHERE status = 'current' + ORDER BY pr_date DESC"; + try { + $stmt = $this->dbh->query($sql); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $news[] = array( + 'id' => $row['id'], + 'title' => strip_tags($row['title']), + 'descr' => $row['intro'], + 'link' => BASE_URL . "press/{$row['id']}/" + ); + } + return $news; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + // }}} + // {{{ getSubNav() + + /** + * getSubNav + * + * @param mixed $parent + * + * @access public + * @return string + */ + function getSubNav($parent) + { + $sql = " + SELECT id,category + FROM bus_category + WHERE parent = :parent + AND active = 't' + ORDER BY pos"; + try { + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":parent", $parent, PDO::PARAM_INT); + $stmt->execute(); + while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $subs[] = array( + 'name' => $row['category'], + 'link' => $this->getToolboxUrl($row['id']) + ); + } + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + if ($parent == 56) { + $portfolio =& new portfolio($this->toolbox); + $portfolioCats = $portfolio->get_portfolio_categories(); + if ($portfolioCats) { + foreach ($portfolioCats as $pCatid => $pName) { + $name = ereg_replace("[?/$^%&*!@#'\"<>,]", "", $pName); + $name = str_replace(" ","-",$name); + $subs[] = array( + 'name' => $pName, + 'link' => BASE_URL.'portfolio-category/'.$name.'-'.$pCatid.'/', + 'hasSubs' => false, + 'subs' => false, + ); + } + } + } + return $subs; + } + // }}} + // {{{ getTestimonials() + /** + * Creates array for use in autoscroller script. + * + * Pulls data from the paragraphs of any catid passed in + * + * @param unknown $pageId the id of the category to pull paragraphs from + * + * @return void + * @access public + */ + function getTestimonials($pageId) + { + $sql = " + SELECT b.id, b.name, b.description + FROM bus b LEFT OUTER JOIN bus_category_bus bcb ON (b.id = bcb.busid) + WHERE bcb.catid = :catid + ORDER BY bcb.pos"; + try { + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":catid", $pageId, PDO::PARAM_INT); + $stmt->execute(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + $testimonials[] = array( + 'name' => $row['name'], + 'link' => BASE_URL + . 'index.php?catid='.$pageId.'#sect-'.$row["id"], + 'descr' => GLM_TOOLBOX::make_teaser($row['description'], 70 ,true) + ); + } + return $testimonials; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + // }}} + // {{{ getToolboxName($id) + + /** + * grab the navigation name for the id + * + * @param integer $id id for bus_category table + * + * @return string page nav name + * @access public + */ + function getToolboxName($id) + { + return $this->toolbox->get_catheader($id, $this->toolbox->DB); + } + + // }}} + // {{{ getToolboxUrl($id) + + /** + * grab the navigation url for the id + * + * @param integer $id id for bus_category table + * + * @return string url + * @access public + */ + function getToolboxUrl($id) + { + return $this->toolbox->get_seo_url($id); + } + + // }}} + + // {{{ googleSearch() + + /** + * Add Google Search module + * + * @return void + * @access public + */ + public function googleSearch() + { + $this->gSearchOn = false; + if ($_REQUEST['query']) { + $this->gSearchOn = true; + $query = urlencode($_REQUEST['query']); + $this->scripts[] = 'http://www.google.com/uds/api?file=uds.js&v=1.0&key='.GSEARCH_API; + $this->scripts[] = BASE_URL.'gsearch.css'; + $this->scripts[] = BASE_URL.'libjs/gsearch.php?query='.$query; + } + } + + // }}} + // {{{ headlines() + + /** + * grab the home page headlines + * + * @param object $toolbox Toolbox object + * + * @return void + * @access public + */ + public function headlines($toolbox) + { + // get headlines aka 'Quick Links' + $this->headlines = $toolbox->get_headlines(); + // boolean for if toolbox has headlines + $this->hasHeadlines = !empty($this->headlines); + } + + // }}} + // {{{ isPhotoGalleryPage() + + /** + * 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; + } + // }}} + // {{{ news() + + /** + * 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; + } + } + + // }}} + // {{{ weather() + + /** + * Add Weather module + * + * @return void + * @access public + */ + public function weather() + { + $weather = new Toolkit_Weather(); + $this->weather = $weather->currentCond['weather']; + $this->tempF = $weather->currentCond['temp_f']; + $this->iconUrlName = $weather->currentCond['icon_url_name']; + $this->location = $weather->currentCond['location']; + } + + // }}} +} +?> diff --git a/Toolkit/Photos/Display.php b/Toolkit/Photos/Display.php new file mode 100755 index 0000000..b28132c --- /dev/null +++ b/Toolkit/Photos/Display.php @@ -0,0 +1,248 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: Display.php,v 1.2 2009/12/15 20:18:16 jamie Exp $ + * @link <> + */ + +/** + * Toolkit_Photos_Display + * + * Display the Photo Gallery assoc to a toolbox page + * + * @category Photos + * @package Toolkit_Photos + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @link <> + */ +class Toolkit_Photos_Display +{ + // {{{ Properties + + /** + * Options for Flexy Templates + * @var array + * @access protected + */ + protected $flexyOptions = array( + 'templateDir' => '/templates', + 'compileDir' => '/templates/compiled', + 'forceCompile' => false, + 'allowPHP' => true, + ); + + /** + * page name for form action and links + * @var unknown + * @access protected + */ + protected $pageName; + + /** + * Photo Table Name + * @var string + * @access protected + */ + protected $photoTable = 'photo'; + + /** + * Photo Category Table Name + * @var string + * @access protected + */ + protected $categoryTable = 'photo_category'; + + /** + * rowCount + * + * @var float + * @access protected + */ + protected $rowCount = 3; + // }}} + // {{{ __construct() + + /** + * __construct() + * + * @return void + * @access public + */ + function __construct() + { + // assign the global dbh to $this->dbh; + $this->dbh = Toolkit_Database::getInstance(); + // set paths for templates + $this->flexyOptions['templateDir'] = dirname(__FILE__) + .$this->flexyOptions['templateDir']; + $this->flexyOptions['compileDir'] = dirname(__FILE__) + .$this->flexyOptions['compileDir']; + // the main display page for events to link to + $this->pageName = BASE_URL.'index.php?catid='.$_REQUEST['catid']; + } + + // }}} + // {{{ listPhotoCategories() + + /** + * listPhotoCategories() + * + * Display Photo Categories + * + * @return mixed Return description (if any) ... + * @access public + */ + function listPhotoCategories() + { + $sql = " + SELECT pc.* + FROM photo_category pc, photo_category_bus pcb + WHERE pcb.photocat_id = pc.id + AND pcb.buscat_id = {$_REQUEST['catid']} + ORDER BY pcb.pos;"; + try { + $data = $this->dbh->query($sql)->fetchAll(); + if (is_array($data)) { + $i = 0; + foreach ($data as &$row) { + unset($row['image']); + // use the first one from its photos + $sql = " + SELECT image + FROM photo + WHERE catid = {$row['id']} + AND image != ''"; + try { + $row2 = $this->dbh->query($sql)->fetch(); + $data[$i]['image'] = $row2['image']; + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + ++$i; + } + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass; + $page->appbase = GLM_APP_BASE_URL; + $page->page = BASE_URL.'index.php?catid='.$_REQUEST['catid'].'&photo_catid='; + $page->cats = $data; + $page->imgPath = PHOTO_SMALL_URL; + $template->compile('photoCats.html'); + return $template->bufferedOutputObject($page); + } else { + return ''; + } + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ listPhotos() + + /** + * listPhotos() + * + * Display Photos + * + * @return mixed Return description (if any) ... + * @access public + */ + function listPhotos() + { + // where clauses + if ($_REQUEST['photo_catid']) { + // grab photo album name for display + try { + $sql = " + SELECT category + FROM photo_category + WHERE id = :id"; + $stmt1 = $this->dbh->prepare($sql); + $stmt1->bindParam(":id", $_REQUEST['photo_catid'], PDO::PARAM_INT); + $stmt1->execute(); + $albumName = $stmt1->fetchColumn(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + $where[] = "catid = {$_REQUEST['photo_catid']}"; + } + // query + $sql = " + SELECT * + FROM {$this->photoTable}"; + if (is_array($where)) { + $sql .= " WHERE ".implode(" AND ", $where); + } + $sql .= " ORDER BY pos"; + try { + $data = $this->dbh->query($sql)->fetchAll(); + $count = 1; + $trueCount = 1; + $num = count($data); + foreach ($data as &$row) { + if ($count == 1) { + $row['firstInRow'] = true; + } else { + $row['firstInRow'] = false; + } + if ($count == $this->rowCount || $trueCount == $num) { + $row['lastInRow'] = true; + $count = 0; + } else { + $row['lastInRow'] = false; + } + ++$count; + ++$trueCount; + } + if (is_array($data)) { + $template = new HTML_Template_Flexy($this->flexyOptions); + $page = new stdClass; + $page->album = ($albumName) ? $albumName: 'Photo Gallery'; + $page->appbase = GLM_APP_BASE_URL; + $page->photos = $data; + $page->imgPath = PHOTO_SMALL_URL; + $page->orgPath = PHOTO_LARGE_URL; + $template->compile('photos.html'); + return $template->bufferedOutputObject($page); + } else { + return ''; + } + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ toHTML() + + /** + * toHTML() + * + * call to listPhotos function for display of Photos + * + * @return void + * @access public + */ + function toHTML() + { + if (is_array($_REQUEST['photo_catid'])) { + return $this->listPhotoCategories(); + } elseif ($_REQUEST['photo_catid']) { + return $this->listPhotos(); + } + } + + // }}} +} +?> diff --git a/Toolkit/Photos/templates/photoCats.html b/Toolkit/Photos/templates/photoCats.html new file mode 100755 index 0000000..e877442 --- /dev/null +++ b/Toolkit/Photos/templates/photoCats.html @@ -0,0 +1,8 @@ + + diff --git a/Toolkit/Photos/templates/photos.html b/Toolkit/Photos/templates/photos.html new file mode 100755 index 0000000..fdd861d --- /dev/null +++ b/Toolkit/Photos/templates/photos.html @@ -0,0 +1,15 @@ + diff --git a/Toolkit/Postcards.php b/Toolkit/Postcards.php new file mode 100644 index 0000000..970e590 --- /dev/null +++ b/Toolkit/Postcards.php @@ -0,0 +1,263 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: Postcards.php,v 1.1.1.1 2009/09/17 20:08:55 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Edit postcards stored in the DB + * + * This class acts like an interface to the admin side functionality. It controls + * which classes to call depending on what the user would like to do. + * (create/edit, list, etc..). It also handles setting up the subnav structure + * and rendering. + * + * @category Postcards + * @package Toolkit_Postcards + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://devsys2.gaslightmedia.com/demo.gaslightmedia.com/admin/postcards.php + */ +class Toolkit_Postcards +{ + // {{{ properties + + /** + * Flexy options used in the renderer + * + * @var array + * @access protected + */ + protected $options; + + /** + * The directory that holds the templates + * + * Keep this setting in relation to this file. + * + * @var string + * @access protected + */ + protected $templatesDir = 'templates'; + + /** + * The directory that holds the compiled templates + * + * Keep this setting in relation to this file. + * + * @var string + * @access protected + */ + protected $compiledTemplatesDir = 'Postcards/templates/compiled'; + + /** + * The name of the template used to render the business info form. + * + * @var string + * @access protected + */ + protected $formTemplate = 'editMember.tpl'; + + /** + * The flexy template object which holds the rendered object + * + * @var object + * @access protected + */ + protected $template; + + /** + * Form access from inside the template + * + * @var object + * @access protected + */ + protected $view; + + // }}} + // {{{ __construct() + + /** + * Object constructor + * + * @access public + */ + public function __construct() + { + echo $this->createSubNav(); + } + + // }}} + // {{{ createSubNav() + + /** + * Create the subnav to navigate the postcards + * + * I'm going to create this subnav to look like the new membersdb + * that way we can get some synergy between our applications + * + * @author Jamie Kahgee + * @return string subnavigation html + * @access public + */ + protected function createSubNav() + { + + $subnav = array( + 'List Cards' => BASE_URL . 'admin/postcards.php?a=listCards', + 'Create New Card' => BASE_URL . 'admin/postcards.php?a=add', + ); + $this->navConfig = $subnav; + + return $this->createNav(); + } + + // }}} + // {{{ makeLiLinks() + + /** + * Create the li elements that go along w/ the subnav + * + * @param string $link URI to parse + * @param string $name link text + * + * @author Jamie Kahgee + * @return void + * @access protected + */ + protected function makeLiLinks($link, $name) + { + $url = parse_url($link); + $action = end(explode('=', $url['query'])); + $homePage = (!isset($_GET['a']) && $name == 'List Cards'); + $currentPage = $_GET['a'] == $action; + if (isset($_GET['id'])) { + $link .= "&id={$_GET['id']}"; + } + if ($currentPage || $homePage) { + $attr = ' id="active"'; + $class= ' class="current"'; + } + $this->nav .= ''.$name.''; + } + + // }}} + // {{{ createNav() + + /** + * Creates the subnav structure used for the multipage forms + * + * @author Jamie Kahgee + * + * @return string UL list of navigation + * + * @access protected + * @since Method available since Release 1.0.0 + */ + protected function createNav() + { + if (array_walk($this->navConfig, array($this, 'makeLiLinks'))) { + return '
      '.$this->nav.'
    '; + } + } + + // }}} + // {{{ setupRenderers() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return void + * @access protected + */ + protected function setupRenderers() + { + $renderer =& new HTML_QuickForm_Renderer_Object(true); + + $this->accept($renderer); + + $this->template =& new HTML_Template_Flexy($this->options); + + // Make the view a copy of the $this object + // That way we have access to call functions in + // this class from within the template. + $this->view = $this; + $this->view->form = $renderer->toObject(); + $this->template->compile($this->formTemplate); + } + + // }}} + // {{{ toHTML() + + /** + * Renders the form + * + * sets the page the form should be redirected to instead of coming back + * around to itself. + * + * @author Jamie Kahgee + * @return string The rendered form + * @access public + * @since Method available since Release 1.0.0 + */ + public function toHTML() + { + // We need to validate (and freeze if needed) + // before we render the form. That way the + // template knows about any errors on the form. + $this->validated = $this->validate(); + + if ($this->validated) { + $processed = $this->process(array(&$this, 'processData'), $this->mergeFiles); + } + + // ProcessData handles settingup the lat/lon coordinates if they were not entered + // into the form. these values ar calculated and then inserted into the forms + // element values. So we need to process the data first and then render the form. + $this->setupRenderers(); + + return $this->template->bufferedOutputObject($this->view); + } + + // }}} + // {{{ show() + + /** + * Determine which form to show to the user + * + * @author Jamie Kahgee + * @return void + * @access public + */ + public function show() + { + switch ($_GET['a']) { + case 'add' : + $addPostCard =& new Toolkit_Postcards_addcard('edit_postcard', + 'post', null, null, null, true); + $addPostCard->show(); + break; + + case 'list' : + default : + break; + } + } + + // }}} +} +?> diff --git a/Toolkit/Postcards/AddCard.php b/Toolkit/Postcards/AddCard.php new file mode 100755 index 0000000..16f9f12 --- /dev/null +++ b/Toolkit/Postcards/AddCard.php @@ -0,0 +1,41 @@ + + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: AddCard.php,v 1.1.1.1 2009/09/17 20:08:57 matrix Exp $ + * @link http://demo.gaslightmedia.com + * @see References to other sections (if any)... + */ + +/** + * Short description for class + * + * Long description (if any) ... + * + * @category Postcards + * @package Toolkit_Postcards + * @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_Postcards_AddCard + extends Toolkit_FormBuilder implements Toolkit_Form +{ +} +?> diff --git a/Toolkit/Postcards/templates/subnav.tpl b/Toolkit/Postcards/templates/subnav.tpl new file mode 100755 index 0000000..23ece43 --- /dev/null +++ b/Toolkit/Postcards/templates/subnav.tpl @@ -0,0 +1,2 @@ +
    + diff --git a/Toolkit/Press/Newsletter.php b/Toolkit/Press/Newsletter.php new file mode 100755 index 0000000..9f19852 --- /dev/null +++ b/Toolkit/Press/Newsletter.php @@ -0,0 +1,356 @@ + + * @copyright 2008 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: Newsletter.php,v 1.3 2009/12/15 20:18:16 jamie Exp $ + * @link <> + */ + +/** + * Description for require_once + */ +require_once BASE.'classes/class_db.inc'; + +/** + * Description for require_once + */ +require_once BASE.'classes/class_template.inc'; + +/** + * Toolkit_PressNewsletter + * + * Updated version of Press News display + * + * @category Toolkit + * @package Toolkit_Press + * @author Steve Sutton + * @copyright 2008 Gaslight Media + * @license Gaslight Media + * @version Release: @package_version@ + * @link <> + */ +class Toolkit_Press_Newsletter +{ + // {{{ Properties + + + /** + * newscatid for news item + * @var string + * @access private + */ + private $_newscatid; + + /** + * toolbox catid + * @var unknown + * @access private + */ + private $_toolboxid; + + /** + * database omject + * @var object + * @access protected + */ + protected $DB; + + /** + * Flexy Template Options + * @var array + * @access protected + */ + protected $flexyOptions; + + /** + * form elements to be merged with template + * @var unknown + * @access public + */ + public $elements; + + /** + * Flexy template object + * @var object + * @access public + */ + public $template; + + /** + * Page object to be merged in with flexy template + * @var object + * @access public + */ + public $page; + // }}} + // {{{ __construct + + + /** + * __construct + * + * @param object $toolbox GLM_TEMPLATE + * @param unknown $catid news catid + * + * @return void + * @access public + */ + function __construct($toolbox, $catid) + { + $this->page = new glmPage(); + $this->flexyOptions = array( + 'templateDir' => BASE.'Toolkit/Press/templates', + 'compileDir' => BASE.'Toolkit/Press/templates/compile', + 'forceCompile' => true, + 'flexyIgnore' => false, + 'allowPHP' => true, + 'privates' => true, + 'globals' => true, + 'globalfunctions' => true, + 'textdomain' => BASE_URL, + 'debug' => false + ); + $this->toolbox = $toolbox; + $this->DB = $toolbox->DB; + $this->dbh = Toolkit_Database::getInstance(); + $this->template = new HTML_Template_Flexy($this->flexyOptions); + $this->page->base_url = BASE_URL; + $this->page->RESIZED = RESIZED; + $this->page->MIDSIZED = MIDSIZED; + $this->page->THUMB = THUMB; + $this->page->UP_BASE_URL = BASE_URL.'uploads/'; + $this->setNewscatid($catid); + $this->setToolboxid(); + if ($_REQUEST['newsid']) { + $this->getNews($_REQUEST['newsid']); + } else { + $this->getNewsPage($catid); + } + $this->getNewsSummary(); + $this->template->compile('news.html'); + if (isset($this->elements)) { + $this->template->outputObject($this->page, $this->elements); + } else { + $this->template->outputObject($this->page); + } + } + + + // }}} + // {{{ getNews + + + /** + * getNews + * + * Grab the news + * + * @param unknown $id id for table news + * + * @return void + * @access public + */ + function getNews($id) + { + $query = " + SET datestyle TO 'sql,us'; + SELECT * + FROM news + WHERE id = $id"; + $news_data = $this->DB->db_auto_get_data($query); + if (is_array($news_data)) { + $this->page->pr_date = $news_data[0]["pr_date"]; + $this->page->title = $news_data[0]["title"]; + $this->page->header = $news_data[0]["header"]; + if ($news_data[0]['image']) { + $this->page->image = $news_data[0]['image']; + $this->page->imgclass = "imageleft"; + if ($news_data[0]['imagename']) { + $this->page->imagename = $news_data[0]['imagename']; + } + } + $this->page->description = $this->toolbox->keyword_replace($news_data[0]["description"]); + if ($news_data[0]['file'] != '') { + $this->page->file = $news_data[0]['file']; + if ($news_data[0]['filename']) { + $this->page->filename = $news_data[0]['filename']; + } + } + $query = " + SELECT * + FROM news_block + WHERE news_id = {$news_data[0]['id']} + ORDER BY pos"; + $news_block_data = $this->DB->db_auto_get_data($query); + if (is_array($news_block_data)) { + for ($i = 0; $i < count($news_block_data); ++$i) { + $val = $news_block_data[$i]; + $this->page->section[$i]['align'] = ($i%2==0) ? "right": "left"; + $this->page->section[$i]['imgclass'] = ($i%2==0) ? "imageright": "imageleft"; + $this->page->section[$i]['header'] = $val["header"]; + if ($val['image']) { + $this->page->section[$i]['image'] = $val["image"]; + } + $this->page->section[$i]['description'] = $this->toolbox->keyword_replace($val["description"]); + if ($val['file'] != '') { + $this->page->section[$i]['file'] = $val["file"]; + if ($val['file']['filename']) { + $this->page->section[$i]['filename'] = $val["filename"]; + } + } + } + } + } + $this->template->compile('news.html'); + } + + + // }}} + // {{{ getNewsPage + + + /** + * getNewsPage + * + * get the current press newsletter + * + * @param unknown $id category id + * + * @return void + * @access public + */ + function getNewsPage($id = null) + { + // get news with catid = $newscatid + $query = " + SELECT id,catid,title,status + FROM news + WHERE catid = {$id} + AND status = 'current'"; + $data = $this->DB->db_auto_get_data($query); + if (is_array($data)) { + $catid = $data[0]['id']; + $id = $data[0]['id']; + $this->getNews($id); + } + } + + + // }}} + // {{{ getNewsSummary + + + /** + * getNewsSummary + * + * get summary of the archives + current new srelease + * + * @return void + * @access public + */ + function getNewsSummary() + { + $query = "SET datestyle TO 'SQL,US'; + SELECT id,pr_date,title + FROM news + WHERE catid = ".$this->_newscatid." + AND status != 'queued' + ORDER BY status desc,pr_date desc"; + $data2 = $this->DB->db_auto_get_data($query); + if (is_array($data2)) { + foreach ($data2 as $key => $val) { + $this->page->news_summary[$val['id']]['pr_date'] = $val['pr_date']; + $this->page->news_summary[$val['id']]['news_page'] = BASE_URL.'index.php?catid='.$_REQUEST['catid'].'&newsid='.$val["id"]; + $this->page->news_summary[$val['id']]['title'] = $val['title']; + } + } + } + + + // }}} + // {{{ getRSSFeed + + + /** + * Create RSS Feed for the newsletter/press + * This gives client ability to send a rss to their users so + * they are up to date on all newsletter post. + * Pulls all non archived news + * + * @access public + * @return string + */ + function getRSSFeed() + { + $options = array( + "indent" => " ", + "linebreak" => "\n", + "typehints" => false, + "addDec1" => true, + "encoding" => "UTF-8", + "rootName" => "rdf:RDF", + "defaultTagName" => "item", + ); + $sql = " + SELECT * + FROM news + WHERE status != 'archived' + ORDER BY status desc,pr_date desc"; + try { + $data = $this->dbh->query($sql)->fetchAll(); + echo '
    '.print_r($data, true).'
    '; + } catch(PDOException $e) { + echo '
    '.print_r($e, true).'
    '; + die($e->getMessage); + } + } + + + // }}} + // {{{ setNewscatid + + + /** + * setNewscatid + * + * sets the _newscatid + * + * @param unknown $id category id for news + * + * @return void + * @access public + */ + function setNewscatid($id) + { + $this->_newscatid = $id; + } + + + // }}} + // {{{ setToolboxid + + + /** + * setToolboxid + * + * sets the _toolboxid + * + * @return void + * @access public + */ + function setToolboxid() + { + $this->_toolboxid =& $GLOBALS['catid']; + } + + // }}} +} +?> diff --git a/Toolkit/Press/templates/news.html b/Toolkit/Press/templates/news.html new file mode 100755 index 0000000..de2148d --- /dev/null +++ b/Toolkit/Press/templates/news.html @@ -0,0 +1,34 @@ +

    {pr_date}

    +

    {title}

    +

    {header}

    +{if:image} + {if:imagename} +
    + '; +
    {imagename}
    +
    + {else:} + + {end:} +{end:} +{description:h} +{if:file} +
    {if:filename}{filename}{else:}{file}{end:}
    +{end:} +{foreach:section,k,v} +

    {v[header]}

    + {if:v[image]} + + {end:} + {v[description]:h} + {if:v[file]} +
    {if:v[filename]}{v[filename]}{else:}{v[file]}{end:}
    + {end:} +{end:} +
    +

    +{foreach:news_summary,k,v} +
    + {v[pr_date]} {v[title]} +

    +{end:} diff --git a/Toolkit/ShortURL.php b/Toolkit/ShortURL.php new file mode 100755 index 0000000..6642309 --- /dev/null +++ b/Toolkit/ShortURL.php @@ -0,0 +1,127 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: ShortURL.php,v 1.1.1.1 2009/09/17 20:08:55 matrix 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 + /** + * PDO Global object + * @var string + * @access protected + */ + public $dbh; + // }}} + + // {{{ __construct() + + /** + * __construct() + * + * @param object &$dbh from setup.phtml + * + * @return void + * @access public + */ + function __construct(&$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 bus_category + WHERE id = :id"; + try { + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":id", $id, PDO::PARAM_INT); + $stmt->execute(); + return $stmt->fetchColumn(); + } catch(PDOException $e) { + Toolkit_Common::handleError($e); + } + return false; + } + + // }}} + // {{{ 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 bus_category + 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; + } + + // }}} +} +?> diff --git a/Toolkit/SiteMap.php b/Toolkit/SiteMap.php new file mode 100755 index 0000000..a1f518b --- /dev/null +++ b/Toolkit/SiteMap.php @@ -0,0 +1,156 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: SiteMap.php,v 1.1.1.1 2009/09/17 20:08:55 matrix 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 for var + * @var string + * @access public + */ + var $beginLevel = "
      "; + + /** + * Description for var + * @var string + * @access public + */ + var $endLevel = "
    "; + + /** + * Description for var + * @var string + * @access public + */ + var $beginItem = "
  • "; + + /** + * Description for var + * @var string + * @access public + */ + var $endItem = "
  • "; + + /** + * Description for var + * @var string + * @access public + */ + var $wholeThread; + + /** + * Description for var + * @var string + * @access public + */ + var $search = ""; + + /** + * Description for var + * @var unknown + * @access public + */ + var $DB; + // }}} + // {{{ __construct() + /** + * __construct + * + * Must be given a GLM_TEMPLATE object + * + * @param mixed $toolbox GLM_TEMPLATE Object + * + * @return void + * @access public + */ + function __construct(GLM_TEMPLATE $toolbox) + { + $this->toolbox =& $toolbox; + $this->DB =& $toolbox->DB; + } + // }}} + // {{{ sortChilds() + /** + * sortChilds + * + * Sort by Parent + * + * @param unknown $threads Array + * + * @return array Return array + * @access public + */ + function sortChilds($threads) + { + 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 unknown $threads Thread array + * @param unknown $thread Start with thread[0] will work it way down + * + * @return wholeThread + * @access public + **/ + function convertToThread($threads, $thread) + { + static $p,$level_counter; + if (!$level_counter) { + $level_counter = 1; + } + $this->wholeThread .= $this->beginLevel; + while (list($parent, $value) = each($thread)) { + $this->wholeThread .= $this->beginItem; + $page = $value['url']; + $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/SortForm.php b/Toolkit/SortForm.php new file mode 100644 index 0000000..1513dd7 --- /dev/null +++ b/Toolkit/SortForm.php @@ -0,0 +1,68 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: SortForm.php,v 1.1.1.1 2009/09/17 20:08:56 matrix 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. + * + * @author Jamie Kahgee + * @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/Toolbox/Admin/EditPage.php b/Toolkit/Toolbox/Admin/EditPage.php new file mode 100644 index 0000000..e6ecddf --- /dev/null +++ b/Toolkit/Toolbox/Admin/EditPage.php @@ -0,0 +1,1044 @@ + + * @release CVS: $Id: EditPage.php,v 1.2 2009/12/15 20:18:16 jamie Exp $: + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ + +/** + * 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_Admin_EditPage + extends Toolkit_FormBuilder implements Toolkit_Form +{ + // {{{ properties + + /** + * Primary database table we need to interact with + * @var string + * @access protected + */ + public $tableName = 'bus_category'; + + /** + * 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(); + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * Sets the database handler this class will use via the PDO passed in + * from the parameters. Sets up the flexyOptions from the default options + * defined in the setup.phtml file, updates where the templates directory + * and compiled templates directory are located. + * + * @param PDO $pdo PHP Data Object used to set the database + * handler + * @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 + * @see Toolkit_FormBuilder, HTML_QuickForm + */ + public function __construct( + PDO $pdo, + $formName, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + + $this->dbh = $pdo; + + $this->flexyOptions = $GLOBALS['flexyOptions']; + $this->flexyOptions['templateDir'] = TEMPLATES_DIR; + $this->flexyOptions['compileDir'] = COMPILED_DIR; + } + + // }}} + + // {{{ configureDefaults() + + /** + * Initializes default form values + * + * @return void + * @access public + */ + public function configureDefaults() + { + if (is_numeric($_GET['id'])) { + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $d = $stmt->fetch(); + $i = ''; + + $d['current_image'] = sprintf($i, THUMB . $d['image']); + + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } else { + $d = array( + 'template' => 1, + ); + } + $this->setupDefaults($d); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @param Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function configureElements(Config_Container $c) + { + $e = array(); + + // get reference to [listing type] section of config file + $config =& $c->getItem('section', 'listing type'); + $pluralDirective =& $config->getItem('directive', 'plural'); + $pluralType = $pluralDirective->getContent(); + + // Grouped Elements are defined here. + $submitBtns = array(); + + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'update_rmv', + 'display' => 'Update' + ); + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'cancel_rmv', + 'display' => 'Cancel' + ); + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'delete_rmv', + 'display' => 'Delete' + ); + + $templates = array(); + + $options = range(1, 6); + foreach ($options as $i) { + $img = ""; + + $templates[] = array( + 'type' => 'radio', + 'req' => false, + 'name' => 'template', + 'display' => "Template $i
    $img", + 'att' => $i, + 'opts' => $i, + ); + } + + // All Elements are created here. + // This includes group element definitions. + $res = $this->getConstant('MEMBERS_DB'); + $isErr = PEAR::isError($res); + if ($isErr) { + Toolkit_Common::handleError($e); + } + if ($res && !$isErr) { + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'memberDbHdr', + 'display' => $pluralType, + ); + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'pageCategories' + ); + // 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' => 'memberCat', + 'display' => 'Member Categories', + 'opts' => array('' => '-- None --'), + 'att' => array( + 'multiple' => 'multiple', + 'size' => 7 + ) + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'no_search_form', + 'display' => 'Search Box', + 'val' => array(0, 1) + ); + } + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'pageAttributesHdr', + 'display' => 'Page Attributes' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'category', + 'display' => 'Navigation Name' + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'parent', + 'display' => 'Parent Page', + 'opts' => array('0' => '-- No Parent --'), + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'keyword', + 'display' => 'Keyword' + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'section_links', + 'display' => 'Search', + 'opts' => 'Create a list of links to the paragraph headlines', + 'val' => array(0, 1) + ); + $res = $this->getConstant('HOME_HEADLINES'); + $isErr = PEAR::isError($res); + if ($isErr) { + Toolkit_Common::handleError($e); + } + if ($res && !$isErr) { + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'homePageHeadlinesHdr', + 'display' => 'Headlines' + ); + $e[] = array( + 'type' => 'advcheckbox', + 'req' => false, + 'name' => 'featured', + 'display' => 'Home Page Headlines', + 'val' => array(0, 1) + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'feature_intro', + 'display' => 'Headline Intro' + ); + } + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'pageBodyHdr', + 'display' => 'Page Body' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'intro', + 'display' => 'Page Title' + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'display' => 'Description', + 'opts' => array( + 'cols' => 70, + 'rows' => 25 + ), + ); + if ($this->hasUploadedImage()) { + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'current_image', + 'display' => 'Current Image' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'imagename', + 'display' => 'Image Caption' + ); + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'remove_image', + 'display' => 'Delete Image' + ); + } + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'image', + 'display' => 'New Image' + ); + $e[] = array( + 'type' => 'group', + 'req' => false, + 'name' => 'page_layout', + 'group' => $templates, + 'label' => 'Template', + 'seperator' => '', + 'appendName' => false + ); + + // If we are editing a page, show three submit buttons + // otherwise, just show one insert button. + if (is_numeric($_GET['id'])) { + $e[] = array( + 'type' => 'group', + 'req' => false, + 'name' => 'submit_buttons', + 'group' => $submitBtns, + 'label' => '', + 'seperator' => '', + 'appendName' => false, + ); + } else { + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'insert_rmv', + 'display' => 'Insert' + ); + } + + $this->setupElements($e); + // 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) + $res = $this->getConstant('MEMBERS_DB'); + $isErr = PEAR::isError($res); + if ($isErr) { + Toolkit_Common::handleError($e); + } + if ($res && !$isErr) { + $this->loadMemberCategories(); + } + // Do the same for the pages + $this->loadParentPages(); + } + + // }}} + // {{{ 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 Config_Container $c Configuration object + * + * @return void + * @access public + */ + public function configureForm(Config_Container $c) + { + $this->configureElements($c); + $this->configureRules(); + $this->configureFilters(); + $this->configureDefaults(); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + // Form Rules + + $this->setupRules($r); + } + + // }}} + + // {{{ getCurrentParent() + + /** + * Gets the parent id of a page + * + * @param integer $id page id + * + * @return integer parent id + * @access protected + */ + protected function getCurrentParent($id) + { + try { + $sql = " + SELECT parent + FROM {$this->tableName} + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $id, PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('parent', $parent); + $stmt->fetch(); + + return $parent; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getNewParentPosition() + + /** + * Gets the position to use for a page + * + * If we are inserting a new page we need to get the position to insert + * the new page at. Or if we are updating an existing page and reassigning + * it to a new parent, we need to get the new position to insert + * the page at. + * + * @param integer $parent page id of the new parent page + * + * @return integer new position to use + * @access protected + */ + protected function getNewParentPosition($parent) + { + try { + $sql = " + SELECT count(*) + 1 AS newparent + FROM {$this->tableName} + WHERE parent = :parent + AND id != :home_id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':parent', $parent, PDO::PARAM_INT); + $stmt->bindValue(':home_id', HOME_ID, PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('newparent', $newParent); + $stmt->fetch(); + + if ($parent == 0) { + ++$newParent; + } + + return $newParent; + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ getTableName() + + /** + * Gets the primary table name + * + * @return string table name + * @access public + */ + public function getTableName() + { + return $this->tableName; + } + + // }}} + // {{{ getConstant() + + /** + * fetch a defined constant value + * + * @param string $constant constant name + * + * @return mixed constant value + * @acess protected + */ + protected function getConstant($constant) + { + if (!defined($constant)) { + return PEAR::raiseError('calling undefined constant'); + } else { + return constant($constant); + } + } + + // }}} + + // {{{ hasUploadedImage() + + /** + * Check to see if page we are editing has an uploaded image + * + * @return boolean If page has a previously uploaded image + * @access protected + */ + protected function hasUploadedImage() + { + if (!is_numeric($_GET['id'])) { + return false; + } + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('image', $image); + $row = $stmt->fetch(); + return !is_null($image); + //return !(is_null($image) || empty($image)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ loadMemberCategories() + + /** + * Loads member categories into the select list + * + * Gets an array structure of the member categories in a linear tree order + * Then walk through the array and load each category into the select list + * + * @return void + * @access public + */ + public function loadMemberCategories() + { + 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( + $this->dbh, + 'category', + 'category_id', + 'parent_id' + ); + + // Get all the data about each category + $sql = " + SELECT * + FROM category + WHERE category_id = ?"; + + $stmt = $this->dbh->prepare($sql); + // Get the member categories select list element + $e =& $this->getElement('memberCat'); + foreach ($c as $i => $j) { + $stmt->execute(array($i)); + $row = $stmt->fetch(); + // the class level is always 1 less than what is reported + // from our $c array + $x = $j - 1; + // Add the option data to the select list. + $e->addOption($row['name'], $i, array('class' => "level-$x")); + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ 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. + * + * @return void + * @throws PDOException throws exception on sql error + * @access public + */ + public function loadParentPages() + { + 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( + $this->dbh, + 'bus_category', + '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 bus_category + WHERE id = ?"; + + $stmt = $this->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['category'], $i, array('class' => "level-$x")); + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertPage() + + /** + * Create a new page in the site by inserting values into the DB + * + * @param array $values Submitted form values + * + * @return boolean Result of insertion + * @access protected + */ + protected function insertPage($values) + { + // Get the member categories if they exists so we don't try and + // insert them into the wrong table. + $memberCats = $values['memberCat']; + unset($values['memberCat']); + + // Get the value of the new position this page will be set to. + $values['pos'] = $this->getNewParentPosition($values['parent']); + + // a non empty file size indicates to use an image has been uploaded. + if (!empty($values['image']['size'])) { + $values['image'] = $this->uploadImage('image'); + if ($values['image'] === false) { + return PEAR::raiseError('Invalid image response'); + } + } else { + unset($values['image']); + } + + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + + try { + $this->dbh->beginTransaction(); + Toolkit_Common::processQuery( + $this->dbh, + $this->tableName, + $sql, + $values + ); + + // If we are trying to associate member categories + // with the toolbox page then insert them here. + if (is_array($memberCats) && !empty($memberCats)) { + // Need to get the last id inserted into the table. + $sql = " + SELECT id + FROM {$this->tableName} + ORDER BY id DESC + LIMIT 1"; + + $row = $this->dbh->query($sql)->fetch(); + $sql = Toolkit_Common::createSQLInsert( + 'bus_cat_member', + array('catid', 'memb_type') + ); + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':catid', $row['id'], PDO::PARAM_INT); + // zip through all the member categories selected + // and insert them into the table. + foreach ($memberCats as $i) { + if (is_numeric($i)) { + $stmt->bindParam(':memb_type', $i, PDO::PARAM_INT); + $stmt->execute(); + } + } + } + + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollback(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ processData() + + /** + * Clean unneeded form elements out of the submitted values array + * + * @param array $values QuickForm submitted elements + * + * @return boolean Result of insert/update functions + * @access public + */ + public function processData($values) + { + foreach ($values as $k => $v) { + switch ($k) { + case 'MAX_FILE_SIZE' : + unset($values[$k]); + break; + + default : + if (substr($k, -4) == '_rmv') { + unset($values[$k]); + } + break; + } + } + + $function = is_numeric($_GET['id']) ? 'updatePage' : 'insertPage'; + return $this->$function($values); + } + + // }}} + + // {{{ removeImage() + // @codeCoverageIgnoreStart + + /** + * Deletes an image from the file server + * + * @param string $fileName Name of the image to delete + * + * @return void + * @access protected + */ + protected function removeImage($fileName) + { + $is = new Toolkit_Image_Server(); + $is->imageDelete($fileName); + } + + // @codeCoverageIgnoreEnd + // }}} + + // {{{ 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 = ' * '; + $error = '
    {error}
    '; + + $renderer->setElementTemplate("\n\t\n\t\t$required{label}$error{element}\n\t", 'submit_buttons'); + $renderer->setElementTemplate("\n\t\n\t\t$required{label}$error{element}\n\t", 'insert_rmv'); + + $renderer->setGroupTemplate("\n\t\n\t\t\n\t\t\t{content}\n\t\t\n\t
    ", 'page_layout'); + $renderer->setGroupElementTemplate("\n\t\n\t\t\n\t", '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() + { + $validated = $this->validate(); + $this->setupRenderers(); + if ($validated) { + $this->cleanForm(); + + $r = $this->process( + array(&$this, 'processData'), + $this->mergeFiles + ); + if (PEAR::isError($r)) { + return Toolkit_Common::handleError($r); + } else { + $this->freeze(); + $output = $this->successMsg; + } + } elseif ($this->isSubmitted()) { + $output = $this->errorMsg; + $output .= parent::toHTML(); + } else { + $output = parent::toHTML(); + } + return $output; + } + + // }}} + + // {{{ updatePage() + + /** + * Update an existing page in the site by updating values in the DB + * + * @param array $values Submitted form values + * + * @return boolean Result of insertion + * @access protected + */ + protected function updatePage($values) + { + // Make sure we are dealing w/ a valid page + if (!is_numeric($_GET['id'])) { + return PEAR::raiseError('Invalid page id'); + } + + // Handle user deleting the page image. + if (array_key_exists('remove_image', $values)) { + $this->removeImage($values['imagename']); + + // unset value so its not included in the update sql query + unset($values['remove_image']); + // set image and imagename to null to overwrite value in db. + // if we are not uploading a new image. + if (empty($values['image']['size'])) { + $values['image'] = $values['imagename'] = null; + } + } + + // a non empty file size indicates to use an image has been uploaded. + if (!empty($values['image']['size'])) { + $values['image'] = $is->imageUpload('image'); + if ($values['image'] === false) { + return PEAR::raiseError('Invalid image response'); + } + } elseif (!is_null($values['image'])) { + unset($values['image']); + } + + // Get the parent id this page is currently set to in the DB. + $curPar = $this->getCurrentParent($_GET['id']); + // parents will be different if we are reassining to a new parent + if ($curPar != $values['parent']) { + // Get an updated position for the new parent page. + $values['pos'] = $this->getNewParentPosition($values['parent']); + } + + try { + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('id = :id') + ); + + $values['id'] = $_GET['id']; + return Toolkit_Common::processQuery( + $this->dbh, + $this->tableName, + $sql, + $values + ); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ uploadImage() + // @codeCoverageIgnoreStart + + /** + * Uploads an image to the image server + * + * @param string $key name of the file upload key to find the image in the + * $_FILES array + * + * @return mixed file name on success, false on error + * @access protected + */ + protected function uploadImage($key) + { + $is = new Toolkit_Image_Server(); + return $is->imageUpload($key); + } + + // @codeCoverageIgnoreEnd + // }}} +} +?> diff --git a/Toolkit/Toolbox/Admin/EditParagraph.php b/Toolkit/Toolbox/Admin/EditParagraph.php new file mode 100644 index 0000000..bc13898 --- /dev/null +++ b/Toolkit/Toolbox/Admin/EditParagraph.php @@ -0,0 +1,692 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @version CVS: $Id: EditParagraph.php,v 1.2 2009/12/15 20:18:16 jamie Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Short description for class + * + * Long description (if any) ... + * + * @category CategoryName + * @package Toolkit_Toolbox + * @author Jamie Kahgee + * @copyright 2009 Jamie Kahgee + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +class Toolkit_Toolbox_Admin_EditParagraph extends Toolkit_FormBuilder +{ + // {{{ properties + + + /** + * Description for protected + * @var string + * @access protected + */ + protected $tableName = 'bus'; + + // }}} + // {{{ __construct() + + /** + * Class constructor + * + * @param string $formName Form's name. + * @param PDO $pdo PHP Data Object used for DB calls + * @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, + PDO $pdo, + $method = 'post', + $action = '', + $target = '', + $attributes = null, + $trackSubmit = false + ) { + parent::__construct( + $formName, + $method, + $action, + $target, + $attributes, + $trackSubmit + ); + $this->dbh = $pdo; + $this->flexyOptions = $GLOBALS['flexyOptions']; + $this->flexyOptions['templateDir'] = TEMPLATES_DIR; + $this->flexyOptions['compileDir'] = COMPILED_DIR; + } + + // }}} + + // {{{ createTables() + + /** + * Read file from parameter and use the PDO parameter to create process file + * + * @param object $pdo Database handler + * @param string $file full path of file to parse + * + * @return void + * @access public + * @static + */ + static public function createTables(PDO $pdo, $file) + { + $sql = file_get_contents($file); + $tok = strtok($sql, ';'); + while ($tok !== false) { + $pdo->query($tok); + $tok = strtok(';'); + } + } + + // }}} + // {{{ configureDefaults() + + /** + * Initializes default form values + * + * @return void + * @access public + */ + public function configureDefaults() + { + if (is_numeric($_GET['id'])) { + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $d = $stmt->fetch(); + $i = ''; + + $d['current_image'] = sprintf($i, THUMB . $d['image']); + + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } else { + $d = array( + 'template' => 1, + ); + } + $this->setupDefaults($d); + } + + // }}} + // {{{ configureElements() + + /** + * Form element definitions + * + * @return void + * @access public + */ + public function configureElements() + { + $e = array(); + // Grouped Elements are defined here. + $submitBtns = array(); + + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'update_rmv', + 'display' => 'Update' + ); + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'cancel_rmv', + 'display' => 'Cancel' + ); + $submitBtns[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'delete_rmv', + 'display' => 'Delete' + ); + + // All Elements are created here. + // This includes group element definitions. + $e[] = array( + 'type' => 'header', + 'req' => false, + 'name' => 'paragraphAttributesHdr', + 'display' => 'Paragraph Attributes' + ); + $e[] = array( + 'type' => 'select', + 'req' => false, + 'name' => 'page', + 'display' => 'Page', + 'opts' => array(), + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'intro', + 'display' => 'Paragraph Title' + ); + $e[] = array( + 'type' => 'textarea', + 'req' => false, + 'name' => 'description', + 'display' => 'Description', + 'opts' => array( + 'cols' => 70, + 'rows' => 25 + ), + ); + if ($this->hasUploadedImage()) { + $e[] = array( + 'type' => 'static', + 'req' => false, + 'name' => 'current_image', + 'display' => 'Current Image' + ); + $e[] = array( + 'type' => 'text', + 'req' => false, + 'name' => 'imagename', + 'display' => 'Image Caption' + ); + $e[] = array( + 'type' => 'checkbox', + 'req' => false, + 'name' => 'remove_image', + 'display' => 'Delete Image' + ); + } + $e[] = array( + 'type' => 'file', + 'req' => false, + 'name' => 'image', + 'display' => 'New Image' + ); + + // If we are editing a page, show three submit buttons + // otherwise, just show one insert button. + if (is_numeric($_GET['id'])) { + $e[] = array( + 'type' => 'group', + 'req' => false, + 'name' => 'submit_buttons', + 'group' => $submitBtns, + 'label' => '', + 'seperator' => '', + 'appendName' => false, + ); + } else { + $e[] = array( + 'type' => 'submit', + 'req' => false, + 'name' => 'insert_rmv', + 'display' => 'Insert' + ); + } + + $this->setupElements($e); + // Do the same for the pages + $this->loadParagraphPages(); + } + + // }}} + // {{{ 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->configureElements(); + $this->configureRules(); + $this->configureFilters(); + $this->configureDefaults(); + } + + // }}} + // {{{ configureRules() + + /** + * Form rule definitions + * + * Adds validation rules for the given fields + * + * @return void + * @access public + */ + public function configureRules() + { + $r = array(); + // Form Rules + + $this->setupRules($r); + } + + // }}} + // {{{ getTableName() + + + /** + * Short description for function + * + * Long description (if any) ... + * + * @return string Return description (if any) ... + * @access public + */ + public function getTableName() + { + return $this->tableName; + } + + // }}} + + // {{{ hasUploadedImage() + + /** + * Check to see if page we are editing has an uploaded image + * + * @return boolean If page has a previously uploaded image + * @access protected + */ + protected function hasUploadedImage() + { + if (!is_numeric($_GET['id'])) { + return false; + } + try { + $sql = " + SELECT * + FROM {$this->tableName} + WHERE id = :id"; + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT); + $stmt->execute(); + $stmt->bindColumn('image', $image); + $row = $stmt->fetch(); + return !is_null($image); + //return !(is_null($image) || empty($image)); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ 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. + * + * @return void + * @throws PDOException throws exception on sql error + * @access public + */ + public function loadParagraphPages() + { + 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( + $this->dbh, + 'bus_category', + 'id', + 'parent', + 'pos', + 1, + $this->maxDepth + ); + + // Get all the data about each category + $sql = " + SELECT * + FROM bus_category + WHERE id = ?"; + + $stmt = $this->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(); + // 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['category'], $i, array('class' => "level-$x")); + } + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ insertPage() + + /** + * Create a new page in the site by inserting values into the DB + * + * @param array $values Submitted form values + * + * @return boolean Result of insertion + * @access protected + */ + protected function insertPage($values) + { + // Get the member categories if they exists so we don't try and + // insert them into the wrong table. + $memberCats = $values['memberCat']; + unset($values['memberCat']); + + // Get the value of the new position this page will be set to. + $values['pos'] = $this->getNewParentPosition($values['parent']); + + // a non empty file size indicates to use an image has been uploaded. + if (!empty($values['image']['size'])) { + $values['image'] = $this->uploadImage('image'); + if ($values['image'] === false) { + return PEAR::raiseError('Invalid image response'); + } + } else { + unset($values['image']); + } + + $sql = Toolkit_Common::createSQLInsert( + $this->tableName, + array_keys($values) + ); + + try { + $this->dbh->beginTransaction(); + Toolkit_Common::processQuery( + $this->dbh, + $this->tableName, + $sql, + $values + ); + + // If we are trying to associate member categories + // with the toolbox page then insert them here. + if (is_array($memberCats) && !empty($memberCats)) { + // Need to get the last id inserted into the table. + $sql = " + SELECT id + FROM {$this->tableName} + ORDER BY id DESC + LIMIT 1"; + + $row = $this->dbh->query($sql)->fetch(); + $sql = Toolkit_Common::createSQLInsert( + 'bus_cat_member', + array('catid', 'memb_type') + ); + + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(':catid', $row['id'], PDO::PARAM_INT); + // zip through all the member categories selected + // and insert them into the table. + foreach ($memberCats as $i) { + if (is_numeric($i)) { + $stmt->bindParam(':memb_type', $i, PDO::PARAM_INT); + $stmt->execute(); + } + } + } + + return $this->dbh->commit(); + } catch (PDOException $e) { + $this->dbh->rollback(); + return Toolkit_Common::handleError($e); + } + } + + // }}} + + // {{{ processData() + + /** + * Clean unneeded form elements out of the submitted values array + * + * @param array $values QuickForm submitted elements + * + * @return boolean Result of insert/update functions + * @access public + */ + public function processData($values) + { + foreach ($values as $k => $v) { + switch ($k) { + case 'MAX_FILE_SIZE' : + unset($values[$k]); + break; + + default : + if (substr($k, -4) == '_rmv') { + unset($values[$k]); + } + break; + } + } + + $function = is_numeric($_GET['id']) ? 'updatePage' : 'insertPage'; + return $this->$function($values); + } + + // }}} + // {{{ removeImage() + // @codeCoverageIgnoreStart + + /** + * Deletes an image from the file server + * + * @param string $fileName Name of the image to delete + * + * @return void + * @access protected + */ + protected function removeImage($fileName) + { + $is = new Toolkit_Image_Server(); + $is->imageDelete($fileName); + } + + // @codeCoverageIgnoreEnd + // }}} + + // {{{ 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 = ' * '; + $error = '
    {error}
    '; + + $renderer->setElementTemplate("\n\t\n\t\t$required{label}$error{element}\n\t", 'submit_buttons'); + $renderer->setElementTemplate("\n\t\n\t\t$required{label}$error{element}\n\t", 'insert_rmv'); + + $renderer->setGroupTemplate("\n\t\n\t\t\n\t\t\t{content}\n\t\t\n\t
    ", 'page_layout'); + $renderer->setGroupElementTemplate("\n\t\n\t\t\n\t", 'page_layout'); + } + + // }}} + + // {{{ updatePage() + + /** + * Update an existing page in the site by updating values in the DB + * + * @param array $values Submitted form values + * + * @return boolean Result of insertion + * @access protected + */ + protected function updatePage($values) + { + // Make sure we are dealing w/ a valid page + if (!is_numeric($_GET['id'])) { + return PEAR::raiseError('Invalid page id'); + } + + // Handle user deleting the page image. + if (array_key_exists('remove_image', $values)) { + $this->removeImage($values['imagename']); + + // unset value so its not included in the update sql query + unset($values['remove_image']); + // set image and imagename to null to overwrite value in db. + // if we are not uploading a new image. + if (empty($values['image']['size'])) { + $values['image'] = $values['imagename'] = null; + } + } + + // a non empty file size indicates to use an image has been uploaded. + if (!empty($values['image']['size'])) { + $values['image'] = $is->imageUpload('image'); + if ($values['image'] === false) { + return PEAR::raiseError('Invalid image response'); + } + } elseif (!is_null($values['image'])) { + unset($values['image']); + } + + // Get the parent id this page is currently set to in the DB. + $curPar = $this->getCurrentParent($_GET['id']); + // parents will be different if we are reassining to a new parent + if ($curPar != $values['parent']) { + // Get an updated position for the new parent page. + $values['pos'] = $this->getNewParentPosition($values['parent']); + } + + try { + $sql = Toolkit_Common::createSQLUpdate( + $this->tableName, + array_keys($values), + array('id = :id') + ); + + $values['id'] = $_GET['id']; + return Toolkit_Common::processQuery( + $this->dbh, + $this->tableName, + $sql, + $values + ); + } catch (PDOException $e) { + return Toolkit_Common::handleError($e); + } + } + + // }}} + // {{{ uploadImage() + // @codeCoverageIgnoreStart + + /** + * Uploads an image to the image server + * + * @param string $key name of the file upload key to find the image in the + * $_FILES array + * + * @return mixed file name on success, false on error + * @access protected + */ + protected function uploadImage($key) + { + $is = new Toolkit_Image_Server(); + return $is->imageUpload($key); + } + + // @codeCoverageIgnoreEnd + // }}} +} +?> diff --git a/Toolkit/Toolbox/Admin/toolbox.sql b/Toolkit/Toolbox/Admin/toolbox.sql new file mode 100644 index 0000000..5fc4cdb --- /dev/null +++ b/Toolkit/Toolbox/Admin/toolbox.sql @@ -0,0 +1,33 @@ +CREATE TABLE bus_category ( +id SERIAL PRIMARY KEY, +parent INTEGER, +category TEXT, +intro TEXT, +description TEXT, +image TEXT, +imagename TEXT, +active BOOLEAN DEFAULT FALSE, +pos INTEGER, +keyword TEXT, +template INTEGER, +featured BOOLEAN DEFAULT FALSE, +no_search_form BOOLEAN DEFAULT FALSE, +feature_intro TEXT, +section_links BOOLEAN DEFAULT FALSE +); + +CREATE TABLE bus ( +id SERIAL PRIMARY KEY, +name TEXT, +description TEXT, +image TEXT, +imagename TEXT, +back_to_top BOOLEAN DEFAULT FALSE +); + +CREATE TABLE bus_category_bus ( +id SERIAL PRIMARY KEY, +busid INTEGER, +catid INTEGER, +pos INTEGER +); diff --git a/Toolkit/Toolbox/Rss.php b/Toolkit/Toolbox/Rss.php new file mode 100644 index 0000000..3ff8979 --- /dev/null +++ b/Toolkit/Toolbox/Rss.php @@ -0,0 +1,123 @@ + + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version CVS: $Id: Rss.php,v 1.1 2009/09/23 15:53:30 matrix Exp $ + * @link <> + */ + +/** + * Create Rss Feed from Toolbox data + * + * @category Toolkit + * @package Toolbox + * @author Steve Sutton + * @copyright 2009 Gaslight Media + * @license Gaslight Media + * @version Release: @package_version@ + * @link <> + */ +class Toolkit_Toolbox_Rss +{ + // {{{ Class Properties + /** + * PDO Reference + * @var object + * @access public + */ + public $dbh; + // }}} + // {{{ __construct() + /** + * Constructer + * + * @param unknown &$pdo Reference to PDO object + * + * @return void + * @access public + */ + function __construct(PDO &$pdo) + { + $this->dbh =& $pdo; + } + // }}} + // {{{ getRssFeed() + /** + * Creates Rss feed for use in any feed reader. + * + * Pulls data from the paragraphs of any catid passed in + * + * @param unknown $pageId the id of the category to pull paragraphs from + * + * @return void + * @access public + */ + function getRssFeed($pageId) + { + $options = array( + "typehints" => false, + "addDecl" => true, + "encoding" => "UTF-8", + "rootName" => "rss", + "rootAttributes" => array('version' => '2.0'), + "defaultTagName" => "item", + "mode" => "simplexml", + ); + $sql = " + SELECT b.id, b.name, b.description, + to_char(b.publish_date, 'Dy, DD Mon YYYY HH:MM:SS GMT') + as publish_date + FROM bus b LEFT OUTER JOIN bus_category_bus bcb ON (b.id = bcb.busid) + WHERE bcb.catid = :catid + ORDER BY bcb.pos"; + try { + $stmt = $this->dbh->prepare($sql); + $stmt->bindParam(":catid", $pageId, PDO::PARAM_INT); + $stmt->execute(); + $newsData = $stmt->fetchAll(PDO::FETCH_ASSOC); + if (is_array($newsData)) { + foreach ($newsData as $row) { + if ($row['title']) { + $title = $row['title']; + } elseif ($row['header']) { + $title = $row['header']; + } else { + $title = $row['pr_date']; + } + $title = $row['name']; + $stories[] = array( + 'title' => strip_tags($title), + 'link' => BASE_URL + . 'index.php?catid=8&newsid='.$row["id"], + 'pubDate' => $row['publish_date'], + 'description' => $row['description'] + ); + } + } + $data['channel'] = array( + 'title' => 'Gaslight Media Testimonials', + 'link' => BASE_URL, + $stories + ); + $serializer = new XML_Serializer($options); + if ($serializer->serialize($data)) { + header('Content-type: text/xml'); + $out = $serializer->getSerializedData(); + echo $out; + } + } catch(PDOException $e) { + echo '
    '.print_r($e, true).'
    '; + die($e->getMessage); + } + } + // }}} +} +?> diff --git a/Toolkit/Tree.php b/Toolkit/Tree.php new file mode 100644 index 0000000..2fda674 --- /dev/null +++ b/Toolkit/Tree.php @@ -0,0 +1,145 @@ + + * @license http://www.gaslightmedia.com Gaslightmedia + * @release CVS: $Id: Tree.php,v 1.1.1.1 2009/09/17 20:08:55 matrix Exp $ + * @link http://demo.gaslightmedia.com + */ + +/** + * Create tree structures of database entries + * + * Base class used to setup tree objects that will render + * database structures into iterable PHP objects. + * + * @category Toolkit + * @package Toolkit_Tree + * @author Jamie Kahgee + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com Gaslightmedia + * @link http://demo.gaslightmedia.com + */ +abstract class Toolkit_Tree +{ + // {{{ properties + + /** + * Database ID of tuple + * + * @var int + * @access public + */ + public $catid = 0; + + /** + * Name of object + * + * @var string + * @access public + */ + public $category; + + /** + * Children of object + * + * @var array + * @access public + */ + public $children = array(); + + /** + * Parent of this category + * + * @var array + * @access public + */ + public $parentId; + + /** + * Database connection handle + * + * @var PDO Object + * @access protected + */ + protected $dbh; + + // }}} + // {{{ __construct() + + /** + * Setup the objects properties and call to setup children + * + * @param integer $catid ID of the Database object + * @param string $name Name of the Database object + * @param PDO $dbh Database handler object + * @param integer $parentId Id of parent node + * + * @author Jamie Kahgee + * @access public + */ + public function __construct($catid, $name, PDO $dbh, $parentId = 0) + { + $this->parentId = $parentId; + $this->catid = $catid; + $this->category = $name; + $this->dbh = $dbh; + $this->addChildren(); + } + + // }}} + // {{{ __get() + + /** + * utilized for reading data from inaccessible members + * + * @param string $name property name + * + * @return mixed void + * @access public + */ + public function __get($name) + { + return $this->$name; + } + + // }}} + // {{{ __set() + + + /** + * Run when writing data to inaccessible members + * + * @param string $name property + * @param string $value new value + * + * @return void + * @access public + */ + public function __set($name, $value) + { + $this->$name = $value; + } + + // }}} + // {{{ addChildren() + + /** + * Attaches children to tree object + * + * @author Jamie Kahgee + * @return void + * @access protected + */ + abstract protected function addChildren(); + + // }}} +} +?> diff --git a/Toolkit/Weather.php b/Toolkit/Weather.php new file mode 100755 index 0000000..2c0a1db --- /dev/null +++ b/Toolkit/Weather.php @@ -0,0 +1,203 @@ + + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com/license.txt The Gaslight License + * @version CVS: $Id: Weather.php,v 1.1.1.1 2009/09/17 20:08:56 matrix Exp $ + * @link <> + */ + +/** + * Weather class for Gaslight Media + * + * You can get the stationId for weather at + * http://www.weather.gov/xml/current_obs/seek.php?state=mi + * Uses NOAA for getting the rss feed for weather + * + * @category Toolkit + * @package Toolkit_Weather + * @author Steve Sutton + * @copyright 2008 Gaslight Media + * @license http://www.gaslightmedia.com/license.txt The Gaslight License + * @link <> + */ +class Toolkit_Weather +{ + //{{{ __Class Properties + + + /** + * The xml file used for caching the feed + * @var $_weatherFile string + * @access private + */ + private $_weatherFile; + + /** + * Station identifier for the feed + * @link http://www.weather.gov/xml/current_obs/seek.php?state=mi + * + * @var $_stationId string + * @access private + */ + private $_stationId = 'KPLN'; + + + /** + * XMLReader object for parsing feed + * @var $_xml object + * @access private + */ + private $_xml; + + /** + * Description for private + * @var $_assoc array + * @access private + */ + private $_assoc; + + /** + * Storage array for the current conditions + * @var $currendCond array + * @access public + */ + public $currentCond; + + /** + * Boolean if the file exists or not + * @var $_cacheFileExist boolean + * @access private + */ + private $_cacheFileExist = false; + + //}}} + //{{{ __construct() + + /** + * Class Constructer + * + * @return void + * @access public + */ + function __construct() + { + $currentErrorMask = ini_get('error_reporting'); + error_reporting(0); + $this->_weatherFile = BASE.'weather-feed.xml'; + $this->interval = 25; // interval in minutes for page cache + $this->fetchWeather(); + $this->setCurrentCond(); + error_reporting($currentErrorMask); + } + + //}}} + //{{{ fetchWeather() + + + /** + * fetchWeather + * + * THis will use curl to grab the weather feed using + * the $_weatherFile as destination + * and the $_stationId for the xml file name + * + * @return void + * @access public + */ + function fetchWeather() + { + if (is_file($this->_weatherFile)) { + $time2hoursago = mktime( + date('H'), + date('i') - $this->interval, + date('s'), + date('m'), + date('d'), + date('Y') + ); + $file_time = filemtime($this->_weatherFile); + if ($file_time < $time2hoursago) { + $this->grabFeedUrl(); + } + if (is_file($this->_weatherFile)) { + $this->_cacheFileExist = true; + } + } else { + $this->grabFeedUrl(); + if (is_file($this->_weatherFile)) { + $this->_cacheFileExist = true; + } + } + } + + //}}} + // {{{ grabFeedUrl() + + + /** + * grabFeedUrl + * + * @return void + * @access public + */ + function grabFeedUrl() + { + // the NOAA xml feed url to be used + // from the _stationId + $feed_url = 'http://www.weather.gov/xml/current_obs/' + .$this->_stationId.'.xml'; + // Curl Options used for connection + $curlOptions = array( + CURLOPT_URL => $feed_url, + CURLOPT_HEADER => 0, + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_TIMEOUT => 15, + CURLOPT_CONNECTTIMEOUT => 5, + CURLOPT_FAILONERROR => 1, + ); + // start curl object + $ch = curl_init(); + // set options + curl_setopt_array($ch, $curlOptions); + // assign the response to a string variable + $response = curl_exec($ch); + // grab the connection info to check for http_code = 200 + $info = curl_getinfo($ch); + curl_close($ch); + if ($info['http_code'] == '200') { + file_put_contents($this->_weatherFile, $response); + } else { + @touch($this->_weatherFile); + } + } + + + // }}} + //{{{ setCurrentCond() + + /** + * Set currentCond + * + * Set the currentCond clas var up with variables from the xml file + * from the weather feed + * + * @return void + * @access public + */ + function setCurrentCond() + { + $xml = new XML_Unserializer(); + $xml->unserialize($this->_weatherFile, true); + $this->currentCond = $xml->getUnserializedData(); + } + + //}}} +} +?> diff --git a/Toolkit/qfcaptcha.php b/Toolkit/qfcaptcha.php new file mode 100755 index 0000000..0a44b41 --- /dev/null +++ b/Toolkit/qfcaptcha.php @@ -0,0 +1,39 @@ + + * @copyright 2006-2008 by Philippe Jausions / 11abacus + * @license http://www.opensource.org/licenses/bsd-license.php New BSD + * @version CVS: $Id: qfcaptcha.php,v 1.2 2009/12/15 20:18:15 jamie Exp $ + * @filesource + * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA + * @see qfcaptcha_form_image.php + * @see qfcaptcha_form_random.php + */ + +// Require the class before opening the session +// so the instance unserialize properly +require_once '../setup.phtml'; +require_once 'Text/CAPTCHA.php'; +require_once 'Text/CAPTCHA/Driver/Image.php'; + +HTTP_Session2::useCookies(false); +HTTP_Session2::start(); + +header('Content-Type: image/jpeg'); + +$sessionVar = (empty($_REQUEST['var'])) + ? '_HTML_QuickForm_CAPTCHA' + : $_REQUEST['var']; + +// Force a new CAPTCHA for each one displayed +$_SESSION[$sessionVar]->setPhrase(); + +echo $_SESSION[$sessionVar]->getCAPTCHAAsJPEG(); +?> diff --git a/admin/.htaccess b/admin/.htaccess new file mode 100644 index 0000000..38dcd05 --- /dev/null +++ b/admin/.htaccess @@ -0,0 +1 @@ +RewriteEngine Off diff --git a/admin/Contact/assets/EditorContent.js b/admin/Contact/assets/EditorContent.js new file mode 100644 index 0000000..97788ad --- /dev/null +++ b/admin/Contact/assets/EditorContent.js @@ -0,0 +1,744 @@ +/*********************************************************************** +** Title.........: Online Image Editor Interface +** Version.......: 1.0 +** Author........: Xiang Wei ZHUO +** Filename......: EditorContents.js +** Last changed..: 31 Mar 2004 +** Notes.........: Handles most of the interface routines for the ImageEditor. +* +* Added: 29 Mar 2004 - Constrainted resizing/scaling +**/ + + +function MM_findObj(n, d) { //v4.01 + var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { + d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} + if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i-1 && navigator.appVersion.indexOf("Mac")>-1)) { + ox=0;oy=0;if(g.style.left){x=parseInt(g.style.left);y=parseInt(g.style.top); + }else{var w1=parseInt(el.style.width);bx=(a<0)?-5-w1:-10; + a=(Math.abs(a)<1000)?0:a;b=(Math.abs(b)<1000)?0:b; + //alert(event.clientX); + if (event == null) x=document.body.scrollLeft + bx; + else x=document.body.scrollLeft + event.clientX + bx; + if (event == null) y=document.body.scrollTop; + else y=document.body.scrollTop + event.clientY;}} + }else if (document.layers) {x=g.x;y=g.y;var q0=document.layers,dd=""; + for(var s=0;s4){xx+="px";yy+="px";} + if(navigator.appVersion.indexOf("MSIE 5")>-1 && navigator.appVersion.indexOf("Mac")>-1){ + xx+=parseInt(document.body.leftMargin);yy+=parseInt(document.body.topMargin); + xx+="px";yy+="px";}e.left=xx;e.top=yy;} + pic_x = parseInt(xx); pic_y = parseInt(yy); + //alert(xx+":"+yy); + } +} + +var ie=document.all +var ns6=document.getElementById&&!document.all + +var dragapproved=false +var z,x,y,status, ant, canvas, content, pic_width, pic_height, image, resizeHandle, oa_w, oa_h, oa_x, oa_y, mx2, my2; + + +function init_resize() +{ + if(mode == "scale") + { + P7_Snap('theImage','ant',0,0); + + if (canvas == null) + canvas = MM_findObj("imgCanvas"); + + if (pic_width == null || pic_height == null) + { + image = MM_findObj("theImage"); + pic_width = image.width; + pic_height = image.height; + } + + if (ant == null) + ant = MM_findObj("ant"); + + ant.style.left = pic_x; ant.style.top = pic_y; + ant.style.width = pic_width; ant.style.height = pic_height; + ant.style.visibility = "visible"; + + drawBoundHandle(); + jg_doc.paint(); + } +} + +initEditor = function () +{ + init_crop(); + init_resize(); + var markerImg = MM_findObj('markerImg', window.top.document); + + if (markerImg.src.indexOf("img/t_white.gif")>0) + toggleMarker() ; +} + +function init_crop() +{ + //if(mode == "crop") { + P7_Snap('theImage','ant',0,0); + //} +} + +function setMode(newMode) +{ + mode = newMode; + reset(); +} + +function reset() +{ + if (ant == null) + ant = MM_findObj("ant"); + + ant.style.visibility = "hidden"; + ant.style.left = 0; + ant.style.top = 0; + ant.style.width = 0; + ant.style.height = 0; + + mx2 = null; + my2 = null; + + jg_doc.clear(); + if(mode != 'measure') + showStatus(); + + if(mode == "scale") { + init_resize(); + } + + P7_Snap('theImage','ant',0,0); +} + +function toggleMarker() +{ + //alert("Toggle"); + if (ant == null) + ant = MM_findObj("ant"); + + if(ant.className=="selection") + ant.className="selectionWhite"; + else + ant.className="selection"; + + if (jg_doc.getColor() == "#000000") + jg_doc.setColor("#FFFFFF"); + else + jg_doc.setColor("#000000"); + + drawBoundHandle + jg_doc.paint(); +} + + +function move(e) +{ + if (dragapproved) + { + //z.style.left=ns6? temp1+e.clientX-x: temp1+event.clientX-x + //z.style.top=ns6? temp2+e.clientY-y : temp2+event.clientY-y + var w = ns6? temp1+e.clientX - x : temp1+event.clientX - x; + var h = ns6? temp2+e.clientY - y : temp2+event.clientY - y; + + //alert(canvas.style.left); + /*if (status !=null) + { + status.innerHTML = "x:"+x+" y:"+y+" w:"+w+" h:"+h+" can_h:"+pic_height; + status.innerHTML += " can_w:"+pic_width+" px:"+pic_x+" py:"+pic_y; + status.innerHTML += " pix:"+image.style.left+" piy:"+image.style.top+" obj:"+obj.id; + }*/ + + /*jg_doc.clear(); + jg_doc.fillRectPattern(0,0,Math.abs(w),Math.abs(h),pattern); + jg_doc.paint(); +*/ + if (ant != null) + { + if (w >= 0) + { + ant.style.left = x; + ant.style.width = w; + } + else + { + ant.style.left = x+w; + ant.style.width = -1*w; + } + + if (h >= 0) + { + ant.style.top = y; + ant.style.height = h; + } + else + { + ant.style.top = y+h; + ant.style.height = -1*h + } + } + + showStatus(); + return false + } +} + +function moveContent(e) +{ + if (dragapproved) + { + + var dx =ns6? oa_x + e.clientX-x: oa_x + event.clientX-x + var dy =ns6? oa_y + e.clientY-y : oa_y + event.clientY-y + + + /*if (status !=null) + { + status.innerHTML = "x:"+x+" y:"+y+" dx:"+dx+" dy:"+dy; + }*/ + + ant.style.left = dx; + ant.style.top = dy; + + showStatus(); + + return false; + } +} + +//Code add for constraints by Frédéric Klee +function moveHandle(e) +{ + if (dragapproved) + { + var w = ns6? e.clientX - x : event.clientX - x; + var h = ns6? e.clientY - y : event.clientY - y; + + var constrained = MM_findObj('constProp', window.top.document); + var orginal_height = document.theImage.height ; + var orginal_width = document.theImage.width ; + rapp = orginal_width/orginal_height ; + rapp_inv = orginal_height / orginal_width ; + + switch(resizeHandle) + { + + case "s-resize": + if (oa_h + h >= 0) + { + ant.style.height = oa_h + h; + if(constrained.checked) + { + ant.style.width = rapp * (oa_h + h) ; + ant.style.left = oa_x - rapp * h/2; + } + + } + break; + case "e-resize": + if(oa_w + w >= 0) + { + ant.style.width = oa_w + w; + if(constrained.checked) + { + ant.style.height = rapp_inv * (oa_w + w) ; + ant.style.top = oa_y - rapp_inv * w/2; + } + + } + break; + case "n-resize": + if (oa_h - h >= 0) + { + ant.style.top = oa_y + h; + ant.style.height = oa_h - h; + if(constrained.checked) + { + ant.style.width = rapp * (oa_h - h) ; + ant.style.left = oa_x + rapp * h/2; + } + + } + break; + case "w-resize": + if(oa_w - w >= 0) + { + ant.style.left = oa_x + w; + ant.style.width = oa_w - w; + if(constrained.checked) + { + ant.style.height = rapp_inv * (oa_w - w) ; + ant.style.top = oa_y + rapp_inv * w/2; + } + + }break; + case "nw-resize": + if(oa_h - h >= 0 && oa_w - w >= 0) { + ant.style.left = oa_x + w; + ant.style.width = oa_w - w; + ant.style.top = oa_y + h; + if(constrained.checked) + ant.style.height = rapp_inv * (oa_w - w) ; + else + ant.style.height = oa_h - h; + } + break; + case "ne-resize": + if (oa_h - h >= 0 && oa_w + w >= 0){ + ant.style.top = oa_y + h; + ant.style.width = oa_w + w; + if(constrained.checked) + ant.style.height = rapp_inv * (oa_w + w) ; + else + ant.style.height = oa_h - h; + } + break; + case "se-resize": + if (oa_h + h >= 0 && oa_w + w >= 0) + { + ant.style.width = oa_w + w; + if(constrained.checked) + ant.style.height = rapp_inv * (oa_w + w) ; + else + ant.style.height = oa_h + h; + } + break; + case "sw-resize": + if (oa_h + h >= 0 && oa_w - w >= 0) + { + ant.style.left = oa_x + w; + ant.style.width = oa_w - w; + if(constrained.checked) + ant.style.height = rapp_inv * (oa_w - w) ; + else + ant.style.height = oa_h + h; + } + } + + showStatus(); + return false; + + } +} + +function drags(e) +{ + if (!ie&&!ns6) + return + + var firedobj=ns6? e.target : event.srcElement + var topelement=ns6? "HTML" : "BODY" + + while (firedobj.tagName!=topelement&& + !(firedobj.className=="crop" + || firedobj.className=="handleBox" + || firedobj.className=="selection" || firedobj.className=="selectionWhite")) + { + firedobj=ns6? firedobj.parentNode : firedobj.parentElement + } + + if(firedobj.className=="handleBox") { + + if(content != null) { + if(content.width != null && content.height != null) { + content.width = 0; + content.height = 0; + } + //alert(content.width+":"+content.height); + } + resizeHandle = firedobj.id; + + /*if(status!=null) { + status.innerHTML = " obj:"+firedobj.id; + }*/ + + x=ns6? e.clientX: event.clientX + y=ns6? e.clientY: event.clientY + + oa_w = parseInt(ant.style.width); + oa_h = parseInt(ant.style.height); + oa_x = parseInt(ant.style.left); + oa_y = parseInt(ant.style.top); + + dragapproved=true + document.onmousemove=moveHandle; + return false; + } + else + if((firedobj.className == "selection" || firedobj.className=="selectionWhite")&& mode == "crop") { + + x=ns6? e.clientX: event.clientX + y=ns6? e.clientY: event.clientY + + oa_x = parseInt(ant.style.left); + oa_y = parseInt(ant.style.top); + + dragapproved=true + document.onmousemove=moveContent; + return false; + } + else + if (firedobj.className=="crop" && mode == "crop") + { + if(content != null) { + if(content.width != null && content.height != null) { + content.width = 0; + content.height = 0; + } + //alert(content.width+":"+content.height); + } + + if (status == null) + status = MM_findObj("status"); + + if (ant == null) + ant = MM_findObj("ant"); + + if (canvas == null) + canvas = MM_findObj("imgCanvas"); + if(content == null) { + content = MM_findObj("cropContent"); + } + + if (pic_width == null || pic_height == null) + { + image = MM_findObj("theImage"); + pic_width = image.width; + pic_height = image.height; + } + + ant.style.visibility = "visible"; + + obj = firedobj; + dragapproved=true + z=firedobj + temp1=parseInt(z.style.left+0) + temp2=parseInt(z.style.top+0) + x=ns6? e.clientX: event.clientX + y=ns6? e.clientY: event.clientY + document.onmousemove=move + return false + } + else if(firedobj.className=="crop" && mode == "measure") { + + if (ant == null) + ant = MM_findObj("ant"); + + if (canvas == null) + canvas = MM_findObj("imgCanvas"); + + x=ns6? e.clientX: event.clientX + y=ns6? e.clientY: event.clientY + + //jg_doc.draw + dragapproved=true + document.onmousemove=measure + + return false + } +} + +function measure(e) +{ + if (dragapproved) + { + mx2 = ns6? e.clientX : event.clientX; + my2 = ns6? e.clientY : event.clientY; + + jg_doc.clear(); + jg_doc.setStroke(Stroke.DOTTED); + jg_doc.drawLine(x,y,mx2,my2); + jg_doc.paint(); + showStatus(); + return false; + } +} + +function setMarker(nx,ny,nw,nh) +{ + if (ant == null) + ant = MM_findObj("ant"); + + if (canvas == null) + canvas = MM_findObj("imgCanvas"); + if(content == null) { + content = MM_findObj("cropContent"); + } + + if (pic_width == null || pic_height == null) + { + image = MM_findObj("theImage"); + pic_width = image.width; + pic_height = image.height; + } + + ant.style.visibility = "visible"; + + nx = pic_x + nx; + ny = pic_y + ny; + + if (nw >= 0) + { + ant.style.left = nx; + ant.style.width = nw; + } + else + { + ant.style.left = nx+nw; + ant.style.width = -1*nw; + } + + if (nh >= 0) + { + ant.style.top = ny; + ant.style.height = nh; + } + else + { + ant.style.top = ny+nh; + ant.style.height = -1*nh + } + + +} + +function max(x,y) +{ + if(y > x) + return x; + else + return y; +} + +function drawBoundHandle() +{ + if(ant == null || ant.style == null) + return false; + + var ah = parseInt(ant.style.height); + var aw = parseInt(ant.style.width); + var ax = parseInt(ant.style.left); + var ay = parseInt(ant.style.top); + + jg_doc.drawHandle(ax-15,ay-15,30,30,"nw-resize"); //upper left + jg_doc.drawHandle(ax-15,ay+ah-15,30,30,"sw-resize"); //lower left + jg_doc.drawHandle(ax+aw-15,ay-15,30,30,"ne-resize"); //upper right + jg_doc.drawHandle(ax+aw-15,ay+ah-15,30,30,"se-resize"); //lower right + + jg_doc.drawHandle(ax+max(15,aw/10),ay-8,aw-2*max(15,aw/10),8,"n-resize"); //top middle + jg_doc.drawHandle(ax+max(15,aw/10),ay+ah,aw-2*max(15,aw/10),8,"s-resize"); //bottom middle + jg_doc.drawHandle(ax-8, ay+max(15,ah/10),8,ah-2*max(15,ah/10),"w-resize"); //left middle + jg_doc.drawHandle(ax+aw, ay+max(15,ah/10),8,ah-2*max(15,ah/10),"e-resize"); //right middle + + + + jg_doc.drawHandleBox(ax-4,ay-4,8,8,"nw-resize"); //upper left + jg_doc.drawHandleBox(ax-4,ay+ah-4,8,8,"sw-resize"); //lower left + jg_doc.drawHandleBox(ax+aw-4,ay-4,8,8,"ne-resize"); //upper right + jg_doc.drawHandleBox(ax+aw-4,ay+ah-4,8,8,"se-resize"); //lower right + + jg_doc.drawHandleBox(ax+aw/2-4,ay-4,8,8,"n-resize"); //top middle + jg_doc.drawHandleBox(ax+aw/2-4,ay+ah-4,8,8,"s-resize"); //bottom middle + jg_doc.drawHandleBox(ax-4, ay+ah/2-4,8,8,"w-resize"); //left middle + jg_doc.drawHandleBox(ax+aw-4, ay+ah/2-4,8,8,"e-resize"); //right middle + + //jg_doc.paint(); +} + +function showStatus() +{ + if(ant == null || ant.style == null) { + return false; + } + + if(mode == "measure") { + //alert(pic_x); + mx1 = x - pic_x; + my1 = y - pic_y; + + mw = mx2 - x; + mh = my2 - y; + + md = parseInt(Math.sqrt(mw*mw + mh*mh)*100)/100; + + ma = (Math.atan(-1*mh/mw)/Math.PI)*180; + if(mw < 0 && mh < 0) + ma = ma+180; + + if (mw <0 && mh >0) + ma = ma - 180; + + ma = parseInt(ma*100)/100; + + if (m_sx != null && !isNaN(mx1)) + m_sx.value = mx1+"px"; + if (m_sy != null && !isNaN(my1)) + m_sy.value = my1+"px"; + if(m_w != null && !isNaN(mw)) + m_w.value = mw + "px"; + if(m_h != null && !isNaN(mh)) + m_h.value = mh + "px"; + + if(m_d != null && !isNaN(md)) + m_d.value = md + "px"; + if(m_a != null && !isNaN(ma)) + m_a.value = ma + ""; + + if(r_ra != null &&!isNaN(ma)) + r_ra.value = ma; + + //alert("mx1:"+mx1+" my1"+my1); + return false; + } + + var ah = parseInt(ant.style.height); + var aw = parseInt(ant.style.width); + var ax = parseInt(ant.style.left); + var ay = parseInt(ant.style.top); + + var cx = ax-pic_x<0?0:ax-pic_x; + var cy = ay-pic_y<0?0:ay-pic_y; + cx = cx>pic_width?pic_width:cx; + cy = cy>pic_height?pic_height:cy; + + var cw = ax-pic_x>0?aw:aw-(pic_x-ax); + var ch = ay-pic_y>0?ah:ah-(pic_y-ay); + + ch = ay+ah0 && s_sh.value.indexOf('%')>0) + { + sw = cw/pic_width; + sh = ch/pic_height; + } + if (s_sw != null) + s_sw.value = sw; + if (s_sh != null) + s_sh.value = sh; + } + +} + +function dragStopped() +{ + dragapproved=false; + + if(ant == null || ant.style == null) { + return false; + } + + if(mode == "measure") { + jg_doc.drawLine(x-4,y,x+4,y); + jg_doc.drawLine(x,y-4,x,y+4); + jg_doc.drawLine(mx2-4,my2,mx2+4,my2); + jg_doc.drawLine(mx2,my2-4,mx2,my2+4); + + jg_doc.paint(); + showStatus(); + return false; + } + var ah = parseInt(ant.style.height); + var aw = parseInt(ant.style.width); + var ax = parseInt(ant.style.left); + var ay = parseInt(ant.style.top); + jg_doc.clear(); + + if(content != null) { + if(content.width != null && content.height != null) { + content.width = aw-1; + content.height = ah-1; + } + //alert(content.width+":"+content.height); + } + if(mode == "crop") { + //alert(pic_y); + jg_doc.fillRectPattern(pic_x,pic_y,pic_width,ay-pic_y,pattern); + + var h1 = ah; + var y1 = ay; + if (ah+ay >= pic_height+pic_y) + h1 = pic_height+pic_y-ay; + else if (ay <= pic_y) + { + h1 = ay+ah-pic_y; + y1 = pic_y; + } + jg_doc.fillRectPattern(pic_x,y1,ax-pic_x,h1,pattern); + jg_doc.fillRectPattern(ax+aw,y1,pic_x+pic_width-ax-aw,h1,pattern); + jg_doc.fillRectPattern(pic_x,ay+ah,pic_width,pic_height+pic_y-ay-ah,pattern); + } + else if(mode == "scale") { + //alert("Resizing: iw:"+image.width+" nw:"+aw); + document.theImage.height = ah; + document.theImage.width = aw; + document.theImage.style.height = ah+" px"; + document.theImage.style.width = aw+" px"; + + P7_Snap('theImage','ant',0,0); + + //alert("After Resizing: iw:"+image.width+" nw:"+aw); + } + + drawBoundHandle(); + jg_doc.paint(); + + showStatus(); + return false; +} + +document.onmousedown=drags +document.onmouseup=dragStopped; + diff --git a/admin/Contact/assets/ImageEditor.css b/admin/Contact/assets/ImageEditor.css new file mode 100644 index 0000000..7cefe46 --- /dev/null +++ b/admin/Contact/assets/ImageEditor.css @@ -0,0 +1,76 @@ +.icons { + font: 11px Tahoma,Verdana,sans-serif; + color: #666699; + text-align: center; + text-decoration: none; + border: 1px solid #EEEEFF; + -Moz-Border-Radius: 6px 6px 6px 6px; +} + +body, td, p { + font: 11px Tahoma,Verdana,sans-serif; +} +.iconsOver { + font: 11px Tahoma,Verdana,sans-serif; + color: #666699; + text-align: center; + text-decoration: none; + background-color: #F9F9FF; + border: 1px solid #666699; + -Moz-Border-Radius: 6px 6px 6px 6px; +} +.topBar { + font: 11px Tahoma,Verdana,sans-serif; + color: #666699; +} +.iconsSel { + font: 11px Tahoma,Verdana,sans-serif; + color: #666699; + text-align: center; + text-decoration: none; + border: 1px solid #666699; + -Moz-Border-Radius: 6px 6px 6px 6px; +} +.iconText { + font: 11px Tahoma,Verdana,sans-serif; + color: #666699; + text-decoration: none; + text-align: center; +} +.measureStats{ + width: 50px; +} + +#slidercasing { + /*border:1px solid #CCCCCC; + background-color:#FFFFFF;*/ + width:100px; + height:5px; + position:relative; + z-index:4; + padding:10px; +} + + +#slidertrack { + position:relative; + border:1px solid #CCCCCC; + background-color:#FFFFCC; + z-index:5; + height:5px; +} + + +#sliderbar { + position:absolute; + z-index:6; + border:1px solid #CCCCCC; + background-color:#DDDDDD; + width:15px; + padding:0px; + height:20px; + cursor: pointer; + top:2px; +} + +select, input, button { font: 11px Tahoma,Verdana,sans-serif; } diff --git a/admin/Contact/assets/dialog.js b/admin/Contact/assets/dialog.js new file mode 100644 index 0000000..7ae4e12 --- /dev/null +++ b/admin/Contact/assets/dialog.js @@ -0,0 +1,111 @@ +// Dialog v3.0 - Copyright (c) 2003-2004 interactivetools.com, inc. +// This copyright notice MUST stay intact for use (see license.txt). +// +// Portions (c) dynarch.com, 2003-2004 +// +// A free WYSIWYG editor replacement for '; + echo ""; + break; + + case "image_align": + case "image2_align": + case "image3_align": + case "image4_align": + case "image5_align": + case "image6_align": + break; + + case "image": + case "image2": + case "image3": + case "image4": + case "image5": + case "image6": + if ($row[$key] != "") { + echo ' +   + +
    + This is the current '.strtoupper( $key ).' used in this newsletter + To change the image, select a new one by clicking the browse button below. + To delete the image without uploading a new one, select + Yes below and click the Update button +
    + +
    +
    + Delete Item Image?   Yes +   No +
    +
    + + '; + } + echo ' + + '.strtoupper($key).': + + + Align: + Left + Right + + + + '.ucfirst($key).' Link: + + + + '; + break; + + case "coupon": + if ($row[$key] != "") { + echo ' +   + +
    + This is the current image used for the Coupon in this newsletter + To change the image, select a new one by clicking the browse button below. + To delete the image without uploading a new one, select + Yes below and click the Update button +
    + +
    +
    + Delete Coupon Image?   Yes +   No +
    +
    + + '; + } + echo ' + + '.strtoupper($key).': + + + + + + '.ucfirst($key).' Link: + + + + '; + break; + } +} + +echo ''; +echo ''; +if ($id) { + ?> + +'; +GLM_TOOLBOX::footer(); +?> + + diff --git a/admin/Contact/edit_contact.phtml b/admin/Contact/edit_contact.phtml new file mode 100644 index 0000000..c1b1017 --- /dev/null +++ b/admin/Contact/edit_contact.phtml @@ -0,0 +1,180 @@ +0){ + $row = db_fetch_array($res,0, PGSQL_ASSOC); + } + else{ + die("No such record"); + } +} +else { // else new entry + // Grab the array of name from $DB_fields and stick it into $row + // Any default values must be placed inside this loop + $row = array(); + for($i=0;$i + +
    +'; +echo "
    "; + +foreach($DB_fields as $key=>$value) { + if($value[type] == "text") { + ?> + + + + + + + + + + + + + + "; + if($row[$value[name]] != "") { + echo "Current Image:"; + echo " + + + Delete this image: + Yes + No + "; + } + echo "New $value[title]:"; + echo ''; + echo ""; + } + elseif($value[type] == "file") { + ?> + + "; + if($row[$value[name]] != "") { + echo "Current File:"; + echo "".$row[$value[name]]." + + + + Delete this File: + + Yes + No + + "; + } + echo "New $value[title]:"; + echo ""; + echo ""; + } + if($value[type] == "desc") { + if($value[name] == "description") { + echo "
    "; + echo "Description and Images"; + } + echo "$value[title]:"; + text_area("$value[name]",$row[$value[name]]); + echo ""; + } + if($value[type] == "state") { + echo "$value[title]:"; + echo build_picklist("$value[name]",$states_US,$row[$value[name]]); + //text_area("$value[name]",$row[$value[name]]); + echo ""; + } + elseif($value[type] == "hide") { + echo ""; + } + elseif( $value['type'] == 'drop' ) + { + echo ''.$value[title].''; + echo ''; + $date_entry = build_picklist($value['name'],$value['drop'],$row[$value['name']]); + echo $date_entry.''; + echo ''; + } + elseif($value[type] == "radio") { + echo "$value[title]:"; + echo "Yes"; + echo "No"; + echo ""; + } +} + +if(isset($id)) { +?> + + + + + + + +
    "; + +GLM_TOOLBOX::footer(); +?> diff --git a/admin/Contact/edit_inquiry.phtml b/admin/Contact/edit_inquiry.phtml new file mode 100644 index 0000000..bf74227 --- /dev/null +++ b/admin/Contact/edit_inquiry.phtml @@ -0,0 +1,87 @@ +db_connect(); +if(!$conn) + { + echo "No Database connection"; + } +GLM_TOOLBOX::top('Edit/Add Inquiry',''); +GLM_TOOLBOX::html_nav_table($nav,$navWidth); +switch($Command) + { + case "Edit": + $qs = "SELECT * + FROM contact_inq + WHERE id = $id"; + $result = pg_Exec($conn,$qs); + $header = pg_result($result,0,'header'); + $description = pg_result($result,0,'description'); + $image = pg_result($result,0,'image'); + $pos = pg_result($result,0,'pos'); + ?> + + + + + + "; + echo ""; + echo ""; + */ + echo ""; + echo ""; + /* + if($image != "") { + echo ""; + echo " + + + + + "; + } + echo ""; + echo ""; + echo ""; + */ + ?> + + + + +
    Header: +
    + +
    Description:
    Current Image: +
    Delete this image: + Yes + No +
    New Image:
    + + +
    + + + + + + +
    Header:
    + + +
    +
    + diff --git a/admin/Contact/emails.php b/admin/Contact/emails.php new file mode 100644 index 0000000..f10e6e8 --- /dev/null +++ b/admin/Contact/emails.php @@ -0,0 +1,38 @@ +db_auto_get_data( $query ); +GLM_TOOLBOX::top( "Email HTML Newsletters", ""); +GLM_TOOLBOX::html_nav_table($nav,$navWidth); +$out = ' + + + + + + + '; + +if( is_array( $data ) ) +{ + foreach( $data as $key => $val ) + { + $out .= ' + + + + + '; + } +} +$out .= '
    +
    + +
    Function:Subject:Last Update:  
    [Edit]  + [View]'.$val["subject"].''.$val["last_update"].'[Delete]
    '; +echo $out; +GLM_TOOLBOX::footer(); +?> diff --git a/admin/Contact/form.js b/admin/Contact/form.js new file mode 100644 index 0000000..0bbabf0 --- /dev/null +++ b/admin/Contact/form.js @@ -0,0 +1,42 @@ +function reshow(object) { + artist = object.options[object.selectedIndex].text; + for (var i = document.track.names.length;i > 0;i--) + document.track.names.options[0] = null; + reloading = true; + showlinks(); + document.track.names.options[0].selected = true; + return false; +} + +function load(object) { + alert('Just testing: ' + object.options[object.selectedIndex].value); + //window.location.href = object.options[object.selectedIndex].value; + return false; +} + +function showlinks() { + if (artist == 'Chris Rea') { + opt('cr/one.zip','The Road To Hell'); + opt('cr/two.zip','Let\'s Dance'); + } + + if (artist == 'Annie Lennox') { + opt('al/why.zip','Why'); + opt('al/wobg.zip','Walking on Broken Glass'); + } + + if (artist == 'Dina Carrol') { + opt('dc/track1.zip','Escaping'); + opt('dc/track2.zip','Only Human'); + } +} + +function opt(href,text) { + if (reloading) { + var optionName = new Option(text, href, false, false) + var length = document.track.names.length; + document.track.names.options[length] = optionName; + } + else + document.write('
    ';C.Command=this;C.onclick=FCKTextColorCommand_OnClick;}};E=D.insertRow(-1).insertCell(-1);E.colSpan=8;C=E.appendChild(CreateSelectionDiv());C.innerHTML='
    '+FCKLang.ColorMoreColors+'
    ';C.Command=this;C.onclick=FCKTextColorCommand_MoreOnClick;} +var FCKPastePlainTextCommand=function(){this.Name='PasteText';};FCKPastePlainTextCommand.prototype.Execute=function(){FCK.PasteAsPlainText();};FCKPastePlainTextCommand.prototype.GetState=function(){return FCK.GetNamedCommandState('Paste');}; +var FCKPasteWordCommand=function(){this.Name='PasteWord';};FCKPasteWordCommand.prototype.Execute=function(){FCK.PasteFromWord();};FCKPasteWordCommand.prototype.GetState=function(){if (FCKConfig.ForcePasteAsPlainText) return -1;else return FCK.GetNamedCommandState('Paste');}; +var FCKTableCommand=function(A){this.Name=A;};FCKTableCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();switch (this.Name){case 'TableInsertRow':FCKTableHandler.InsertRow();break;case 'TableDeleteRows':FCKTableHandler.DeleteRows();break;case 'TableInsertColumn':FCKTableHandler.InsertColumn();break;case 'TableDeleteColumns':FCKTableHandler.DeleteColumns();break;case 'TableInsertCell':FCKTableHandler.InsertCell();break;case 'TableDeleteCells':FCKTableHandler.DeleteCells();break;case 'TableMergeCells':FCKTableHandler.MergeCells();break;case 'TableSplitCell':FCKTableHandler.SplitCell();break;case 'TableDelete':FCKTableHandler.DeleteTable();break;default:alert(FCKLang.UnknownCommand.replace(/%1/g,this.Name));}};FCKTableCommand.prototype.GetState=function(){return 0;} +var FCKStyleCommand=function(){this.Name='Style';this.StylesLoader=new FCKStylesLoader();this.StylesLoader.Load(FCKConfig.StylesXmlPath);this.Styles=this.StylesLoader.Styles;};FCKStyleCommand.prototype.Execute=function(A,B){FCKUndo.SaveUndoStep();if (B.Selected) B.Style.RemoveFromSelection();else B.Style.ApplyToSelection();FCKUndo.SaveUndoStep();FCK.Focus();FCK.Events.FireEvent("OnSelectionChange");};FCKStyleCommand.prototype.GetState=function(){if (!FCK.EditorDocument) return -1;var A=FCK.EditorDocument.selection;if (FCKSelection.GetType()=='Control'){var e=FCKSelection.GetSelectedElement();if (e) return this.StylesLoader.StyleGroups[e.tagName]?0:-1;};return 0;};FCKStyleCommand.prototype.GetActiveStyles=function(){var A=[];if (FCKSelection.GetType()=='Control') this._CheckStyle(FCKSelection.GetSelectedElement(),A,false);else this._CheckStyle(FCKSelection.GetParentElement(),A,true);return A;};FCKStyleCommand.prototype._CheckStyle=function(A,B,C){if (!A) return;if (A.nodeType==1){var D=this.StylesLoader.StyleGroups[A.tagName];if (D){for (var i=0;i<\/body><\/html>');B.close();FCKTools.AddEventListenerEx(D,'focus',FCKPanel_Window_OnFocus,this);FCKTools.AddEventListenerEx(D,'blur',FCKPanel_Window_OnBlur,this);};B.dir=FCKLang.Dir;B.oncontextmenu=FCKTools.CancelEvent;this.MainNode=B.body.appendChild(B.createElement('DIV'));this.MainNode.style.cssFloat=this.IsRTL?'right':'left';};FCKPanel.prototype.AppendStyleSheet=function(A){FCKTools.AppendStyleSheet(this.Document,A);};FCKPanel.prototype.Preload=function(x,y,A){if (this._Popup) this._Popup.show(x,y,0,0,A);};FCKPanel.prototype.Show=function(x,y,A,B,C){var D;if (this._Popup){this._Popup.show(x,y,0,0,A);this.MainNode.style.width=B?B+'px':'';this.MainNode.style.height=C?C+'px':'';D=this.MainNode.offsetWidth;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=(x*-1)+A.offsetWidth-D;};this._Popup.show(x,y,D,this.MainNode.offsetHeight,A);if (this.OnHide){if (this._Timer) CheckPopupOnHide.call(this,true);this._Timer=FCKTools.SetInterval(CheckPopupOnHide,100,this);}}else{if (typeof(FCKFocusManager)!='undefined') FCKFocusManager.Lock();if (this.ParentPanel) this.ParentPanel.Lock();this.MainNode.style.width=B?B+'px':'';this.MainNode.style.height=C?C+'px':'';D=this.MainNode.offsetWidth;if (!B) this._IFrame.width=1;if (!C) this._IFrame.height=1;D=this.MainNode.offsetWidth;var E=FCKTools.GetElementPosition(A.nodeType==9?(FCKTools.IsStrictMode(A)?A.documentElement:A.body):A,this._Window);if (this.IsRTL&&!this.IsContextMenu) x=(x*-1);x+=E.X;y+=E.Y;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=x+A.offsetWidth-D;}else{var F=FCKTools.GetViewPaneSize(this._Window);var G=FCKTools.GetScrollPosition(this._Window);var H=F.Height+G.Y;var I=F.Width+G.X;if ((x+D)>I) x-=x+D-I;if ((y+this.MainNode.offsetHeight)>H) y-=y+this.MainNode.offsetHeight-H;};if (x<0) x=0;this._IFrame.style.left=x+'px';this._IFrame.style.top=y+'px';var J=D;var K=this.MainNode.offsetHeight;this._IFrame.width=J;this._IFrame.height=K;this._IFrame.contentWindow.focus();};this._IsOpened=true;FCKTools.RunFunction(this.OnShow,this);};FCKPanel.prototype.Hide=function(A){if (this._Popup) this._Popup.hide();else{if (!this._IsOpened) return;if (typeof(FCKFocusManager)!='undefined') FCKFocusManager.Unlock();this._IFrame.width=this._IFrame.height=0;this._IsOpened=false;if (this.ParentPanel) this.ParentPanel.Unlock();if (!A) FCKTools.RunFunction(this.OnHide,this);}};FCKPanel.prototype.CheckIsOpened=function(){if (this._Popup) return this._Popup.isOpen;else return this._IsOpened;};FCKPanel.prototype.CreateChildPanel=function(){var A=this._Popup?FCKTools.GetDocumentWindow(this.Document):this._Window;var B=new FCKPanel(A,true);B.ParentPanel=this;return B;};FCKPanel.prototype.Lock=function(){this._LockCounter++;};FCKPanel.prototype.Unlock=function(){if (--this._LockCounter==0&&!this.HasFocus) this.Hide();};function FCKPanel_Window_OnFocus(e,A){A.HasFocus=true;};function FCKPanel_Window_OnBlur(e,A){A.HasFocus=false;if (A._LockCounter==0) FCKTools.RunFunction(A.Hide,A);};function CheckPopupOnHide(A){if (A||!this._Popup.isOpen){window.clearInterval(this._Timer);this._Timer=null;FCKTools.RunFunction(this.OnHide,this);}};function FCKPanel_Cleanup(){this._Popup=null;this._Window=null;this.Document=null;this.MainNode=null;} +var FCKIcon=function(A){var B=A?typeof(A):'undefined';switch (B){case 'number':this.Path=FCKConfig.SkinPath+'fck_strip.gif';this.Size=16;this.Position=A;break;case 'undefined':this.Path=FCK_SPACER_PATH;break;case 'string':this.Path=A;break;default:this.Path=A[0];this.Size=A[1];this.Position=A[2];}};FCKIcon.prototype.CreateIconElement=function(A){var B,eIconImage;if (this.Position){var C='-'+((this.Position-1)*this.Size)+'px';if (FCKBrowserInfo.IsIE){B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path;eIconImage.style.top=C;}else{B=A.createElement('IMG');B.src=FCK_SPACER_PATH;B.style.backgroundPosition='0px '+C;B.style.backgroundImage='url('+this.Path+')';}}else{B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path?this.Path:FCK_SPACER_PATH;};B.className='TB_Button_Image';return B;} +var FCKToolbarButtonUI=function(A,B,C,D,E,F){this.Name=A;this.Label=B||A;this.Tooltip=C||this.Label;this.Style=E||0;this.State=F||0;this.Icon=new FCKIcon(D);if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarButtonUI_Cleanup);};FCKToolbarButtonUI.prototype._CreatePaddingElement=function(A){var B=A.createElement('IMG');B.className='TB_Button_Padding';B.src=FCK_SPACER_PATH;return B;};FCKToolbarButtonUI.prototype.Create=function(A){var B=this.MainElement;if (B){FCKToolbarButtonUI_Cleanup.call(this);if (B.parentNode) B.parentNode.removeChild(B);B=this.MainElement=null;};var C=FCKTools.GetElementDocument(A);B=this.MainElement=C.createElement('DIV');B._FCKButton=this;B.title=this.Tooltip;if (FCKBrowserInfo.IsGecko) B.onmousedown=FCKTools.CancelEvent;this.ChangeState(this.State,true);if (this.Style==0&&!this.ShowArrow){B.appendChild(this.Icon.CreateIconElement(C));}else{var D=B.appendChild(C.createElement('TABLE'));D.cellPadding=0;D.cellSpacing=0;var E=D.insertRow(-1);var F=E.insertCell(-1);if (this.Style==0||this.Style==2) F.appendChild(this.Icon.CreateIconElement(C));else F.appendChild(this._CreatePaddingElement(C));if (this.Style==1||this.Style==2){F=E.insertCell(-1);F.className='TB_Button_Text';F.noWrap=true;F.appendChild(C.createTextNode(this.Label));};if (this.ShowArrow){if (this.Style!=0){E.insertCell(-1).appendChild(this._CreatePaddingElement(C));};F=E.insertCell(-1);var G=F.appendChild(C.createElement('IMG'));G.src=FCKConfig.SkinPath+'images/toolbar.buttonarrow.gif';G.width=5;G.height=3;};F=E.insertCell(-1);F.appendChild(this._CreatePaddingElement(C));};A.appendChild(B);};FCKToolbarButtonUI.prototype.ChangeState=function(A,B){if (!B&&this.State==A) return;var e=this.MainElement;switch (parseInt(A,10)){case 0:e.className='TB_Button_Off';e.onmouseover=FCKToolbarButton_OnMouseOverOff;e.onmouseout=FCKToolbarButton_OnMouseOutOff;e.onclick=FCKToolbarButton_OnClick;break;case 1:e.className='TB_Button_On';e.onmouseover=FCKToolbarButton_OnMouseOverOn;e.onmouseout=FCKToolbarButton_OnMouseOutOn;e.onclick=FCKToolbarButton_OnClick;break;case -1:e.className='TB_Button_Disabled';e.onmouseover=null;e.onmouseout=null;e.onclick=null;break;};this.State=A;};function FCKToolbarButtonUI_Cleanup(){if (this.MainElement){this.MainElement._FCKButton=null;this.MainElement=null;}};function FCKToolbarButton_OnMouseOverOn(){this.className='TB_Button_On_Over';};function FCKToolbarButton_OnMouseOutOn(){this.className='TB_Button_On';};function FCKToolbarButton_OnMouseOverOff(){this.className='TB_Button_Off_Over';};function FCKToolbarButton_OnMouseOutOff(){this.className='TB_Button_Off';};function FCKToolbarButton_OnClick(e){if (this._FCKButton.OnClick) this._FCKButton.OnClick(this._FCKButton);}; +var FCKToolbarButton=function(A,B,C,D,E,F,G){this.CommandName=A;this.Label=B;this.Tooltip=C;this.Style=D;this.SourceView=E?true:false;this.ContextSensitive=F?true:false;if (G==null) this.IconPath=FCKConfig.SkinPath+'toolbar/'+A.toLowerCase()+'.gif';else if (typeof(G)=='number') this.IconPath=[FCKConfig.SkinPath+'fck_strip.gif',16,G];};FCKToolbarButton.prototype.Create=function(A){this._UIButton=new FCKToolbarButtonUI(this.CommandName,this.Label,this.Tooltip,this.IconPath,this.Style);this._UIButton.OnClick=this.Click;this._UIButton._ToolbarButton=this;this._UIButton.Create(A);};FCKToolbarButton.prototype.RefreshState=function(){var A=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (A==this._UIButton.State) return;this._UIButton.ChangeState(A);};FCKToolbarButton.prototype.Click=function(){var A=this._ToolbarButton||this;FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(A.CommandName).Execute();};FCKToolbarButton.prototype.Enable=function(){this.RefreshState();};FCKToolbarButton.prototype.Disable=function(){this._UIButton.ChangeState(-1);} +var FCKSpecialCombo=function(A,B,C,D,E){this.FieldWidth=B||100;this.PanelWidth=C||150;this.PanelMaxHeight=D||150;this.Label=' ';this.Caption=A;this.Tooltip=A;this.Style=2;this.Enabled=true;this.Items={};this._Panel=new FCKPanel(E||window,true);this._Panel.AppendStyleSheet(FCKConfig.SkinPath+'fck_editor.css');this._PanelBox=this._Panel.MainNode.appendChild(this._Panel.Document.createElement('DIV'));this._PanelBox.className='SC_Panel';this._PanelBox.style.width=this.PanelWidth+'px';this._PanelBox.innerHTML='
    ';this._ItemsHolderEl=this._PanelBox.getElementsByTagName('TD')[0];if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKSpecialCombo_Cleanup);};function FCKSpecialCombo_ItemOnMouseOver(){this.className+=' SC_ItemOver';};function FCKSpecialCombo_ItemOnMouseOut(){this.className=this.originalClass;};function FCKSpecialCombo_ItemOnClick(){this.className=this.originalClass;this.FCKSpecialCombo._Panel.Hide();this.FCKSpecialCombo.SetLabel(this.FCKItemLabel);if (typeof(this.FCKSpecialCombo.OnSelect)=='function') this.FCKSpecialCombo.OnSelect(this.FCKItemID,this);};FCKSpecialCombo.prototype.AddItem=function(A,B,C,D){var E=this._ItemsHolderEl.appendChild(this._Panel.Document.createElement('DIV'));E.className=E.originalClass='SC_Item';E.innerHTML=B;E.FCKItemID=A;E.FCKItemLabel=C||A;E.FCKSpecialCombo=this;E.Selected=false;if (FCKBrowserInfo.IsIE) E.style.width='100%';if (D) E.style.backgroundColor=D;E.onmouseover=FCKSpecialCombo_ItemOnMouseOver;E.onmouseout=FCKSpecialCombo_ItemOnMouseOut;E.onclick=FCKSpecialCombo_ItemOnClick;this.Items[A.toString().toLowerCase()]=E;return E;};FCKSpecialCombo.prototype.SelectItem=function(A){A=A?A.toString().toLowerCase():'';var B=this.Items[A];if (B){B.className=B.originalClass='SC_ItemSelected';B.Selected=true;}};FCKSpecialCombo.prototype.SelectItemByLabel=function(A,B){for (var C in this.Items){var D=this.Items[C];if (D.FCKItemLabel==A){D.className=D.originalClass='SC_ItemSelected';D.Selected=true;if (B) this.SetLabel(A);}}};FCKSpecialCombo.prototype.DeselectAll=function(A){for (var i in this.Items){this.Items[i].className=this.Items[i].originalClass='SC_Item';this.Items[i].Selected=false;};if (A) this.SetLabel('');};FCKSpecialCombo.prototype.SetLabelById=function(A){A=A?A.toString().toLowerCase():'';var B=this.Items[A];this.SetLabel(B?B.FCKItemLabel:'');};FCKSpecialCombo.prototype.SetLabel=function(A){this.Label=A.length==0?' ':A;if (this._LabelEl){this._LabelEl.innerHTML=this.Label;FCKTools.DisableSelection(this._LabelEl);}};FCKSpecialCombo.prototype.SetEnabled=function(A){this.Enabled=A;this._OuterTable.className=A?'':'SC_FieldDisabled';};FCKSpecialCombo.prototype.Create=function(A){var B=FCKTools.GetElementDocument(A);var C=this._OuterTable=A.appendChild(B.createElement('TABLE'));C.cellPadding=0;C.cellSpacing=0;C.insertRow(-1);var D;var E;switch (this.Style){case 0:D='TB_ButtonType_Icon';E=false;break;case 1:D='TB_ButtonType_Text';E=false;break;case 2:E=true;break;};if (this.Caption&&this.Caption.length>0&&E){var F=C.rows[0].insertCell(-1);F.innerHTML=this.Caption;F.className='SC_FieldCaption';};var G=FCKTools.AppendElement(C.rows[0].insertCell(-1),'div');if (E){G.className='SC_Field';G.style.width=this.FieldWidth+'px';G.innerHTML='
     
    ';this._LabelEl=G.getElementsByTagName('label')[0];this._LabelEl.innerHTML=this.Label;}else{G.className='TB_Button_Off';G.innerHTML='
    '+this.Caption+'
    ';};G.SpecialCombo=this;G.onmouseover=FCKSpecialCombo_OnMouseOver;G.onmouseout=FCKSpecialCombo_OnMouseOut;G.onclick=FCKSpecialCombo_OnClick;FCKTools.DisableSelection(this._Panel.Document.body);};function FCKSpecialCombo_Cleanup(){this._LabelEl=null;this._OuterTable=null;this._ItemsHolderEl=null;this._PanelBox=null;if (this.Items){for (var A in this.Items) this.Items[A]=null;}};function FCKSpecialCombo_OnMouseOver(){if (this.SpecialCombo.Enabled){switch (this.SpecialCombo.Style){case 0:this.className='TB_Button_On_Over';break;case 1:this.className='TB_Button_On_Over';break;case 2:this.className='SC_Field SC_FieldOver';break;}}};function FCKSpecialCombo_OnMouseOut(){switch (this.SpecialCombo.Style){case 0:this.className='TB_Button_Off';break;case 1:this.className='TB_Button_Off';break;case 2:this.className='SC_Field';break;}};function FCKSpecialCombo_OnClick(e){var A=this.SpecialCombo;if (A.Enabled){var B=A._Panel;var C=A._PanelBox;var D=A._ItemsHolderEl;var E=A.PanelMaxHeight;if (A.OnBeforeClick) A.OnBeforeClick(A);if (FCKBrowserInfo.IsIE) B.Preload(0,this.offsetHeight,this);if (D.offsetHeight>E) C.style.height=E+'px';else C.style.height='';B.Show(0,this.offsetHeight,this);}}; +var FCKToolbarSpecialCombo=function(){this.SourceView=false;this.ContextSensitive=true;this._LastValue=null;};function FCKToolbarSpecialCombo_OnSelect(A,B){FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).Execute(A,B);};FCKToolbarSpecialCombo.prototype.Create=function(A){this._Combo=new FCKSpecialCombo(this.GetLabel(),this.FieldWidth,this.PanelWidth,this.PanelMaxHeight,FCKBrowserInfo.IsIE?window:FCKTools.GetElementWindow(A).parent);this._Combo.Tooltip=this.Tooltip;this._Combo.Style=this.Style;this.CreateItems(this._Combo);this._Combo.Create(A);this._Combo.CommandName=this.CommandName;this._Combo.OnSelect=FCKToolbarSpecialCombo_OnSelect;};function FCKToolbarSpecialCombo_RefreshActiveItems(A,B){A.DeselectAll();A.SelectItem(B);A.SetLabelById(B);};FCKToolbarSpecialCombo.prototype.RefreshState=function(){var A;var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (B!=-1){A=1;if (this.RefreshActiveItems) this.RefreshActiveItems(this._Combo,B);else{if (this._LastValue!=B){this._LastValue=B;FCKToolbarSpecialCombo_RefreshActiveItems(this._Combo,B);}}}else A=-1;if (A==this.State) return;if (A==-1){this._Combo.DeselectAll();this._Combo.SetLabel('');};this.State=A;this._Combo.SetEnabled(A!=-1);};FCKToolbarSpecialCombo.prototype.Enable=function(){this.RefreshState();};FCKToolbarSpecialCombo.prototype.Disable=function(){this.State=-1;this._Combo.DeselectAll();this._Combo.SetLabel('');this._Combo.SetEnabled(false);}; +var FCKToolbarFontsCombo=function(A,B){this.CommandName='FontName';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarFontsCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontsCombo.prototype.GetLabel=function(){return FCKLang.Font;};FCKToolbarFontsCombo.prototype.CreateItems=function(A){var B=FCKConfig.FontNames.split(';');for (var i=0;i'+B[i]+'
    ');} +var FCKToolbarFontSizeCombo=function(A,B){this.CommandName='FontSize';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarFontSizeCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontSizeCombo.prototype.GetLabel=function(){return FCKLang.FontSize;};FCKToolbarFontSizeCombo.prototype.CreateItems=function(A){A.FieldWidth=70;var B=FCKConfig.FontSizes.split(';');for (var i=0;i'+C[1]+'
    ',C[1]);}} +var FCKToolbarFontFormatCombo=function(A,B){this.CommandName='FontFormat';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;this.NormalLabel='Normal';this.PanelWidth=190;};FCKToolbarFontFormatCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontFormatCombo.prototype.GetLabel=function(){return FCKLang.FontFormat;};FCKToolbarFontFormatCombo.prototype.CreateItems=function(A){var B=A._Panel.Document;FCKTools.AppendStyleSheet(B,FCKConfig.ToolbarComboPreviewCSS);if (FCKConfig.BodyId&&FCKConfig.BodyId.length>0) B.body.id=FCKConfig.BodyId;if (FCKConfig.BodyClass&&FCKConfig.BodyClass.length>0) B.body.className+=' '+FCKConfig.BodyClass;var C=FCKLang['FontFormats'].split(';');var D={p:C[0],pre:C[1],address:C[2],h1:C[3],h2:C[4],h3:C[5],h4:C[6],h5:C[7],h6:C[8],div:C[9]};var E=FCKConfig.FontFormats.split(';');for (var i=0;i<'+F+'>'+G+'
    ',G);}};if (FCKBrowserInfo.IsIE){FCKToolbarFontFormatCombo.prototype.RefreshActiveItems=function(A,B){if (B==this.NormalLabel){if (A.Label!=' ') A.DeselectAll(true);}else{if (this._LastValue==B) return;A.SelectItemByLabel(B,true);};this._LastValue=B;}} +var FCKToolbarStyleCombo=function(A,B){this.CommandName='Style';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarStyleCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarStyleCombo.prototype.GetLabel=function(){return FCKLang.Style;};FCKToolbarStyleCombo.prototype.CreateItems=function(A){var B=A._Panel.Document;FCKTools.AppendStyleSheet(B,FCKConfig.ToolbarComboPreviewCSS);B.body.className+=' ForceBaseFont';if (FCKConfig.BodyId&&FCKConfig.BodyId.length>0) B.body.id=FCKConfig.BodyId;if (FCKConfig.BodyClass&&FCKConfig.BodyClass.length>0) B.body.className+=' '+FCKConfig.BodyClass;if (!(FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsGecko10)) A.OnBeforeClick=this.RefreshVisibleItems;var C=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).Styles;for (var s in C){var D=C[s];var E;if (D.IsObjectElement) E=A.AddItem(s,s);else E=A.AddItem(s,D.GetOpenerTag()+s+D.GetCloserTag());E.Style=D;}};FCKToolbarStyleCombo.prototype.RefreshActiveItems=function(A){A.DeselectAll();var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetActiveStyles();if (B.length>0){for (var i=0;i'+document.getElementById('xToolbarSpace').innerHTML+'');G.close();G.oncontextmenu=FCKTools.CancelEvent;FCKTools.AppendStyleSheet(G,FCKConfig.SkinPath+'fck_editor.css');B=D.__FCKToolbarSet=new FCKToolbarSet(G);B._IFrame=F;if (FCK.IECleanup) FCK.IECleanup.AddItem(D,FCKToolbarSet_Target_Cleanup);};B.CurrentInstance=FCK;FCK.AttachToOnSelectionChange(B.RefreshItemsState);return B;};function FCK_OnBlur(A){var B=A.ToolbarSet;if (B.CurrentInstance==A) B.Disable();};function FCK_OnFocus(A){var B=A.ToolbarSet;var C=A||FCK;B.CurrentInstance.FocusManager.RemoveWindow(B._IFrame.contentWindow);B.CurrentInstance=C;C.FocusManager.AddWindow(B._IFrame.contentWindow,true);B.Enable();};function FCKToolbarSet_Cleanup(){this._TargetElement=null;this._IFrame=null;};function FCKToolbarSet_Target_Cleanup(){this.__FCKToolbarSet=null;};var FCKToolbarSet=function(A){this._Document=A;this._TargetElement=A.getElementById('xToolbar');var B=A.getElementById('xExpandHandle');var C=A.getElementById('xCollapseHandle');B.title=FCKLang.ToolbarExpand;B.onclick=FCKToolbarSet_Expand_OnClick;C.title=FCKLang.ToolbarCollapse;C.onclick=FCKToolbarSet_Collapse_OnClick;if (!FCKConfig.ToolbarCanCollapse||FCKConfig.ToolbarStartExpanded) this.Expand();else this.Collapse();C.style.display=FCKConfig.ToolbarCanCollapse?'':'none';if (FCKConfig.ToolbarCanCollapse) C.style.display='';else A.getElementById('xTBLeftBorder').style.display='';this.Toolbars=[];this.IsLoaded=false;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarSet_Cleanup);};function FCKToolbarSet_Expand_OnClick(){FCK.ToolbarSet.Expand();};function FCKToolbarSet_Collapse_OnClick(){FCK.ToolbarSet.Collapse();};FCKToolbarSet.prototype.Expand=function(){this._ChangeVisibility(false);};FCKToolbarSet.prototype.Collapse=function(){this._ChangeVisibility(true);};FCKToolbarSet.prototype._ChangeVisibility=function(A){this._Document.getElementById('xCollapsed').style.display=A?'':'none';this._Document.getElementById('xExpanded').style.display=A?'none':'';if (FCKBrowserInfo.IsGecko){FCKTools.RunFunction(window.onresize);}};FCKToolbarSet.prototype.Load=function(A){this.Name=A;this.Items=[];this.ItemsWysiwygOnly=[];this.ItemsContextSensitive=[];this._TargetElement.innerHTML='';var B=FCKConfig.ToolbarSets[A];if (!B){alert(FCKLang.UnknownToolbarSet.replace(/%1/g,A));return;};this.Toolbars=[];for (var x=0;x0) A.deleteRow(0);}};FCKMenuBlock.prototype.Create=function(A){if (!this._ItemsTable){if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKMenuBlock_Cleanup);this._Window=FCKTools.GetElementWindow(A);var B=FCKTools.GetElementDocument(A);var C=A.appendChild(B.createElement('table'));C.cellPadding=0;C.cellSpacing=0;FCKTools.DisableSelection(C);var D=C.insertRow(-1).insertCell(-1);D.className='MN_Menu';var E=this._ItemsTable=D.appendChild(B.createElement('table'));E.cellPadding=0;E.cellSpacing=0;};for (var i=0;i0&&F.href.length==0);if (G) return;menu.AddSeparator();if (E) menu.AddItem('Link',FCKLang.EditLink,34);menu.AddItem('Unlink',FCKLang.RemoveLink,35);}}};case 'Image':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&!tag.getAttribute('_fckfakelement')){menu.AddSeparator();menu.AddItem('Image',FCKLang.ImageProperties,37);}}};case 'Anchor':return {AddItems:function(menu,tag,tagName){var F=FCKSelection.MoveToAncestorNode('A');var G=(F&&F.name.length>0);if (G||(tagName=='IMG'&&tag.getAttribute('_fckanchor'))){menu.AddSeparator();menu.AddItem('Anchor',FCKLang.AnchorProp,36);}}};case 'Flash':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckflash')){menu.AddSeparator();menu.AddItem('Flash',FCKLang.FlashProperties,38);}}};case 'Form':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('FORM')){menu.AddSeparator();menu.AddItem('Form',FCKLang.FormProp,48);}}};case 'Checkbox':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='checkbox'){menu.AddSeparator();menu.AddItem('Checkbox',FCKLang.CheckboxProp,49);}}};case 'Radio':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='radio'){menu.AddSeparator();menu.AddItem('Radio',FCKLang.RadioButtonProp,50);}}};case 'TextField':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='text'||tag.type=='password')){menu.AddSeparator();menu.AddItem('TextField',FCKLang.TextFieldProp,51);}}};case 'HiddenField':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='hidden'){menu.AddSeparator();menu.AddItem('HiddenField',FCKLang.HiddenFieldProp,56);}}};case 'ImageButton':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='image'){menu.AddSeparator();menu.AddItem('ImageButton',FCKLang.ImageButtonProp,55);}}};case 'Button':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='button'||tag.type=='submit'||tag.type=='reset')){menu.AddSeparator();menu.AddItem('Button',FCKLang.ButtonProp,54);}}};case 'Select':return {AddItems:function(menu,tag,tagName){if (tagName=='SELECT'){menu.AddSeparator();menu.AddItem('Select',FCKLang.SelectionFieldProp,53);}}};case 'Textarea':return {AddItems:function(menu,tag,tagName){if (tagName=='TEXTAREA'){menu.AddSeparator();menu.AddItem('Textarea',FCKLang.TextareaProp,52);}}};case 'BulletedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('UL')){menu.AddSeparator();menu.AddItem('BulletedList',FCKLang.BulletedListProp,27);}}};case 'NumberedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('OL')){menu.AddSeparator();menu.AddItem('NumberedList',FCKLang.NumberedListProp,26);}}};};return null;};function FCK_ContextMenu_OnBeforeOpen(){FCK.Events.FireEvent('OnSelectionChange');var A,sTagName;if ((A=FCKSelection.GetSelectedElement())) sTagName=A.tagName;var B=FCK.ContextMenu._InnerContextMenu;B.RemoveAllItems();var C=FCK.ContextMenu.Listeners;for (var i=0;i0){var A;if (this.AvailableLangs.IndexOf(FCKLanguageManager.ActiveLanguage.Code)>=0) A=FCKLanguageManager.ActiveLanguage.Code;else A=this.AvailableLangs[0];LoadScript(this.Path+'lang/'+A+'.js');};LoadScript(this.Path+'fckplugin.js');} +var FCKPlugins=FCK.Plugins={};FCKPlugins.ItemsCount=0;FCKPlugins.Items={};FCKPlugins.Load=function(){var A=FCKPlugins.Items;for (var i=0;i-1);};String.prototype.Equals=function(){var A=arguments;if (A.length==1&&A[0].pop) A=A[0];for (var i=0;iC) return false;if (B){var E=new RegExp(A+'$','i');return E.test(this);}else return (D==0||this.substr(C-D,D)==A);};String.prototype.Remove=function(A,B){var s='';if (A>0) s=this.substring(0,A);if (A+B0){var B=A.pop();if (B) B[1].call(B[0]);};this._FCKCleanupObj=null;if (CollectGarbage) CollectGarbage();} +var s=navigator.userAgent.toLowerCase();var FCKBrowserInfo={IsIE:s.Contains('msie'),IsIE7:s.Contains('msie 7'),IsGecko:s.Contains('gecko/'),IsSafari:s.Contains('safari'),IsOpera:s.Contains('opera'),IsMac:s.Contains('macintosh')};(function(A){A.IsGeckoLike=(A.IsGecko||A.IsSafari||A.IsOpera);if (A.IsGecko){var B=s.match(/gecko\/(\d+)/)[1];A.IsGecko10=B<20051111;}else A.IsGecko10=false;})(FCKBrowserInfo); +var FCKURLParams={};(function(){var A=document.location.search.substr(1).split('&');for (var i=0;i0?'':'';var A=FCK.KeystrokeHandler=new FCKKeystrokeHandler();A.OnKeystroke=_FCK_KeystrokeHandler_OnKeystroke;A.SetKeystrokes(FCKConfig.Keystrokes);if (FCKBrowserInfo.IsIE7){if ((CTRL+86/*V*/) in A.Keystrokes) A.SetKeystrokes([CTRL+86,true]);if ((SHIFT+45/*INS*/) in A.Keystrokes) A.SetKeystrokes([SHIFT+45,true]);};this.EditingArea=new FCKEditingArea(document.getElementById('xEditingArea'));this.EditingArea.FFSpellChecker=false;this.SetHTML(this.GetLinkedFieldValue());},Focus:function(){FCK.EditingArea.Focus();},SetStatus:function(A){this.Status=A;if (A==1){FCKFocusManager.AddWindow(window,true);if (FCKBrowserInfo.IsIE) FCKFocusManager.AddWindow(window.frameElement,true);if (FCKConfig.StartupFocus) FCK.Focus();};this.Events.FireEvent('OnStatusChange',A);},FixBody:function(){var A=FCKConfig.EnterMode;if (A!='p'&&A!='div') return;var B=this.EditorDocument;if (!B) return;var C=B.body;if (!C) return;FCKDomTools.TrimNode(C);var D=C.firstChild;var E;while (D){var F=false;switch (D.nodeType){case 1:if (!FCKListsLib.BlockElements[D.nodeName.toLowerCase()]) F=true;break;case 3:if (E||D.nodeValue.Trim().length>0) F=true;};if (F){var G=D.parentNode;if (!E) E=G.insertBefore(B.createElement(A),D);E.appendChild(G.removeChild(D));D=E.nextSibling;}else{if (E){FCKDomTools.TrimNode(E);E=null;};D=D.nextSibling;}};if (E) FCKDomTools.TrimNode(E);},GetXHTML:function(A){if (FCK.EditMode==1) return FCK.EditingArea.Textarea.value;this.FixBody();var B;var C=FCK.EditorDocument;if (!C) return null;if (FCKConfig.FullPage) B=FCKXHtml.GetXHTML(C.getElementsByTagName('html')[0],true,A);else{if (FCKConfig.IgnoreEmptyParagraphValue&&C.body.innerHTML=='

     

    ') B='';else B=FCKXHtml.GetXHTML(C.body,false,A);};B=FCK.ProtectEventsRestore(B);if (FCKBrowserInfo.IsIE) B=B.replace(FCKRegexLib.ToReplace,'$1');if (FCK.DocTypeDeclaration&&FCK.DocTypeDeclaration.length>0) B=FCK.DocTypeDeclaration+'\n'+B;if (FCK.XmlDeclaration&&FCK.XmlDeclaration.length>0) B=FCK.XmlDeclaration+'\n'+B;return FCKConfig.ProtectedSource.Revert(B);},UpdateLinkedField:function(){FCK.LinkedField.value=FCK.GetXHTML(FCKConfig.FormatOutput);FCK.Events.FireEvent('OnAfterLinkedFieldUpdate');},RegisteredDoubleClickHandlers:{},OnDoubleClick:function(A){var B=FCK.RegisteredDoubleClickHandlers[A.tagName];if (B) B(A);},RegisterDoubleClickHandler:function(A,B){FCK.RegisteredDoubleClickHandlers[B.toUpperCase()]=A;},OnAfterSetHTML:function(){FCKDocumentProcessor.Process(FCK.EditorDocument);FCKUndo.SaveUndoStep();FCK.Events.FireEvent('OnSelectionChange');FCK.Events.FireEvent('OnAfterSetHTML');},ProtectUrls:function(A){A=A.replace(FCKRegexLib.ProtectUrlsA,'$1$4$2$3$5$2 _fcksavedurl=$2$3$5$2');A=A.replace(FCKRegexLib.ProtectUrlsImg,'$1$4$2$3$5$2 _fcksavedurl=$2$3$5$2');return A;},ProtectEvents:function(A){return A.replace(FCKRegexLib.TagsWithEvent,_FCK_ProtectEvents_ReplaceTags);},ProtectEventsRestore:function(A){return A.replace(FCKRegexLib.ProtectedEvents,_FCK_ProtectEvents_RestoreEvents);},ProtectTags:function(A){var B='META';if (FCKConfig.ProtectedTags.length>0) B+='|'+FCKConfig.ProtectedTags;if (FCKBrowserInfo.IsIE) B+='|ABBR';var C=new RegExp('<('+B+')([ \>])','gi');A=A.replace(C,'','gi');A=A.replace(C,'<\/FCK:$1>');return A;},SetHTML:function(A){this.EditingArea.Mode=FCK.EditMode;if (FCK.EditMode==0){A=FCKConfig.ProtectedSource.Protect(A);A=FCK.ProtectEvents(A);A=FCK.ProtectUrls(A);A=FCK.ProtectTags(A);if (FCKBrowserInfo.IsGecko){A=A.replace(FCKRegexLib.StrongOpener,'');A=A.replace(FCKRegexLib.EmOpener,'');};var B='';if (FCKConfig.FullPage){if (!FCKRegexLib.HeadOpener.test(A)){if (!FCKRegexLib.HtmlOpener.test(A)) A=''+A+'';A=A.replace(FCKRegexLib.HtmlOpener,'$&');};FCK.DocTypeDeclaration=A.match(FCKRegexLib.DocTypeTag);if (FCKBrowserInfo.IsIE) B=FCK._GetBehaviorsStyle();else if (FCKConfig.ShowBorders) B='';B+='';B=A.replace(FCKRegexLib.HeadCloser,B+'$&');if (FCK.TempBaseTag.length>0&&!FCKRegexLib.HasBaseTag.test(A)) B=B.replace(FCKRegexLib.HeadOpener,'$&'+FCK.TempBaseTag);}else{B=FCKConfig.DocType+'';if (FCKBrowserInfo.IsIE) B+=FCK._GetBehaviorsStyle();else if (FCKConfig.ShowBorders) B+='';B+=FCK.TempBaseTag;var C='0) C+=' id="'+FCKConfig.BodyId+'"';if (FCKConfig.BodyClass&&FCKConfig.BodyClass.length>0) C+=' class="'+FCKConfig.BodyClass+'"';B+=''+C+'>';if (FCKBrowserInfo.IsGecko&&(A.length==0||FCKRegexLib.EmptyParagraph.test(A))) B+=GECKO_BOGUS;else B+=A;B+='';};this.EditingArea.OnLoad=_FCK_EditingArea_OnLoad;this.EditingArea.Start(B);}else{FCK.EditorWindow=null;FCK.EditorDocument=null;this.EditingArea.OnLoad=null;this.EditingArea.Start(A);this.EditingArea.Textarea._FCKShowContextMenu=true;FCK.EnterKeyHandler=null;FCK.KeystrokeHandler.AttachToElement(this.EditingArea.Textarea);this.EditingArea.Textarea.focus();FCK.Events.FireEvent('OnAfterSetHTML');};if (FCKBrowserInfo.IsGecko) window.onresize();},HasFocus:false,RedirectNamedCommands:{},ExecuteNamedCommand:function(A,B,C){FCKUndo.SaveUndoStep();if (!C&&FCK.RedirectNamedCommands[A]!=null) FCK.ExecuteRedirectedNamedCommand(A,B);else{FCK.Focus();FCK.EditorDocument.execCommand(A,false,B);FCK.Events.FireEvent('OnSelectionChange');};FCKUndo.SaveUndoStep();},GetNamedCommandState:function(A){try{if (!FCK.EditorDocument.queryCommandEnabled(A)) return -1;else return FCK.EditorDocument.queryCommandState(A)?1:0;}catch (e){return 0;}},GetNamedCommandValue:function(A){var B='';var C=FCK.GetNamedCommandState(A);if (C==-1) return null;try{B=this.EditorDocument.queryCommandValue(A);}catch(e) {};return B?B:'';},PasteFromWord:function(){FCKDialog.OpenDialog('FCKDialog_Paste',FCKLang.PasteFromWord,'dialog/fck_paste.html',400,330,'Word');},Preview:function(){var A=FCKConfig.ScreenWidth*0.8;var B=FCKConfig.ScreenHeight*0.7;var C=(FCKConfig.ScreenWidth-A)/2;var D=window.open('',null,'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+A+',height='+B+',left='+C);var E;if (FCKConfig.FullPage){if (FCK.TempBaseTag.length>0) E=FCK.TempBaseTag+FCK.GetXHTML();else E=FCK.GetXHTML();}else{E=FCKConfig.DocType+''+FCK.TempBaseTag+''+FCKLang.Preview+''+_FCK_GetEditorAreaStyleTags()+''+FCK.GetXHTML()+'';};D.document.write(E);D.document.close();},SwitchEditMode:function(A){var B=(FCK.EditMode==0);var C;if (B){if (!A&&FCKBrowserInfo.IsIE) FCKUndo.SaveUndoStep();C=FCK.GetXHTML(FCKConfig.FormatSource);if (C==null) return false;}else C=this.EditingArea.Textarea.value;FCK.EditMode=B?1:0;FCK.SetHTML(C);FCK.Focus();FCKTools.RunFunction(FCK.ToolbarSet.RefreshModeState,FCK.ToolbarSet);return true;},CreateElement:function(A){var e=FCK.EditorDocument.createElement(A);return FCK.InsertElementAndGetIt(e);},InsertElementAndGetIt:function(e){e.setAttribute('FCKTempLabel','true');this.InsertElement(e);var A=FCK.EditorDocument.getElementsByTagName(e.tagName);for (var i=0;i/g,/\r/g,/\n/g],[''',''','"','=','<','>',' ',' '])+'"';};function _FCK_ProtectEvents_RestoreEvents(A,B){return B.ReplaceAll([/'/g,/"/g,/=/g,/</g,/>/g,/ /g,/ /g,/'/g],["'",'"','=','<','>','\r','\n','&']);};function _FCK_EditingArea_OnLoad(){FCK.EditorWindow=FCK.EditingArea.Window;FCK.EditorDocument=FCK.EditingArea.Document;FCK.InitializeBehaviors();if (!FCKConfig.DisableEnterKeyHandler) FCK.EnterKeyHandler=new FCKEnterKey(FCK.EditorWindow,FCKConfig.EnterMode,FCKConfig.ShiftEnterMode);FCK.KeystrokeHandler.AttachToElement(FCK.EditorDocument);FCK.OnAfterSetHTML();if (FCK.Status!=0) return;FCK.ResetIsDirty();FCK.SetStatus(1);};function _FCK_GetEditorAreaStyleTags(){var A='';var B=FCKConfig.EditorAreaCSS;for (var i=0;i';return A;};function _FCK_KeystrokeHandler_OnKeystroke(A,B){if (FCK.Status!=2) return false;if (FCK.EditMode==0){if (B=='Paste') return!FCK.Events.FireEvent('OnPaste');}else{if (B.Equals('Paste','Undo','Redo','SelectAll')) return false;};var C=FCK.Commands.GetCommand(B);return (C.Execute.apply(C,FCKTools.ArgumentsToArray(arguments,2))!==false);};(function(){var A=window.parent.document;var B=A.getElementById(FCK.Name);var i=0;while (B||i==0){if (B&&B.tagName.toLowerCase().Equals('input','textarea')){FCK.LinkedField=B;break;};B=A.getElementsByName(FCK.Name)[i++];}})();var FCKTempBin={Elements:[],AddElement:function(A){var B=this.Elements.length;this.Elements[B]=A;return B;},RemoveElement:function(A){var e=this.Elements[A];this.Elements[A]=null;return e;},Reset:function(){var i=0;while (i0) C+='TABLE { behavior: '+B+' ; }';C+='';FCK._BehaviorsStyle=C;};return FCK._BehaviorsStyle;};function Doc_OnMouseUp(){if (FCK.EditorWindow.event.srcElement.tagName=='HTML'){FCK.Focus();FCK.EditorWindow.event.cancelBubble=true;FCK.EditorWindow.event.returnValue=false;}};function Doc_OnPaste(){return (FCK.Status==2&&FCK.Events.FireEvent("OnPaste"));};function Doc_OnKeyDown(){if (FCK.EditorWindow){var e=FCK.EditorWindow.event;if (!(e.keyCode>=16&&e.keyCode<=18)) Doc_OnKeyDownUndo();};return true;};function Doc_OnKeyDownUndo(){if (!FCKUndo.Typing){FCKUndo.SaveUndoStep();FCKUndo.Typing=true;FCK.Events.FireEvent("OnSelectionChange");};FCKUndo.TypesCount++;if (FCKUndo.TypesCount>FCKUndo.MaxTypes){FCKUndo.TypesCount=0;FCKUndo.SaveUndoStep();}};function Doc_OnDblClick(){FCK.OnDoubleClick(FCK.EditorWindow.event.srcElement);FCK.EditorWindow.event.cancelBubble=true;};function Doc_OnSelectionChange(){FCK.Events.FireEvent("OnSelectionChange");};FCK.InitializeBehaviors=function(A){this.EditorDocument.attachEvent('onmouseup',Doc_OnMouseUp);this.EditorDocument.body.attachEvent('onpaste',Doc_OnPaste);FCK.ContextMenu._InnerContextMenu.AttachToElement(FCK.EditorDocument.body);if (FCKConfig.TabSpaces>0){window.FCKTabHTML='';for (i=0;i 
    '+A;B.getElementById('__fakeFCKRemove__').removeNode(true);};function FCK_PreloadImages(){var A=new FCKImagePreloader();A.AddImages(FCKConfig.PreloadImages);A.AddImages(FCKConfig.SkinPath+'fck_strip.gif');A.OnComplete=LoadToolbarSetup;A.Start();};function Document_OnContextMenu(){return (event.srcElement._FCKShowContextMenu==true);};document.oncontextmenu=Document_OnContextMenu;function FCK_Cleanup(){this.EditorWindow=null;this.EditorDocument=null;};FCK.Paste=function(){if (FCK._PasteIsRunning) return true;if (FCKConfig.ForcePasteAsPlainText){FCK.PasteAsPlainText();return false;};var A=FCK.GetClipboardHTML();if (FCKConfig.AutoDetectPasteFromWord&&A.length>0){var B=/<\w[^>]*(( class="?MsoNormal"?)|(="mso-))/gi;if (B.test(A)){if (confirm(FCKLang.PasteWordConfirm)){FCK.PasteFromWord();return false;}}};FCK._PasteIsRunning=true;FCK.ExecuteNamedCommand('Paste');delete FCK._PasteIsRunning;return false;};FCK.PasteAsPlainText=function(){var A=clipboardData.getData("Text");if (A&&A.length>0){A=FCKTools.HTMLEncode(A).replace(/\n/g,'
    ');this.InsertHtml(A);}};FCK.InsertElement=function(A){FCK.InsertHtml(A.outerHTML);};FCK.GetClipboardHTML=function(){var A=document.getElementById('___FCKHiddenDiv');if (!A){A=document.createElement('DIV');A.id='___FCKHiddenDiv';var B=A.style;B.position='absolute';B.visibility=B.overflow='hidden';B.width=B.height=1;document.body.appendChild(A);};A.innerHTML='';var C=document.body.createTextRange();C.moveToElementText(A);C.execCommand('Paste');var D=A.innerHTML;A.innerHTML='';return D;};FCK.AttachToOnSelectionChange=function(A){this.Events.AttachEvent('OnSelectionChange',A);};FCK.CreateLink=function(A){FCK.ExecuteNamedCommand('Unlink');if (A.length>0){var B='javascript:void(0);/*'+(new Date().getTime())+'*/';FCK.ExecuteNamedCommand('CreateLink',B);var C=this.EditorDocument.links;for (i=0;i0&&!isNaN(E)) this.PageConfig[D]=parseInt(E,10);else this.PageConfig[D]=E;}};function FCKConfig_LoadPageConfig(){var A=FCKConfig.PageConfig;for (var B in A) FCKConfig[B]=A[B];};function FCKConfig_PreProcess(){var A=FCKConfig;if (A.AllowQueryStringDebug){try{if ((/fckdebug=true/i).test(window.top.location.search)) A.Debug=true;}catch (e) {/*Ignore it. Much probably we are inside a FRAME where the "top" is in another domain (security error).*/}};if (!A.PluginsPath.EndsWith('/')) A.PluginsPath+='/';if (typeof(A.EditorAreaCSS)=='string') A.EditorAreaCSS=[A.EditorAreaCSS];var B=A.ToolbarComboPreviewCSS;if (!B||B.length==0) A.ToolbarComboPreviewCSS=A.EditorAreaCSS;else if (typeof(B)=='string') A.ToolbarComboPreviewCSS=[B];};FCKConfig.ToolbarSets={};FCKConfig.Plugins={};FCKConfig.Plugins.Items=[];FCKConfig.Plugins.Add=function(A,B,C){FCKConfig.Plugins.Items.AddItem([A,B,C]);};FCKConfig.ProtectedSource={};FCKConfig.ProtectedSource.RegexEntries=[//g,//gi,//gi];FCKConfig.ProtectedSource.Add=function(A){this.RegexEntries.AddItem(A);};FCKConfig.ProtectedSource.Protect=function(A){function _Replace(protectedSource){var B=FCKTempBin.AddElement(protectedSource);return '';};for (var i=0;i|>)/g,_Replace);} +var FCKDebug={};FCKDebug._GetWindow=function(){if (!this.DebugWindow||this.DebugWindow.closed) this.DebugWindow=window.open(FCKConfig.BasePath+'fckdebug.html','FCKeditorDebug','menubar=no,scrollbars=yes,resizable=yes,location=no,toolbar=no,width=600,height=500',true);return this.DebugWindow;};FCKDebug.Output=function(A,B,C){if (!FCKConfig.Debug) return;try{this._GetWindow().Output(A,B);}catch (e) {}};FCKDebug.OutputObject=function(A,B){if (!FCKConfig.Debug) return;try{this._GetWindow().OutputObject(A,B);}catch (e) {}} +var FCKDomTools={MoveChildren:function(A,B){if (A==B) return;var C;while ((C=A.firstChild)) B.appendChild(A.removeChild(C));},TrimNode:function(A,B){this.LTrimNode(A);this.RTrimNode(A,B);},LTrimNode:function(A){var B;while ((B=A.firstChild)){if (B.nodeType==3){var C=B.nodeValue.LTrim();var D=B.nodeValue.length;if (C.length==0){A.removeChild(B);continue;}else if (C.length0) break;if (A.lastChild) A=A.lastChild;else return this.GetPreviousSourceElement(A,B,C,D);};return null;},GetNextSourceElement:function(A,B,C,D){if (!A) return null;if (A.nextSibling) A=A.nextSibling;else return this.GetNextSourceElement(A.parentNode,B,C,D);while (A){if (A.nodeType==1){if (C&&A.nodeName.IEquals(C)) break;if (!D||!A.nodeName.IEquals(D)) return A;}else if (B&&A.nodeType==3&&A.nodeValue.RTrim().length>0) break;if (A.firstChild) A=A.firstChild;else return this.GetNextSourceElement(A,B,C,D);};return null;},InsertAfterNode:function(A,B){return A.parentNode.insertBefore(B,A.nextSibling);},GetParents:function(A){var B=[];while (A){B.splice(0,0,A);A=A.parentNode;};return B;},GetIndexOf:function(A){var B=A.parentNode?A.parentNode.firstChild:null;var C=-1;while (B){C++;if (B==A) return C;B=B.nextSibling;};return-1;}}; +var GECKO_BOGUS='
    ';var FCKTools={};FCKTools.CreateBogusBR=function(A){var B=A.createElement('br');B.setAttribute('type','_moz');return B;};FCKTools.AppendStyleSheet=function(A,B){if (typeof(B)=='string') return this._AppendStyleSheet(A,B);else{var C=[];for (var i=0;i/g,'>');return A;};FCKTools.AddSelectOption=function(A,B,C){var D=FCKTools.GetElementDocument(A).createElement("OPTION");D.text=B;D.value=C;A.options.add(D);return D;};FCKTools.RunFunction=function(A,B,C,D){if (A) this.SetTimeout(A,0,B,C,D);};FCKTools.SetTimeout=function(A,B,C,D,E){return (E||window).setTimeout(function(){if (D) A.apply(C,[].concat(D));else A.apply(C);},B);};FCKTools.SetInterval=function(A,B,C,D,E){return (E||window).setInterval(function(){A.apply(C,D||[]);},B);};FCKTools.ConvertStyleSizeToHtml=function(A){return A.EndsWith('%')?A:parseInt(A,10);};FCKTools.ConvertHtmlSizeToStyle=function(A){return A.EndsWith('%')?A:(A+'px');};FCKTools.GetElementAscensor=function(A,B){var e=A;var C=","+B.toUpperCase()+",";while (e){if (C.indexOf(","+e.nodeName.toUpperCase()+",")!=-1) return e;e=e.parentNode;};return null;};FCKTools.CreateEventListener=function(A,B){var f=function(){var C=[];for (var i=0;i0) B[B.length]=C;};return B;};FCKTools.RemoveOuterTags=function(e){e.insertAdjacentHTML('beforeBegin',e.innerHTML);e.parentNode.removeChild(e);};FCKTools.CreateXmlObject=function(A){var B;switch (A){case 'XmlHttp':B=['MSXML2.XmlHttp','Microsoft.XmlHttp'];break;case 'DOMDocument':B=['MSXML2.DOMDocument','Microsoft.XmlDom'];break;};for (var i=0;i<2;i++){try { return new ActiveXObject(B[i]);}catch (e){}};if (FCKLang.NoActiveX){alert(FCKLang.NoActiveX);FCKLang.NoActiveX=null;};return null;};FCKTools.DisableSelection=function(A){A.unselectable='on';var e,i=0;while ((e=A.all[i++])){switch (e.tagName){case 'IFRAME':case 'TEXTAREA':case 'INPUT':case 'SELECT':break;default:e.unselectable='on';}}};FCKTools.GetScrollPosition=function(A){var B=A.document;var C={ X:B.documentElement.scrollLeft,Y:B.documentElement.scrollTop };if (C.X>0||C.Y>0) return C;return { X:B.body.scrollLeft,Y:B.body.scrollTop };};FCKTools.AddEventListener=function(A,B,C){A.attachEvent('on'+B,C);};FCKTools.RemoveEventListener=function(A,B,C){A.detachEvent('on'+B,C);};FCKTools.AddEventListenerEx=function(A,B,C,D){var o={};o.Source=A;o.Params=D||[];o.Listener=function(ev){return C.apply(o.Source,[ev].concat(o.Params));};if (FCK.IECleanup) FCK.IECleanup.AddItem(null,function() { o.Source=null;o.Params=null;});A.attachEvent('on'+B,o.Listener);A=null;D=null;};FCKTools.GetViewPaneSize=function(A){var B;var C=A.document.documentElement;if (C&&C.clientWidth) B=C;else B=top.document.body;if (B) return { Width:B.clientWidth,Height:B.clientHeight };else return { Width:0,Height:0 };};FCKTools.SaveStyles=function(A){var B={};if (A.className.length>0){B.Class=A.className;A.className='';};var C=A.style.cssText;if (C.length>0){B.Inline=C;A.style.cssText='';};return B;};FCKTools.RestoreStyles=function(A,B){A.className=B.Class||'';A.style.cssText=B.Inline||'';};FCKTools.RegisterDollarFunction=function(A){A.$=A.document.getElementById;};FCKTools.AppendElement=function(A,B){return A.appendChild(this.GetElementDocument(A).createElement(B));};FCKTools.ToLowerCase=function(A){return A.toLowerCase();} +var FCKeditorAPI;function InitializeAPI(){var A=window.parent;if (!(FCKeditorAPI=A.FCKeditorAPI)){var B='var FCKeditorAPI = {Version : "2.4",VersionBuild : "1148",__Instances : new Object(),GetInstance : function( name ){return this.__Instances[ name ];},_FormSubmit : function(){for ( var name in FCKeditorAPI.__Instances ){var oEditor = FCKeditorAPI.__Instances[ name ] ;if ( oEditor.GetParentForm() == this )oEditor.UpdateLinkedField() ;}this._FCKOriginalSubmit() ;},_FunctionQueue : {Functions : new Array(),IsRunning : false,Add : function( f ){this.Functions.push( f );if ( !this.IsRunning )this.StartNext();},StartNext : function(){var aQueue = this.Functions ;if ( aQueue.length > 0 ){this.IsRunning = true;aQueue[0].call();}else this.IsRunning = false;},Remove : function( f ){var aQueue = this.Functions;var i = 0, fFunc;while( (fFunc = aQueue[ i ]) ){if ( fFunc == f )aQueue.splice( i,1 );i++ ;}this.StartNext();}}}';if (A.execScript) A.execScript(B,'JavaScript');else{if (FCKBrowserInfo.IsGecko10){eval.call(A,B);}else if (FCKBrowserInfo.IsSafari){var C=A.document;var D=C.createElement('script');D.appendChild(C.createTextNode(B));C.documentElement.appendChild(D);}else A.eval(B);};FCKeditorAPI=A.FCKeditorAPI;};FCKeditorAPI.__Instances[FCK.Name]=FCK;};function _AttachFormSubmitToAPI(){var A=FCK.GetParentForm();if (A){FCKTools.AddEventListener(A,'submit',FCK.UpdateLinkedField);if (!A._FCKOriginalSubmit&&(typeof(A.submit)=='function'||(!A.submit.tagName&&!A.submit.length))){A._FCKOriginalSubmit=A.submit;A.submit=FCKeditorAPI._FormSubmit;}}};function FCKeditorAPI_Cleanup(){delete FCKeditorAPI.__Instances[FCK.Name];};FCKTools.AddEventListener(window,'unload',FCKeditorAPI_Cleanup); +var FCKImagePreloader=function(){this._Images=[];};FCKImagePreloader.prototype={AddImages:function(A){if (typeof(A)=='string') A=A.split(';');this._Images=this._Images.concat(A);},Start:function(){var A=this._Images;this._PreloadCount=A.length;for (var i=0;i]*\>)([\s\S]*)(\<\/body\>[\s\S]*)/i,ToReplace:/___fcktoreplace:([\w]+)/ig,MetaHttpEquiv:/http-equiv\s*=\s*["']?([^"' ]+)/i,HasBaseTag:/]*>/i,HeadOpener:/]*>/i,HeadCloser:/<\/head\s*>/i,FCK_Class:/(\s*FCK__[A-Za-z]*\s*)/,ElementName:/(^[a-z_:][\w.\-:]*\w$)|(^[a-z_]$)/,ForceSimpleAmpersand:/___FCKAmp___/g,SpaceNoClose:/\/>/g,EmptyParagraph:/^<(p|div)>\s*<\/\1>$/i,TagBody:/>])/gi,StrongCloser:/<\/STRONG>/gi,EmOpener:/])/gi,EmCloser:/<\/EM>/gi,GeckoEntitiesMarker:/#\?-\:/g,ProtectUrlsImg:/(?:(]+))/gi,ProtectUrlsA:/(?:(]+))/gi,Html4DocType:/HTML 4\.0 Transitional/i,DocTypeTag:/]*>/i,TagsWithEvent:/<[^\>]+ on\w+[\s\r\n]*=[\s\r\n]*?('|")[\s\S]+?\>/g,EventAttributes:/\s(on\w+)[\s\r\n]*=[\s\r\n]*?('|")([\s\S]*?)\2/g,ProtectedEvents:/\s\w+_fckprotectedatt="([^"]+)"/g,StyleProperties:/\S+\s*:/g};var FCKListsLib={BlockElements:{ address:1,blockquote:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,noscript:1,ol:1,p:1,pre:1,script:1,table:1,ul:1 },NonEmptyBlockElements:{ p:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,address:1,pre:1,ol:1,ul:1,li:1,td:1,th:1 },PathBlockElements:{ address:1,blockquote:1,div:1,dl:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1,ol:1,ul:1,li:1,dt:1,de:1 },InlineChildReqElements:{ abbr:1,acronym:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,i:1,ins:1,label:1,kbd:1,q:1,samp:1,small:1,span:1,strong:1,sub:1,sup:1,tt:1,'var':1 },EmptyElements:{ base:1,meta:1,link:1,hr:1,br:1,param:1,img:1,area:1,input:1 }}; +var FCKLanguageManager=FCK.Language={AvailableLanguages:{af:'Afrikaans',ar:'Arabic',bg:'Bulgarian',bn:'Bengali/Bangla',bs:'Bosnian',ca:'Catalan',cs:'Czech',da:'Danish',de:'German',el:'Greek',en:'English','en-au':'English (Australia)','en-ca':'English (Canadian)','en-uk':'English (United Kingdom)',eo:'Esperanto',es:'Spanish',et:'Estonian',eu:'Basque',fa:'Persian',fi:'Finnish',fo:'Faroese',fr:'French',gl:'Galician',he:'Hebrew',hi:'Hindi',hr:'Croatian',hu:'Hungarian',it:'Italian',ja:'Japanese',km:'Khmer',ko:'Korean',lt:'Lithuanian',lv:'Latvian',mn:'Mongolian',ms:'Malay',nb:'Norwegian Bokmal',nl:'Dutch',no:'Norwegian',pl:'Polish',pt:'Portuguese (Portugal)','pt-br':'Portuguese (Brazil)',ro:'Romanian',ru:'Russian',sk:'Slovak',sl:'Slovenian',sr:'Serbian (Cyrillic)','sr-latn':'Serbian (Latin)',sv:'Swedish',th:'Thai',tr:'Turkish',uk:'Ukrainian',vi:'Vietnamese',zh:'Chinese Traditional','zh-cn':'Chinese Simplified'},GetActiveLanguage:function(){if (FCKConfig.AutoDetectLanguage){var A;if (navigator.userLanguage) A=navigator.userLanguage.toLowerCase();else if (navigator.language) A=navigator.language.toLowerCase();else{return FCKConfig.DefaultLanguage;};if (A.length>=5){A=A.substr(0,5);if (this.AvailableLanguages[A]) return A;};if (A.length>=2){A=A.substr(0,2);if (this.AvailableLanguages[A]) return A;}};return this.DefaultLanguage;},TranslateElements:function(A,B,C,D){var e=A.getElementsByTagName(B);var E,s;for (var i=0;i0) C+='|'+FCKConfig.AdditionalNumericEntities;FCKXHtmlEntities.EntitiesRegex=new RegExp(C,'g');} +var FCKXHtml={};FCKXHtml.CurrentJobNum=0;FCKXHtml.GetXHTML=function(A,B,C){FCKXHtmlEntities.Initialize();var D=FCK.IsDirty();this._CreateNode=FCKConfig.ForceStrongEm?FCKXHtml_CreateNode_StrongEm:FCKXHtml_CreateNode_Normal;FCKXHtml.SpecialBlocks=[];this.XML=FCKTools.CreateXmlObject('DOMDocument');this.MainNode=this.XML.appendChild(this.XML.createElement('xhtml'));FCKXHtml.CurrentJobNum++;if (B) this._AppendNode(this.MainNode,A);else this._AppendChildNodes(this.MainNode,A,false);var E=this._GetMainXmlString();this.XML=null;E=E.substr(7,E.length-15).Trim();if (FCKBrowserInfo.IsGecko) E=E.replace(/$/,'');E=E.replace(FCKRegexLib.SpaceNoClose,' />');if (FCKConfig.ForceSimpleAmpersand) E=E.replace(FCKRegexLib.ForceSimpleAmpersand,'&');if (C) E=FCKCodeFormatter.Format(E);for (var i=0;i0;if (C) A.appendChild(this.XML.createTextNode(B.replace(FCKXHtmlEntities.EntitiesRegex,FCKXHtml_GetEntity)));return C;};function FCKXHtml_GetEntity(A){var B=FCKXHtmlEntities.Entities[A]||('#'+A.charCodeAt(0));return '#?-:'+B+';';};FCKXHtml._RemoveAttribute=function(A,B,C){var D=A.attributes.getNamedItem(C);if (D&&B.test(D.nodeValue)){var E=D.nodeValue.replace(B,'');if (E.length==0) A.attributes.removeNamedItem(C);else D.nodeValue=E;}};FCKXHtml.TagProcessors={img:function(A,B){if (!A.attributes.getNamedItem('alt')) FCKXHtml._AppendAttribute(A,'alt','');var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'src',C);return A;},a:function(A,B){if (B.innerHTML.Trim().length==0&&!B.name) return false;var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'href',C);if (FCKBrowserInfo.IsIE){FCKXHtml._RemoveAttribute(A,FCKRegexLib.FCK_Class,'class');if (B.name) FCKXHtml._AppendAttribute(A,'name',B.name);};FCKXHtml._AppendChildNodes(A,B,false);return A;},script:function(A,B){if (!A.attributes.getNamedItem('type')) FCKXHtml._AppendAttribute(A,'type','text/javascript');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(B.text)));return A;},style:function(A,B){if (!A.attributes.getNamedItem('type')) FCKXHtml._AppendAttribute(A,'type','text/css');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(B.innerHTML)));return A;},title:function(A,B){A.appendChild(FCKXHtml.XML.createTextNode(FCK.EditorDocument.title));return A;},table:function(A,B){if (FCKBrowserInfo.IsIE) FCKXHtml._RemoveAttribute(A,FCKRegexLib.FCK_Class,'class');FCKXHtml._AppendChildNodes(A,B,false);return A;},ol:function(A,B,C){if (B.innerHTML.Trim().length==0) return false;var D=C.lastChild;if (D&&D.nodeType==3) D=D.previousSibling;if (D&&D.nodeName.toUpperCase()=='LI'){B._fckxhtmljob=null;FCKXHtml._AppendNode(D,B);return false;};FCKXHtml._AppendChildNodes(A,B);return A;},span:function(A,B){if (B.innerHTML.length==0) return false;FCKXHtml._AppendChildNodes(A,B,false);return A;}};FCKXHtml.TagProcessors.ul=FCKXHtml.TagProcessors.ol; +FCKXHtml._GetMainXmlString=function(){return this.MainNode.xml;};FCKXHtml._AppendAttributes=function(A,B,C,D){var E=B.attributes;for (var n=0;n0) FCKXHtml._AppendAttribute(A,'shape',D);};return A;};FCKXHtml.TagProcessors['label']=function(A,B){if (B.htmlFor.length>0) FCKXHtml._AppendAttribute(A,'for',B.htmlFor);FCKXHtml._AppendChildNodes(A,B);return A;};FCKXHtml.TagProcessors['form']=function(A,B){if (B.acceptCharset&&B.acceptCharset.length>0&&B.acceptCharset!='UNKNOWN') FCKXHtml._AppendAttribute(A,'accept-charset',B.acceptCharset);if (B.name) FCKXHtml._AppendAttribute(A,'name',B.name);FCKXHtml._AppendChildNodes(A,B);return A;};FCKXHtml.TagProcessors['textarea']=FCKXHtml.TagProcessors['select']=function(A,B){if (B.name) FCKXHtml._AppendAttribute(A,'name',B.name);FCKXHtml._AppendChildNodes(A,B);return A;};FCKXHtml.TagProcessors['div']=function(A,B){if (B.align.length>0) FCKXHtml._AppendAttribute(A,'align',B.align);FCKXHtml._AppendChildNodes(A,B,true);return A;} +var FCKCodeFormatter={};FCKCodeFormatter.Init=function(){var A=this.Regex={};A.BlocksOpener=/\<(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi;A.BlocksCloser=/\<\/(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi;A.NewLineTags=/\<(BR|HR)[^\>]*\>/gi;A.MainTags=/\<\/?(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR)[^\>]*\>/gi;A.LineSplitter=/\s*\n+\s*/g;A.IncreaseIndent=/^\<(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \/\>]/i;A.DecreaseIndent=/^\<\/(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \>]/i;A.FormatIndentatorRemove=new RegExp('^'+FCKConfig.FormatIndentator);A.ProtectedTags=/(]*>)([\s\S]*?)(<\/PRE>)/gi;};FCKCodeFormatter._ProtectData=function(A,B,C,D){return B+'___FCKpd___'+FCKCodeFormatter.ProtectedData.AddItem(C)+D;};FCKCodeFormatter.Format=function(A){if (!this.Regex) this.Init();FCKCodeFormatter.ProtectedData=[];var B=A.replace(this.Regex.ProtectedTags,FCKCodeFormatter._ProtectData);B=B.replace(this.Regex.BlocksOpener,'\n$&');B=B.replace(this.Regex.BlocksCloser,'$&\n');B=B.replace(this.Regex.NewLineTags,'$&\n');B=B.replace(this.Regex.MainTags,'\n$&\n');var C='';var D=B.split(this.Regex.LineSplitter);B='';for (var i=0;i=0&&A==FCKUndo.SavedData[FCKUndo.CurrentIndex][0]) return;if (FCKUndo.CurrentIndex+1>=FCKConfig.MaxUndoLevels) FCKUndo.SavedData.shift();else FCKUndo.CurrentIndex++;var B;if (FCK.EditorDocument.selection.type=='Text') B=FCK.EditorDocument.selection.createRange().getBookmark();FCKUndo.SavedData[FCKUndo.CurrentIndex]=[A,B];FCK.Events.FireEvent("OnSelectionChange");};FCKUndo.CheckUndoState=function(){return (FCKUndo.Typing||FCKUndo.CurrentIndex>0);};FCKUndo.CheckRedoState=function(){return (!FCKUndo.Typing&&FCKUndo.CurrentIndex<(FCKUndo.SavedData.length-1));};FCKUndo.Undo=function(){if (FCKUndo.CheckUndoState()){if (FCKUndo.CurrentIndex==(FCKUndo.SavedData.length-1)){FCKUndo.SaveUndoStep();};FCKUndo._ApplyUndoLevel(--FCKUndo.CurrentIndex);FCK.Events.FireEvent("OnSelectionChange");}};FCKUndo.Redo=function(){if (FCKUndo.CheckRedoState()){FCKUndo._ApplyUndoLevel(++FCKUndo.CurrentIndex);FCK.Events.FireEvent("OnSelectionChange");}};FCKUndo._ApplyUndoLevel=function(A){var B=FCKUndo.SavedData[A];if (!B) return;FCK.SetInnerHtml(B[0]);if (B[1]){var C=FCK.EditorDocument.selection.createRange();C.moveToBookmark(B[1]);C.select();};FCKUndo.TypesCount=0;FCKUndo.Typing=false;} +var FCKEditingArea=function(A){this.TargetElement=A;this.Mode=0;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKEditingArea_Cleanup);};FCKEditingArea.prototype.Start=function(A,B){var C=this.TargetElement;var D=FCKTools.GetElementDocument(C);while(C.childNodes.length>0) C.removeChild(C.childNodes[0]);if (this.Mode==0){var E=this.IFrame=D.createElement('iframe');E.src='javascript:void(0)';E.frameBorder=0;E.width=E.height='100%';C.appendChild(E);if (FCKBrowserInfo.IsIE) A=A.replace(/(]*?)\s*\/?>(?!\s*<\/base>)/gi,'$1>');else if (!B){if (FCKBrowserInfo.IsGecko) A=A.replace(/(]*>)\s*(<\/body>)/i,'$1'+GECKO_BOGUS+'$2');var F=A.match(FCKRegexLib.BodyContents);if (F){A=F[1]+' '+F[3];this._BodyHTML=F[2];}else this._BodyHTML=A;};this.Window=E.contentWindow;var G=this.Document=this.Window.document;G.open();G.write(A);G.close();if (FCKBrowserInfo.IsGecko10&&!B){this.Start(A,true);return;};this.Window._FCKEditingArea=this;if (FCKBrowserInfo.IsGecko10) this.Window.setTimeout(FCKEditingArea_CompleteStart,500);else FCKEditingArea_CompleteStart.call(this.Window);}else{var H=this.Textarea=D.createElement('textarea');H.className='SourceField';H.dir='ltr';H.style.width=H.style.height='100%';H.style.border='none';C.appendChild(H);H.value=A;FCKTools.RunFunction(this.OnLoad);}};function FCKEditingArea_CompleteStart(){if (!this.document.body){this.setTimeout(FCKEditingArea_CompleteStart,50);return;};var A=this._FCKEditingArea;A.MakeEditable();FCKTools.RunFunction(A.OnLoad);};FCKEditingArea.prototype.MakeEditable=function(){var A=this.Document;if (FCKBrowserInfo.IsIE){A.body.contentEditable=true;}else{try{A.body.spellcheck=(this.FFSpellChecker!==false);if (this._BodyHTML){A.body.innerHTML=this._BodyHTML;this._BodyHTML=null;};A.designMode='on';try{A.execCommand('styleWithCSS',false,FCKConfig.GeckoUseSPAN);}catch (e){A.execCommand('useCSS',false,!FCKConfig.GeckoUseSPAN);};A.execCommand('enableObjectResizing',false,!FCKConfig.DisableObjectResizing);A.execCommand('enableInlineTableEditing',false,!FCKConfig.DisableFFTableHandles);}catch (e) {}}};FCKEditingArea.prototype.Focus=function(){try{if (this.Mode==0){if (FCKBrowserInfo.IsIE&&this.Document.hasFocus()) return;if (FCKBrowserInfo.IsSafari) this.IFrame.focus();else{this.Window.focus();}}else{var A=FCKTools.GetElementDocument(this.Textarea);if ((!A.hasFocus||A.hasFocus())&&A.activeElement==this.Textarea) return;this.Textarea.focus();}}catch(e) {}};function FCKEditingArea_Cleanup(){this.TargetElement=null;this.IFrame=null;this.Document=null;this.Textarea=null;if (this.Window){this.Window._FCKEditingArea=null;this.Window=null;}} +var FCKKeystrokeHandler=function(A){this.Keystrokes={};this.CancelCtrlDefaults=(A!==false);};FCKKeystrokeHandler.prototype.AttachToElement=function(A){FCKTools.AddEventListenerEx(A,'keydown',_FCKKeystrokeHandler_OnKeyDown,this);if (FCKBrowserInfo.IsGecko10||FCKBrowserInfo.IsOpera||(FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsMac)) FCKTools.AddEventListenerEx(A,'keypress',_FCKKeystrokeHandler_OnKeyPress,this);};FCKKeystrokeHandler.prototype.SetKeystrokes=function(){for (var i=0;i40))){B._CancelIt=true;if (A.preventDefault) return A.preventDefault();A.returnValue=false;A.cancelBubble=true;return false;};return true;};function _FCKKeystrokeHandler_OnKeyPress(A,B){if (B._CancelIt){if (A.preventDefault) return A.preventDefault();return false;};return true;} +var FCKListHandler={OutdentListItem:function(A){var B=A.parentNode;if (B.tagName.toUpperCase().Equals('UL','OL')){var C=FCKTools.GetElementDocument(A);var D=new FCKDocumentFragment(C);var E=D.RootNode;var F=false;var G=FCKDomTools.GetFirstChild(A,['UL','OL']);if (G){F=true;var H;while ((H=G.firstChild)) E.appendChild(G.removeChild(H));FCKDomTools.RemoveNode(G);};var I;var J=false;while ((I=A.nextSibling)){if (!F&&I.nodeType==1&&I.nodeName.toUpperCase()=='LI') J=F=true;E.appendChild(I.parentNode.removeChild(I));if (!J&&I.nodeType==1&&I.nodeName.toUpperCase().Equals('UL','OL')) FCKDomTools.RemoveNode(I,true);};var K=B.parentNode.tagName.toUpperCase();var L=(K=='LI');if (L||K.Equals('UL','OL')){if (F){var G=B.cloneNode(false);D.AppendTo(G);A.appendChild(G);}else if (L) D.InsertAfterNode(B.parentNode);else D.InsertAfterNode(B);if (L) FCKDomTools.InsertAfterNode(B.parentNode,B.removeChild(A));else FCKDomTools.InsertAfterNode(B,B.removeChild(A));}else{if (F){var N=B.cloneNode(false);D.AppendTo(N);FCKDomTools.InsertAfterNode(B,N);};var O=C.createElement('p');FCKDomTools.MoveChildren(B.removeChild(A),O);FCKDomTools.InsertAfterNode(B,O);A=O;};if (this.CheckEmptyList(B)) FCKDomTools.RemoveNode(B,true);};return A;},CheckEmptyList:function(A){return (FCKDomTools.GetFirstChild(A,'LI')==null);},CheckListHasContents:function(A){var B=A.firstChild;while (B){switch (B.nodeType){case 1:if (!B.nodeName.IEquals('UL','LI')) return true;break;case 3:if (B.nodeValue.Trim().length>0) return true;};B=B.nextSibling;};return false;}}; +var FCKElementPath=function(A){var B=null;var C=null;var D=[];var e=A;while (e){if (e.nodeType==1){if (!this.LastElement) this.LastElement=e;var E=e.nodeName.toLowerCase();if (!C&&!B&&FCKListsLib.PathBlockElements[E]!=null) B=e;if (!C&&(/^(?:body|td|th|caption|form)$/).test(E)) C=e;D.push(e);if (E=='BODY') break;};e=e.parentNode;};this.Block=B;this.BlockLimit=C;this.Elements=D;}; +var FCKDomRange=function(A){this.Window=A;};FCKDomRange.prototype={_UpdateElementInfo:function(){if (!this._Range) this.Release(true);else{var A=this._Range.startContainer;var B=this._Range.endContainer;var C=new FCKElementPath(A);this.StartContainer=C.LastElement;this.StartBlock=C.Block;this.StartBlockLimit=C.BlockLimit;if (A!=B) C=new FCKElementPath(B);this.EndContainer=C.LastElement;this.EndBlock=C.Block;this.EndBlockLimit=C.BlockLimit;}},CreateRange:function(){return new FCKW3CRange(this.Window.document);},DeleteContents:function(){if (this._Range){this._Range.deleteContents();this._UpdateElementInfo();}},ExtractContents:function(){if (this._Range){var A=this._Range.extractContents();this._UpdateElementInfo();return A;}},CheckIsCollapsed:function(){if (this._Range) return this._Range.collapsed;},Collapse:function(A){if (this._Range) this._Range.collapse(A);this._UpdateElementInfo();},Clone:function(){var A=FCKTools.CloneObject(this);if (this._Range) A._Range=this._Range.cloneRange();return A;},MoveToNodeContents:function(A){if (!this._Range) this._Range=this.CreateRange();this._Range.selectNodeContents(A);this._UpdateElementInfo();},MoveToElementStart:function(A){this.SetStart(A,1);this.SetEnd(A,1);},InsertNode:function(A){if (this._Range) this._Range.insertNode(A);},CheckIsEmpty:function(A){if (this.CheckIsCollapsed()) return true;var B=this.Window.document.createElement('div');this._Range.cloneContents().AppendTo(B);FCKDomTools.TrimNode(B,A);return (B.innerHTML.length==0);},CheckStartOfBlock:function(){var A=this.Clone();A.Collapse(true);A.SetStart(A.StartBlock||A.StartBlockLimit,1);var B=A.CheckIsEmpty();A.Release();return B;},CheckEndOfBlock:function(A){var B=this.Clone();B.Collapse(false);B.SetEnd(B.EndBlock||B.EndBlockLimit,2);var C=B.CheckIsEmpty(true);B.Release();if (A) this.Select();return C;},CreateBookmark:function(){var A={StartId:'fck_dom_range_start_'+(new Date()).valueOf()+'_'+Math.floor(Math.random()*1000),EndId:'fck_dom_range_end_'+(new Date()).valueOf()+'_'+Math.floor(Math.random()*1000)};var B=this.Window.document;var C;var D;if (!this.CheckIsCollapsed()){C=B.createElement('span');C.id=A.EndId;C.innerHTML=' ';D=this.Clone();D.Collapse(false);D.InsertNode(C);};C=B.createElement('span');C.id=A.StartId;C.innerHTML=' ';D=this.Clone();D.Collapse(true);D.InsertNode(C);return A;},MoveToBookmark:function(A,B){var C=this.Window.document;var D=C.getElementById(A.StartId);var E=C.getElementById(A.EndId);this.SetStart(D,3);if (!B) FCKDomTools.RemoveNode(D);if (E){this.SetEnd(E,3);if (!B) FCKDomTools.RemoveNode(E);}else this.Collapse(true);},SetStart:function(A,B){var C=this._Range;if (!C) C=this._Range=this.CreateRange();switch(B){case 1:C.setStart(A,0);break;case 2:C.setStart(A,A.childNodes.length);break;case 3:C.setStartBefore(A);break;case 4:C.setStartAfter(A);};this._UpdateElementInfo();},SetEnd:function(A,B){var C=this._Range;if (!C) C=this._Range=this.CreateRange();switch(B){case 1:C.setEnd(A,0);break;case 2:C.setEnd(A,A.childNodes.length);break;case 3:C.setEndBefore(A);break;case 4:C.setEndAfter(A);};this._UpdateElementInfo();},Expand:function(A){var B,oSibling;switch (A){case 'block_contents':if (this.StartBlock) this.SetStart(this.StartBlock,1);else{B=this._Range.startContainer;if (B.nodeType==1){if (!(B=B.childNodes[this._Range.startOffset])) B=B.firstChild;};if (!B) return;while (true){oSibling=B.previousSibling;if (!oSibling){if (B.parentNode!=this.StartBlockLimit) B=B.parentNode;else break;}else if (oSibling.nodeType!=1||!(/^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/).test(oSibling.nodeName.toUpperCase())){B=oSibling;}else break;};this._Range.setStartBefore(B);};if (this.EndBlock) this.SetEnd(this.EndBlock,2);else{B=this._Range.endContainer;if (B.nodeType==1) B=B.childNodes[this._Range.endOffset]||B.lastChild;if (!B) return;while (true){oSibling=B.nextSibling;if (!oSibling){if (B.parentNode!=this.EndBlockLimit) B=B.parentNode;else break;}else if (oSibling.nodeType!=1||!(/^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/).test(oSibling.nodeName.toUpperCase())){B=oSibling;}else break;};this._Range.setEndAfter(B);};this._UpdateElementInfo();}},Release:function(A){if (!A) this.Window=null;this.StartContainer=null;this.StartBlock=null;this.StartBlockLimit=null;this.EndContainer=null;this.EndBlock=null;this.EndBlockLimit=null;this._Range=null;}}; +FCKDomRange.prototype.MoveToSelection=function(){this.Release(true);this._Range=new FCKW3CRange(this.Window.document);var A=this.Window.document.selection;if (A.type!='Control'){B=this._GetSelectionMarkerTag(true);this._Range.setStart(B.parentNode,FCKDomTools.GetIndexOf(B));B.parentNode.removeChild(B);var B=this._GetSelectionMarkerTag(false);this._Range.setEnd(B.parentNode,FCKDomTools.GetIndexOf(B));B.parentNode.removeChild(B);this._UpdateElementInfo();}else{var C=A.createRange().item(0);if (C){this._Range.setStartBefore(C);this._Range.setEndAfter(C);this._UpdateElementInfo();}}};FCKDomRange.prototype.Select=function(){if (this._Range){var A=this.CheckIsCollapsed();var B=this._GetRangeMarkerTag(true);if (!A) var C=this._GetRangeMarkerTag(false);var D=this.Window.document.body.createTextRange();D.moveToElementText(B);D.moveStart('character',1);if (!A){var E=this.Window.document.body.createTextRange();E.moveToElementText(C);D.setEndPoint('EndToEnd',E);D.moveEnd('character',-1);};this._Range.setStartBefore(B);B.parentNode.removeChild(B);if (A){try{D.pasteHTML(' ');D.moveStart('character',-1);}catch (e){};D.select();D.pasteHTML('');}else{this._Range.setEndBefore(C);C.parentNode.removeChild(C);D.select();}}};FCKDomRange.prototype._GetSelectionMarkerTag=function(A){var B=this.Window.document.selection.createRange();B.collapse(A===true);var C='fck_dom_range_temp_'+(new Date()).valueOf()+'_'+Math.floor(Math.random()*1000);B.pasteHTML('');return this.Window.document.getElementById(C);};FCKDomRange.prototype._GetRangeMarkerTag=function(A){var B=this._Range;if (!A){B=B.cloneRange();B.collapse(A===true);};var C=this.Window.document.createElement('span');C.innerHTML=' ';B.insertNode(C);return C;} +var FCKDocumentFragment=function(A){this._Document=A;this.RootNode=A.createElement('div');};FCKDocumentFragment.prototype={AppendTo:function(A){FCKDomTools.MoveChildren(this.RootNode,A);},AppendHtml:function(A){var B=this._Document.createElement('div');B.innerHTML=A;FCKDomTools.MoveChildren(B,this.RootNode);},InsertAfterNode:function(A){var B=this.RootNode;var C;while((C=B.lastChild)) FCKDomTools.InsertAfterNode(A,B.removeChild(C));}}; +var FCKW3CRange=function(A){this._Document=A;this.startContainer=null;this.startOffset=null;this.endContainer=null;this.endOffset=null;this.collapsed=true;};FCKW3CRange.CreateRange=function(A){return new FCKW3CRange(A);};FCKW3CRange.CreateFromRange=function(A,B){var C=FCKW3CRange.CreateRange(A);C.setStart(B.startContainer,B.startOffset);C.setEnd(B.endContainer,B.endOffset);return C;};FCKW3CRange.prototype={_UpdateCollapsed:function(){this.collapsed=(this.startContainer==this.endContainer&&this.startOffset==this.endOffset);},setStart:function(A,B){this.startContainer=A;this.startOffset=B;if (!this.endContainer){this.endContainer=A;this.endOffset=B;};this._UpdateCollapsed();},setEnd:function(A,B){this.endContainer=A;this.endOffset=B;if (!this.startContainer){this.startContainer=A;this.startOffset=B;};this._UpdateCollapsed();},setStartAfter:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setStartBefore:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A));},setEndAfter:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setEndBefore:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A));},collapse:function(A){if (A){this.endContainer=this.startContainer;this.endOffset=this.startOffset;}else{this.startContainer=this.endContainer;this.startOffset=this.endOffset;};this.collapsed=true;},selectNodeContents:function(A){this.setStart(A,0);this.setEnd(A,A.nodeType==3?A.data.length:A.childNodes.length);},insertNode:function(A){var B=this.startContainer;var C=this.startOffset;if (B.nodeType==3){B.splitText(C);if (B==this.endContainer) this.setEnd(B.nextSibling,this.endOffset-this.startOffset);FCKDomTools.InsertAfterNode(B,A);return;}else{B.insertBefore(A,B.childNodes[C]||null);if (B==this.endContainer){this.endOffset++;this.collapsed=false;}}},deleteContents:function(){if (this.collapsed) return;this._ExecContentsAction(0);},extractContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(1,A);return A;},cloneContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(2,A);return A;},_ExecContentsAction:function(A,B){var C=this.startContainer;var D=this.endContainer;var E=this.startOffset;var F=this.endOffset;var G=false;var H=false;if (D.nodeType==3) D=D.splitText(F);else{if (D.childNodes.length>0){if (F>D.childNodes.length-1){D=FCKDomTools.InsertAfterNode(D.lastChild,this._Document.createTextNode(''));H=true;}else D=D.childNodes[F];}};if (C.nodeType==3){C.splitText(E);if (C==D) D=C.nextSibling;}else{if (C.childNodes.length>0&&E<=C.childNodes.length-1){if (E==0){C=C.insertBefore(this._Document.createTextNode(''),C.firstChild);G=true;}else C=C.childNodes[E].previousSibling;}};var I=FCKDomTools.GetParents(C);var J=FCKDomTools.GetParents(D);var i,topStart,topEnd;for (i=0;i0&&levelStartNode!=D) levelClone=K.appendChild(levelStartNode.cloneNode(levelStartNode==D));if (!I[k]||levelStartNode.parentNode!=I[k].parentNode){currentNode=levelStartNode.previousSibling;while(currentNode){if (currentNode==I[k]||currentNode==C) break;currentSibling=currentNode.previousSibling;if (A==2) K.insertBefore(currentNode.cloneNode(true),K.firstChild);else{currentNode.parentNode.removeChild(currentNode);if (A==1) K.insertBefore(currentNode,K.firstChild);};currentNode=currentSibling;}};if (K) K=levelClone;};if (A==2){var L=this.startContainer;if (L.nodeType==3){L.data+=L.nextSibling.data;L.parentNode.removeChild(L.nextSibling);};var M=this.endContainer;if (M.nodeType==3&&M.nextSibling){M.data+=M.nextSibling.data;M.parentNode.removeChild(M.nextSibling);}}else{if (topStart&&topEnd&&(C.parentNode!=topStart.parentNode||D.parentNode!=topEnd.parentNode)) this.setStart(topEnd.parentNode,FCKDomTools.GetIndexOf(topEnd));this.collapse(true);};if(G) C.parentNode.removeChild(C);if(H&&D.parentNode) D.parentNode.removeChild(D);},cloneRange:function(){return FCKW3CRange.CreateFromRange(this._Document,this);},toString:function(){var A=this.cloneContents();var B=this._Document.createElement('div');A.AppendTo(B);return B.textContent||B.innerText;}}; +var FCKEnterKey=function(A,B,C){this.Window=A;this.EnterMode=B||'p';this.ShiftEnterMode=C||'br';var D=new FCKKeystrokeHandler(false);D._EnterKey=this;D.OnKeystroke=FCKEnterKey_OnKeystroke;D.SetKeystrokes([[13,'Enter'],[SHIFT+13,'ShiftEnter'],[8,'Backspace'],[46,'Delete']]);D.AttachToElement(A.document);};function FCKEnterKey_OnKeystroke(A,B){var C=this._EnterKey;try{switch (B){case 'Enter':return C.DoEnter();break;case 'ShiftEnter':return C.DoShiftEnter();break;case 'Backspace':return C.DoBackspace();break;case 'Delete':return C.DoDelete();}}catch (e){};return false;};FCKEnterKey.prototype.DoEnter=function(A,B){this._HasShift=(B===true);var C=A||this.EnterMode;if (C=='br') return this._ExecuteEnterBr();else return this._ExecuteEnterBlock(C);};FCKEnterKey.prototype.DoShiftEnter=function(){return this.DoEnter(this.ShiftEnterMode,true);};FCKEnterKey.prototype.DoBackspace=function(){var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (!B.CheckIsCollapsed()) return false;var C=B.StartBlock;var D=B.EndBlock;if (B.StartBlockLimit==B.EndBlockLimit&&C&&D){if (!B.CheckIsCollapsed()){var E=B.CheckEndOfBlock();B.DeleteContents();if (C!=D){B.SetStart(D,1);B.SetEnd(D,1);};B.Select();A=(C==D);};if (B.CheckStartOfBlock()){var F=B.StartBlock;var G=FCKDomTools.GetPreviousSourceElement(F,true,['BODY',B.StartBlockLimit.nodeName],['UL','OL']);A=this._ExecuteBackspace(B,G,F);}else if (FCKBrowserInfo.IsGecko){B.Select();}};B.Release();return A;};FCKEnterKey.prototype._ExecuteBackspace=function(A,B,C){var D=false;if (!B&&C.nodeName.IEquals('LI')&&C.parentNode.parentNode.nodeName.IEquals('LI')){B=C.parentNode.parentNode;C=FCKListHandler.OutdentListItem(C);};if (B&&B.nodeName.IEquals('LI')){var E=FCKDomTools.GetLastChild(B,['UL','OL']);while (E){B=FCKDomTools.GetLastChild(E,'LI');E=FCKDomTools.GetLastChild(B,['UL','OL']);}};if (B&&C){if (C.nodeName.IEquals('LI')&&!B.nodeName.IEquals('LI')) C=FCKListHandler.OutdentListItem(C);var F=C.parentNode;if (B.nodeName.IEquals('TABLE','HR')){FCKDomTools.RemoveNode(B);D=true;}else{FCKDomTools.RemoveNode(C);while (F.innerHTML.Trim().length==0){var G=F.parentNode;G.removeChild(F);F=G;};FCKDomTools.TrimNode(C);FCKDomTools.TrimNode(B);A.SetStart(B,2);A.Collapse(true);var H=A.CreateBookmark();FCKDomTools.MoveChildren(C,B);A.MoveToBookmark(H);A.Select();D=true;}};return D;};FCKEnterKey.prototype.DoDelete=function(){var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (B.CheckIsCollapsed()&&B.CheckEndOfBlock(FCKBrowserInfo.IsGecko)){var C=B.StartBlock;var D=FCKDomTools.GetNextSourceElement(C,true,[B.StartBlockLimit.nodeName],['UL','OL']);A=this._ExecuteBackspace(B,C,D);};B.Release();return A;};FCKEnterKey.prototype._ExecuteEnterBlock=function(A){var B=new FCKDomRange(this.Window);B.MoveToSelection();if (B.StartBlockLimit==B.EndBlockLimit){if (!B.StartBlock) this._FixBlock(B,true,A);if (!B.EndBlock) this._FixBlock(B,false,A);var C=B.StartBlock;var D=B.EndBlock;if (!B.CheckIsEmpty()) B.DeleteContents();if (C==D){var E;var F=B.CheckStartOfBlock();var G=B.CheckEndOfBlock();if (F&&!G){E=C.cloneNode(false);if (FCKBrowserInfo.IsGeckoLike) E.innerHTML=GECKO_BOGUS;C.parentNode.insertBefore(E,C);if (FCKBrowserInfo.IsIE){B.MoveToNodeContents(E);B.Select();};B.MoveToElementStart(C);}else{if (G){var H=C.tagName.toUpperCase();if (F&&H=='LI'){var I=FCKListHandler.OutdentListItem(C);B.MoveToElementStart(I);}else{if ((/^H[1-6]$/).test(H)) E=this.Window.document.createElement(A);else E=C.cloneNode(false);if (FCKBrowserInfo.IsGeckoLike){E.innerHTML=GECKO_BOGUS;if (F) C.innerHTML=GECKO_BOGUS;}}}else{B.SetEnd(C,2);var J=B.ExtractContents();E=C.cloneNode(false);FCKDomTools.TrimNode(J.RootNode);if (J.RootNode.firstChild.nodeType==1&&J.RootNode.firstChild.tagName.toUpperCase().Equals('UL','OL')) E.innerHTML=GECKO_BOGUS;J.AppendTo(E);if (FCKBrowserInfo.IsGecko){var K=FCKDomTools.GetLastChild(E);if (!K||K.nodeName.toLowerCase()!='br'||K.getAttribute('type',2)!='_moz') E.appendChild(FCKTools.CreateBogusBR(this.Window.document));}};if (E){FCKDomTools.InsertAfterNode(C,E);B.MoveToElementStart(E);if (FCKBrowserInfo.IsGecko) E.scrollIntoView(false);}}}else{B.MoveToElementStart(D);};B.Select();};B.Release();return true;};FCKEnterKey.prototype._ExecuteEnterBr=function(A){var B=new FCKDomRange(this.Window);B.MoveToSelection();if (B.StartBlockLimit==B.EndBlockLimit){B.DeleteContents();B.MoveToSelection();var C=B.CheckStartOfBlock();var D=B.CheckEndOfBlock();var E=B.StartBlock?B.StartBlock.tagName.toUpperCase():'';var F=this._HasShift;if (!F&&E=='LI') return this._ExecuteEnterBlock(null);if (!F&&D&&(/^H[1-6]$/).test(E)){FCKDebug.Output('BR - Header');FCKDomTools.InsertAfterNode(B.StartBlock,this.Window.document.createElement('br'));if (FCKBrowserInfo.IsGecko) FCKDomTools.InsertAfterNode(B.StartBlock,this.Window.document.createTextNode(''));B.SetStart(B.StartBlock.nextSibling,FCKBrowserInfo.IsIE?3:1);}else{FCKDebug.Output('BR - No Header');var G=this.Window.document.createElement('br');B.InsertNode(G);if (FCKBrowserInfo.IsGecko) FCKDomTools.InsertAfterNode(G,this.Window.document.createTextNode(''));if (D&&FCKBrowserInfo.IsGecko){var H=FCKDomTools.GetLastChild(G.parentNode,'BR');if (H&&H.getAttribute('type',2)!='_moz') G.parentNode.appendChild(FCKTools.CreateBogusBR(this.Window.document));};if (FCKBrowserInfo.IsIE) B.SetStart(G,4);else B.SetStart(G.nextSibling,1);};B.Collapse(true);B.Select();};B.Release();return true;};FCKEnterKey.prototype._FixBlock=function(A,B,C){var D=A.CreateBookmark();A.Collapse(B);A.Expand('block_contents');var E=this.Window.document.createElement(C);A.ExtractContents().AppendTo(E);FCKDomTools.TrimNode(E);A.InsertNode(E);A.MoveToBookmark(D);} +var FCKDocumentProcessor={};FCKDocumentProcessor._Items=[];FCKDocumentProcessor.AppendNew=function(){var A={};this._Items.AddItem(A);return A;};FCKDocumentProcessor.Process=function(A){var B,i=0;while((B=this._Items[i++])) B.ProcessDocument(A);};var FCKDocumentProcessor_CreateFakeImage=function(A,B){var C=FCK.EditorDocument.createElement('IMG');C.className=A;C.src=FCKConfig.FullBasePath+'images/spacer.gif';C.setAttribute('_fckfakelement','true',0);C.setAttribute('_fckrealelement',FCKTempBin.AddElement(B),0);return C;};if (FCKBrowserInfo.IsIE||FCKBrowserInfo.IsOpera){var FCKAnchorsProcessor=FCKDocumentProcessor.AppendNew();FCKAnchorsProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('A');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.name.length>0){if (C.innerHTML!=''){if (FCKBrowserInfo.IsIE) C.className+=' FCK__AnchorC';}else{var D=FCKDocumentProcessor_CreateFakeImage('FCK__Anchor',C.cloneNode(true));D.setAttribute('_fckanchor','true',0);C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}}}};var FCKPageBreaksProcessor=FCKDocumentProcessor.AppendNew();FCKPageBreaksProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('DIV');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.style.pageBreakAfter=='always'&&C.childNodes.length==1&&C.childNodes[0].style&&C.childNodes[0].style.display=='none'){var D=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',C.cloneNode(true));C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}};var FCKFlashProcessor=FCKDocumentProcessor.AppendNew();FCKFlashProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('EMBED');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.src.EndsWith('.swf',true)){var D=C.cloneNode(true);if (FCKBrowserInfo.IsIE){var E=['scale','play','loop','menu','wmode','quality'];for (var F=0;i0) A.style.width=FCKTools.ConvertHtmlSizeToStyle(B.width);if (B.height>0) A.style.height=FCKTools.ConvertHtmlSizeToStyle(B.height);};FCK.GetRealElement=function(A){var e=FCKTempBin.Elements[A.getAttribute('_fckrealelement')];if (A.getAttribute('_fckflash')){if (A.style.width.length>0) e.width=FCKTools.ConvertStyleSizeToHtml(A.style.width);if (A.style.height.length>0) e.height=FCKTools.ConvertStyleSizeToHtml(A.style.height);};return e;}; +var FCKSelection=FCK.Selection={}; +FCKSelection.GetType=function(){return FCK.EditorDocument.selection.type;};FCKSelection.GetSelectedElement=function(){if (this.GetType()=='Control'){var A=FCK.EditorDocument.selection.createRange();if (A&&A.item) return FCK.EditorDocument.selection.createRange().item(0);}};FCKSelection.GetParentElement=function(){switch (this.GetType()){case 'Control':return FCKSelection.GetSelectedElement().parentElement;case 'None':return null;default:return FCK.EditorDocument.selection.createRange().parentElement();}};FCKSelection.SelectNode=function(A){FCK.Focus();FCK.EditorDocument.selection.empty();var B;try{B=FCK.EditorDocument.body.createControlRange();B.addElement(A);}catch(e){B=FCK.EditorDocument.selection.createRange();B.moveToElementText(A);};B.select();};FCKSelection.Collapse=function(A){FCK.Focus();if (this.GetType()=='Text'){var B=FCK.EditorDocument.selection.createRange();B.collapse(A==null||A===true);B.select();}};FCKSelection.HasAncestorNode=function(A){var B;if (FCK.EditorDocument.selection.type=="Control"){B=this.GetSelectedElement();}else{var C=FCK.EditorDocument.selection.createRange();B=C.parentElement();};while (B){if (B.tagName==A) return true;B=B.parentNode;};return false;};FCKSelection.MoveToAncestorNode=function(A){var B,oRange;if (!FCK.EditorDocument) return null;if (FCK.EditorDocument.selection.type=="Control"){oRange=FCK.EditorDocument.selection.createRange();for (i=0;i=0;i--){var D=B.rows[i];if (C==0&&D.cells.length==1){FCKTableHandler.DeleteRows(D);continue;};if (D.cells[C]) D.removeChild(D.cells[C]);}};FCKTableHandler.InsertCell=function(A){var B=A?A:FCKSelection.MoveToAncestorNode('TD');if (!B) return null;var C=FCK.EditorDocument.createElement('TD');if (FCKBrowserInfo.IsGecko) C.innerHTML=GECKO_BOGUS;if (B.cellIndex==B.parentNode.cells.length-1){B.parentNode.appendChild(C);}else{B.parentNode.insertBefore(C,B.nextSibling);};return C;};FCKTableHandler.DeleteCell=function(A){if (A.parentNode.cells.length==1){FCKTableHandler.DeleteRows(FCKTools.GetElementAscensor(A,'TR'));return;};A.parentNode.removeChild(A);};FCKTableHandler.DeleteCells=function(){var A=FCKTableHandler.GetSelectedCells();for (var i=A.length-1;i>=0;i--){FCKTableHandler.DeleteCell(A[i]);}};FCKTableHandler.MergeCells=function(){var A=FCKTableHandler.GetSelectedCells();if (A.length<2) return;if (A[0].parentNode!=A[A.length-1].parentNode) return;var B=isNaN(A[0].colSpan)?1:A[0].colSpan;var C='';var D=FCK.EditorDocument.createDocumentFragment();for (var i=A.length-1;i>=0;i--){var E=A[i];for (var c=E.childNodes.length-1;c>=0;c--){var F=E.removeChild(E.childNodes[c]);if ((F.hasAttribute&&F.hasAttribute('_moz_editor_bogus_node'))||(F.getAttribute&&F.getAttribute('type',2)=='_moz')) continue;D.insertBefore(F,D.firstChild);};if (i>0){B+=isNaN(E.colSpan)?1:E.colSpan;FCKTableHandler.DeleteCell(E);}};A[0].colSpan=B;if (FCKBrowserInfo.IsGecko&&D.childNodes.length==0) A[0].innerHTML=GECKO_BOGUS;else A[0].appendChild(D);};FCKTableHandler.SplitCell=function(){var A=FCKTableHandler.GetSelectedCells();if (A.length!=1) return;var B=this._CreateTableMap(A[0].parentNode.parentNode);var C=FCKTableHandler._GetCellIndexSpan(B,A[0].parentNode.rowIndex,A[0]);var D=this._GetCollumnCells(B,C);for (var i=0;i1) E.rowSpan=A[0].rowSpan;}else{if (isNaN(D[i].colSpan)) D[i].colSpan=2;else D[i].colSpan+=1;}}};FCKTableHandler._GetCellIndexSpan=function(A,B,C){if (A.length=0&&B.compareEndPoints('StartToEnd',D)<=0)||(B.compareEndPoints('EndToStart',D)>=0&&B.compareEndPoints('EndToEnd',D)<=0)){A[A.length]=C.cells[i];}}}};return A;}; +var FCKXml=function(){this.Error=false;};FCKXml.prototype.LoadUrl=function(A){this.Error=false;var B=FCKTools.CreateXmlObject('XmlHttp');if (!B){this.Error=true;return;};B.open("GET",A,false);B.send(null);if (B.status==200||B.status==304) this.DOMDocument=B.responseXML;else if (B.status==0&&B.readyState==4){this.DOMDocument=FCKTools.CreateXmlObject('DOMDocument');this.DOMDocument.async=false;this.DOMDocument.resolveExternals=false;this.DOMDocument.loadXML(B.responseText);}else{this.DOMDocument=null;};if (this.DOMDocument==null||this.DOMDocument.firstChild==null){this.Error=true;if (window.confirm('Error loading "'+A+'"\r\nDo you want to see more info?')) alert('URL requested: "'+A+'"\r\nServer response:\r\nStatus: '+B.status+'\r\nResponse text:\r\n'+B.responseText);}};FCKXml.prototype.SelectNodes=function(A,B){if (this.Error) return [];if (B) return B.selectNodes(A);else return this.DOMDocument.selectNodes(A);};FCKXml.prototype.SelectSingleNode=function(A,B){if (this.Error) return null;if (B) return B.selectSingleNode(A);else return this.DOMDocument.selectSingleNode(A);} +var FCKStyleDef=function(A,B){this.Name=A;this.Element=B.toUpperCase();this.IsObjectElement=FCKRegexLib.ObjectElements.test(this.Element);this.Attributes={};};FCKStyleDef.prototype.AddAttribute=function(A,B){this.Attributes[A]=B;};FCKStyleDef.prototype.GetOpenerTag=function(){var s='<'+this.Element;for (var a in this.Attributes) s+=' '+a+'="'+this.Attributes[a]+'"';return s+'>';};FCKStyleDef.prototype.GetCloserTag=function(){return '';};FCKStyleDef.prototype.RemoveFromSelection=function(){if (FCKSelection.GetType()=='Control') this._RemoveMe(FCK.ToolbarSet.CurrentInstance.Selection.GetSelectedElement());else this._RemoveMe(FCK.ToolbarSet.CurrentInstance.Selection.GetParentElement());} +FCKStyleDef.prototype.ApplyToSelection=function(){var A=FCK.ToolbarSet.CurrentInstance.EditorDocument.selection;if (A.type=='Text'){var B=A.createRange();var e=document.createElement(this.Element);e.innerHTML=B.htmlText;this._AddAttributes(e);this._RemoveDuplicates(e);B.pasteHTML(e.outerHTML);}else if (A.type=='Control'){var C=FCK.ToolbarSet.CurrentInstance.Selection.GetSelectedElement();if (C.tagName==this.Element) this._AddAttributes(C);}};FCKStyleDef.prototype._AddAttributes=function(A){for (var a in this.Attributes){switch (a.toLowerCase()){case 'style':A.style.cssText=this.Attributes[a];break;case 'class':A.setAttribute('className',this.Attributes[a],0);break;case 'src':A.setAttribute('_fcksavedurl',this.Attributes[a],0);default:A.setAttribute(a,this.Attributes[a],0);}}};FCKStyleDef.prototype._RemoveDuplicates=function(A){for (var i=0;i');else if (A=='div'&&FCKBrowserInfo.IsGecko) FCK.ExecuteNamedCommand('FormatBlock','div');else FCK.ExecuteNamedCommand('FormatBlock','<'+A+'>');};FCKFormatBlockCommand.prototype.GetState=function(){return FCK.GetNamedCommandValue('FormatBlock');};var FCKPreviewCommand=function(){this.Name='Preview';};FCKPreviewCommand.prototype.Execute=function(){FCK.Preview();};FCKPreviewCommand.prototype.GetState=function(){return 0;};var FCKSaveCommand=function(){this.Name='Save';};FCKSaveCommand.prototype.Execute=function(){var A=FCK.GetParentForm();if (typeof(A.onsubmit)=='function'){var B=A.onsubmit();if (B!=null&&B===false) return;};A.submit();};FCKSaveCommand.prototype.GetState=function(){return 0;};var FCKNewPageCommand=function(){this.Name='NewPage';};FCKNewPageCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();FCK.SetHTML('');FCKUndo.Typing=true;};FCKNewPageCommand.prototype.GetState=function(){return 0;};var FCKSourceCommand=function(){this.Name='Source';};FCKSourceCommand.prototype.Execute=function(){if (FCKConfig.SourcePopup){var A=FCKConfig.ScreenWidth*0.65;var B=FCKConfig.ScreenHeight*0.65;FCKDialog.OpenDialog('FCKDialog_Source',FCKLang.Source,'dialog/fck_source.html',A,B,null,null,true);}else FCK.SwitchEditMode();};FCKSourceCommand.prototype.GetState=function(){return (FCK.EditMode==0?0:1);};var FCKUndoCommand=function(){this.Name='Undo';};FCKUndoCommand.prototype.Execute=function(){if (FCKBrowserInfo.IsIE) FCKUndo.Undo();else FCK.ExecuteNamedCommand('Undo');};FCKUndoCommand.prototype.GetState=function(){if (FCKBrowserInfo.IsIE) return (FCKUndo.CheckUndoState()?0:-1);else return FCK.GetNamedCommandState('Undo');};var FCKRedoCommand=function(){this.Name='Redo';};FCKRedoCommand.prototype.Execute=function(){if (FCKBrowserInfo.IsIE) FCKUndo.Redo();else FCK.ExecuteNamedCommand('Redo');};FCKRedoCommand.prototype.GetState=function(){if (FCKBrowserInfo.IsIE) return (FCKUndo.CheckRedoState()?0:-1);else return FCK.GetNamedCommandState('Redo');};var FCKPageBreakCommand=function(){this.Name='PageBreak';};FCKPageBreakCommand.prototype.Execute=function(){var e=FCK.EditorDocument.createElement('DIV');e.style.pageBreakAfter='always';e.innerHTML=' ';var A=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',e);A=FCK.InsertElement(A);};FCKPageBreakCommand.prototype.GetState=function(){return 0;};var FCKUnlinkCommand=function(){this.Name='Unlink';};FCKUnlinkCommand.prototype.Execute=function(){if (FCKBrowserInfo.IsGecko){var A=FCK.Selection.MoveToAncestorNode('A');if (A) FCK.Selection.SelectNode(A);};FCK.ExecuteNamedCommand(this.Name);if (FCKBrowserInfo.IsGecko) FCK.Selection.Collapse(true);};FCKUnlinkCommand.prototype.GetState=function(){var A=FCK.GetNamedCommandState(this.Name);if (A==0&&FCK.EditMode==0){var B=FCKSelection.MoveToAncestorNode('A');var C=(B&&B.name.length>0&&B.href.length==0);if (C) A=-1;};return A;};var FCKSelectAllCommand=function(){this.Name='SelectAll';};FCKSelectAllCommand.prototype=new FCKNamedCommand('SelectAll');FCKSelectAllCommand.prototype.GetState=function(){return 0;} +var FCKSpellCheckCommand=function(){this.Name='SpellCheck';this.IsEnabled=(FCKConfig.SpellChecker=='ieSpell'||FCKConfig.SpellChecker=='SpellerPages');};FCKSpellCheckCommand.prototype.Execute=function(){switch (FCKConfig.SpellChecker){case 'ieSpell':this._RunIeSpell();break;case 'SpellerPages':FCKDialog.OpenDialog('FCKDialog_SpellCheck','Spell Check','dialog/fck_spellerpages.html',440,480);break;}};FCKSpellCheckCommand.prototype._RunIeSpell=function(){try{var A=new ActiveXObject("ieSpell.ieSpellExtension");A.CheckAllLinkedDocuments(FCK.EditorDocument);}catch(e){if(e.number==-2146827859){if (confirm(FCKLang.IeSpellDownload)) window.open(FCKConfig.IeSpellDownloadUrl,'IeSpellDownload');}else alert('Error Loading ieSpell: '+e.message+' ('+e.number+')');}};FCKSpellCheckCommand.prototype.GetState=function(){return this.IsEnabled?0:-1;} +var FCKTextColorCommand=function(A){this.Name=A=='ForeColor'?'TextColor':'BGColor';this.Type=A;var B;if (FCKBrowserInfo.IsIE) B=window;else if (FCK.ToolbarSet._IFrame) B=FCKTools.GetElementWindow(FCK.ToolbarSet._IFrame);else B=window.parent;this._Panel=new FCKPanel(B,true);this._Panel.AppendStyleSheet(FCKConfig.SkinPath+'fck_editor.css');this._Panel.MainNode.className='FCK_Panel';this._CreatePanelBody(this._Panel.Document,this._Panel.MainNode);FCKTools.DisableSelection(this._Panel.Document.body);};FCKTextColorCommand.prototype.Execute=function(A,B,C){FCK._ActiveColorPanelType=this.Type;this._Panel.Show(A,B,C);};FCKTextColorCommand.prototype.SetColor=function(A){if (FCK._ActiveColorPanelType=='ForeColor') FCK.ExecuteNamedCommand('ForeColor',A);else if (FCKBrowserInfo.IsGeckoLike){if (FCKBrowserInfo.IsGecko&&!FCKConfig.GeckoUseSPAN) FCK.EditorDocument.execCommand('useCSS',false,false);FCK.ExecuteNamedCommand('hilitecolor',A);if (FCKBrowserInfo.IsGecko&&!FCKConfig.GeckoUseSPAN) FCK.EditorDocument.execCommand('useCSS',false,true);}else FCK.ExecuteNamedCommand('BackColor',A);delete FCK._ActiveColorPanelType;};FCKTextColorCommand.prototype.GetState=function(){return 0;};function FCKTextColorCommand_OnMouseOver() { this.className='ColorSelected';};function FCKTextColorCommand_OnMouseOut() { this.className='ColorDeselected';};function FCKTextColorCommand_OnClick(){this.className='ColorDeselected';this.Command.SetColor('#'+this.Color);this.Command._Panel.Hide();};function FCKTextColorCommand_AutoOnClick(){this.className='ColorDeselected';this.Command.SetColor('');this.Command._Panel.Hide();};function FCKTextColorCommand_MoreOnClick(){this.className='ColorDeselected';this.Command._Panel.Hide();FCKDialog.OpenDialog('FCKDialog_Color',FCKLang.DlgColorTitle,'dialog/fck_colorselector.html',400,330,this.Command.SetColor);};FCKTextColorCommand.prototype._CreatePanelBody=function(A,B){function CreateSelectionDiv(){var C=A.createElement("DIV");C.className='ColorDeselected';C.onmouseover=FCKTextColorCommand_OnMouseOver;C.onmouseout=FCKTextColorCommand_OnMouseOut;return C;};var D=B.appendChild(A.createElement("TABLE"));D.className='ForceBaseFont';D.style.tableLayout='fixed';D.cellPadding=0;D.cellSpacing=0;D.border=0;D.width=150;var E=D.insertRow(-1).insertCell(-1);E.colSpan=8;var C=E.appendChild(CreateSelectionDiv());C.innerHTML='\n \n \n \n \n
    '+FCKLang.ColorAutomatic+'
    ';C.Command=this;C.onclick=FCKTextColorCommand_AutoOnClick;var G=FCKConfig.FontColors.toString().split(',');var H=0;while (H
    ';C.Command=this;C.onclick=FCKTextColorCommand_OnClick;}};E=D.insertRow(-1).insertCell(-1);E.colSpan=8;C=E.appendChild(CreateSelectionDiv());C.innerHTML='
    '+FCKLang.ColorMoreColors+'
    ';C.Command=this;C.onclick=FCKTextColorCommand_MoreOnClick;} +var FCKPastePlainTextCommand=function(){this.Name='PasteText';};FCKPastePlainTextCommand.prototype.Execute=function(){FCK.PasteAsPlainText();};FCKPastePlainTextCommand.prototype.GetState=function(){return FCK.GetNamedCommandState('Paste');}; +var FCKPasteWordCommand=function(){this.Name='PasteWord';};FCKPasteWordCommand.prototype.Execute=function(){FCK.PasteFromWord();};FCKPasteWordCommand.prototype.GetState=function(){if (FCKConfig.ForcePasteAsPlainText) return -1;else return FCK.GetNamedCommandState('Paste');}; +var FCKTableCommand=function(A){this.Name=A;};FCKTableCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();switch (this.Name){case 'TableInsertRow':FCKTableHandler.InsertRow();break;case 'TableDeleteRows':FCKTableHandler.DeleteRows();break;case 'TableInsertColumn':FCKTableHandler.InsertColumn();break;case 'TableDeleteColumns':FCKTableHandler.DeleteColumns();break;case 'TableInsertCell':FCKTableHandler.InsertCell();break;case 'TableDeleteCells':FCKTableHandler.DeleteCells();break;case 'TableMergeCells':FCKTableHandler.MergeCells();break;case 'TableSplitCell':FCKTableHandler.SplitCell();break;case 'TableDelete':FCKTableHandler.DeleteTable();break;default:alert(FCKLang.UnknownCommand.replace(/%1/g,this.Name));}};FCKTableCommand.prototype.GetState=function(){return 0;} +var FCKStyleCommand=function(){this.Name='Style';this.StylesLoader=new FCKStylesLoader();this.StylesLoader.Load(FCKConfig.StylesXmlPath);this.Styles=this.StylesLoader.Styles;};FCKStyleCommand.prototype.Execute=function(A,B){FCKUndo.SaveUndoStep();if (B.Selected) B.Style.RemoveFromSelection();else B.Style.ApplyToSelection();FCKUndo.SaveUndoStep();FCK.Focus();FCK.Events.FireEvent("OnSelectionChange");};FCKStyleCommand.prototype.GetState=function(){if (!FCK.EditorDocument) return -1;var A=FCK.EditorDocument.selection;if (FCKSelection.GetType()=='Control'){var e=FCKSelection.GetSelectedElement();if (e) return this.StylesLoader.StyleGroups[e.tagName]?0:-1;};return 0;};FCKStyleCommand.prototype.GetActiveStyles=function(){var A=[];if (FCKSelection.GetType()=='Control') this._CheckStyle(FCKSelection.GetSelectedElement(),A,false);else this._CheckStyle(FCKSelection.GetParentElement(),A,true);return A;};FCKStyleCommand.prototype._CheckStyle=function(A,B,C){if (!A) return;if (A.nodeType==1){var D=this.StylesLoader.StyleGroups[A.tagName];if (D){for (var i=0;i<\/body><\/html>');B.close();FCKTools.AddEventListenerEx(D,'focus',FCKPanel_Window_OnFocus,this);FCKTools.AddEventListenerEx(D,'blur',FCKPanel_Window_OnBlur,this);};B.dir=FCKLang.Dir;B.oncontextmenu=FCKTools.CancelEvent;this.MainNode=B.body.appendChild(B.createElement('DIV'));this.MainNode.style.cssFloat=this.IsRTL?'right':'left';};FCKPanel.prototype.AppendStyleSheet=function(A){FCKTools.AppendStyleSheet(this.Document,A);};FCKPanel.prototype.Preload=function(x,y,A){if (this._Popup) this._Popup.show(x,y,0,0,A);};FCKPanel.prototype.Show=function(x,y,A,B,C){var D;if (this._Popup){this._Popup.show(x,y,0,0,A);this.MainNode.style.width=B?B+'px':'';this.MainNode.style.height=C?C+'px':'';D=this.MainNode.offsetWidth;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=(x*-1)+A.offsetWidth-D;};this._Popup.show(x,y,D,this.MainNode.offsetHeight,A);if (this.OnHide){if (this._Timer) CheckPopupOnHide.call(this,true);this._Timer=FCKTools.SetInterval(CheckPopupOnHide,100,this);}}else{if (typeof(FCKFocusManager)!='undefined') FCKFocusManager.Lock();if (this.ParentPanel) this.ParentPanel.Lock();this.MainNode.style.width=B?B+'px':'';this.MainNode.style.height=C?C+'px':'';D=this.MainNode.offsetWidth;if (!B) this._IFrame.width=1;if (!C) this._IFrame.height=1;D=this.MainNode.offsetWidth;var E=FCKTools.GetElementPosition(A.nodeType==9?(FCKTools.IsStrictMode(A)?A.documentElement:A.body):A,this._Window);if (this.IsRTL&&!this.IsContextMenu) x=(x*-1);x+=E.X;y+=E.Y;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=x+A.offsetWidth-D;}else{var F=FCKTools.GetViewPaneSize(this._Window);var G=FCKTools.GetScrollPosition(this._Window);var H=F.Height+G.Y;var I=F.Width+G.X;if ((x+D)>I) x-=x+D-I;if ((y+this.MainNode.offsetHeight)>H) y-=y+this.MainNode.offsetHeight-H;};if (x<0) x=0;this._IFrame.style.left=x+'px';this._IFrame.style.top=y+'px';var J=D;var K=this.MainNode.offsetHeight;this._IFrame.width=J;this._IFrame.height=K;this._IFrame.contentWindow.focus();};this._IsOpened=true;FCKTools.RunFunction(this.OnShow,this);};FCKPanel.prototype.Hide=function(A){if (this._Popup) this._Popup.hide();else{if (!this._IsOpened) return;if (typeof(FCKFocusManager)!='undefined') FCKFocusManager.Unlock();this._IFrame.width=this._IFrame.height=0;this._IsOpened=false;if (this.ParentPanel) this.ParentPanel.Unlock();if (!A) FCKTools.RunFunction(this.OnHide,this);}};FCKPanel.prototype.CheckIsOpened=function(){if (this._Popup) return this._Popup.isOpen;else return this._IsOpened;};FCKPanel.prototype.CreateChildPanel=function(){var A=this._Popup?FCKTools.GetDocumentWindow(this.Document):this._Window;var B=new FCKPanel(A,true);B.ParentPanel=this;return B;};FCKPanel.prototype.Lock=function(){this._LockCounter++;};FCKPanel.prototype.Unlock=function(){if (--this._LockCounter==0&&!this.HasFocus) this.Hide();};function FCKPanel_Window_OnFocus(e,A){A.HasFocus=true;};function FCKPanel_Window_OnBlur(e,A){A.HasFocus=false;if (A._LockCounter==0) FCKTools.RunFunction(A.Hide,A);};function CheckPopupOnHide(A){if (A||!this._Popup.isOpen){window.clearInterval(this._Timer);this._Timer=null;FCKTools.RunFunction(this.OnHide,this);}};function FCKPanel_Cleanup(){this._Popup=null;this._Window=null;this.Document=null;this.MainNode=null;} +var FCKIcon=function(A){var B=A?typeof(A):'undefined';switch (B){case 'number':this.Path=FCKConfig.SkinPath+'fck_strip.gif';this.Size=16;this.Position=A;break;case 'undefined':this.Path=FCK_SPACER_PATH;break;case 'string':this.Path=A;break;default:this.Path=A[0];this.Size=A[1];this.Position=A[2];}};FCKIcon.prototype.CreateIconElement=function(A){var B,eIconImage;if (this.Position){var C='-'+((this.Position-1)*this.Size)+'px';if (FCKBrowserInfo.IsIE){B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path;eIconImage.style.top=C;}else{B=A.createElement('IMG');B.src=FCK_SPACER_PATH;B.style.backgroundPosition='0px '+C;B.style.backgroundImage='url('+this.Path+')';}}else{B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path?this.Path:FCK_SPACER_PATH;};B.className='TB_Button_Image';return B;} +var FCKToolbarButtonUI=function(A,B,C,D,E,F){this.Name=A;this.Label=B||A;this.Tooltip=C||this.Label;this.Style=E||0;this.State=F||0;this.Icon=new FCKIcon(D);if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarButtonUI_Cleanup);};FCKToolbarButtonUI.prototype._CreatePaddingElement=function(A){var B=A.createElement('IMG');B.className='TB_Button_Padding';B.src=FCK_SPACER_PATH;return B;};FCKToolbarButtonUI.prototype.Create=function(A){var B=this.MainElement;if (B){FCKToolbarButtonUI_Cleanup.call(this);if (B.parentNode) B.parentNode.removeChild(B);B=this.MainElement=null;};var C=FCKTools.GetElementDocument(A);B=this.MainElement=C.createElement('DIV');B._FCKButton=this;B.title=this.Tooltip;if (FCKBrowserInfo.IsGecko) B.onmousedown=FCKTools.CancelEvent;this.ChangeState(this.State,true);if (this.Style==0&&!this.ShowArrow){B.appendChild(this.Icon.CreateIconElement(C));}else{var D=B.appendChild(C.createElement('TABLE'));D.cellPadding=0;D.cellSpacing=0;var E=D.insertRow(-1);var F=E.insertCell(-1);if (this.Style==0||this.Style==2) F.appendChild(this.Icon.CreateIconElement(C));else F.appendChild(this._CreatePaddingElement(C));if (this.Style==1||this.Style==2){F=E.insertCell(-1);F.className='TB_Button_Text';F.noWrap=true;F.appendChild(C.createTextNode(this.Label));};if (this.ShowArrow){if (this.Style!=0){E.insertCell(-1).appendChild(this._CreatePaddingElement(C));};F=E.insertCell(-1);var G=F.appendChild(C.createElement('IMG'));G.src=FCKConfig.SkinPath+'images/toolbar.buttonarrow.gif';G.width=5;G.height=3;};F=E.insertCell(-1);F.appendChild(this._CreatePaddingElement(C));};A.appendChild(B);};FCKToolbarButtonUI.prototype.ChangeState=function(A,B){if (!B&&this.State==A) return;var e=this.MainElement;switch (parseInt(A,10)){case 0:e.className='TB_Button_Off';e.onmouseover=FCKToolbarButton_OnMouseOverOff;e.onmouseout=FCKToolbarButton_OnMouseOutOff;e.onclick=FCKToolbarButton_OnClick;break;case 1:e.className='TB_Button_On';e.onmouseover=FCKToolbarButton_OnMouseOverOn;e.onmouseout=FCKToolbarButton_OnMouseOutOn;e.onclick=FCKToolbarButton_OnClick;break;case -1:e.className='TB_Button_Disabled';e.onmouseover=null;e.onmouseout=null;e.onclick=null;break;};this.State=A;};function FCKToolbarButtonUI_Cleanup(){if (this.MainElement){this.MainElement._FCKButton=null;this.MainElement=null;}};function FCKToolbarButton_OnMouseOverOn(){this.className='TB_Button_On_Over';};function FCKToolbarButton_OnMouseOutOn(){this.className='TB_Button_On';};function FCKToolbarButton_OnMouseOverOff(){this.className='TB_Button_Off_Over';};function FCKToolbarButton_OnMouseOutOff(){this.className='TB_Button_Off';};function FCKToolbarButton_OnClick(e){if (this._FCKButton.OnClick) this._FCKButton.OnClick(this._FCKButton);}; +var FCKToolbarButton=function(A,B,C,D,E,F,G){this.CommandName=A;this.Label=B;this.Tooltip=C;this.Style=D;this.SourceView=E?true:false;this.ContextSensitive=F?true:false;if (G==null) this.IconPath=FCKConfig.SkinPath+'toolbar/'+A.toLowerCase()+'.gif';else if (typeof(G)=='number') this.IconPath=[FCKConfig.SkinPath+'fck_strip.gif',16,G];};FCKToolbarButton.prototype.Create=function(A){this._UIButton=new FCKToolbarButtonUI(this.CommandName,this.Label,this.Tooltip,this.IconPath,this.Style);this._UIButton.OnClick=this.Click;this._UIButton._ToolbarButton=this;this._UIButton.Create(A);};FCKToolbarButton.prototype.RefreshState=function(){var A=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (A==this._UIButton.State) return;this._UIButton.ChangeState(A);};FCKToolbarButton.prototype.Click=function(){var A=this._ToolbarButton||this;FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(A.CommandName).Execute();};FCKToolbarButton.prototype.Enable=function(){this.RefreshState();};FCKToolbarButton.prototype.Disable=function(){this._UIButton.ChangeState(-1);} +var FCKSpecialCombo=function(A,B,C,D,E){this.FieldWidth=B||100;this.PanelWidth=C||150;this.PanelMaxHeight=D||150;this.Label=' ';this.Caption=A;this.Tooltip=A;this.Style=2;this.Enabled=true;this.Items={};this._Panel=new FCKPanel(E||window,true);this._Panel.AppendStyleSheet(FCKConfig.SkinPath+'fck_editor.css');this._PanelBox=this._Panel.MainNode.appendChild(this._Panel.Document.createElement('DIV'));this._PanelBox.className='SC_Panel';this._PanelBox.style.width=this.PanelWidth+'px';this._PanelBox.innerHTML='
    ';this._ItemsHolderEl=this._PanelBox.getElementsByTagName('TD')[0];if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKSpecialCombo_Cleanup);};function FCKSpecialCombo_ItemOnMouseOver(){this.className+=' SC_ItemOver';};function FCKSpecialCombo_ItemOnMouseOut(){this.className=this.originalClass;};function FCKSpecialCombo_ItemOnClick(){this.className=this.originalClass;this.FCKSpecialCombo._Panel.Hide();this.FCKSpecialCombo.SetLabel(this.FCKItemLabel);if (typeof(this.FCKSpecialCombo.OnSelect)=='function') this.FCKSpecialCombo.OnSelect(this.FCKItemID,this);};FCKSpecialCombo.prototype.AddItem=function(A,B,C,D){var E=this._ItemsHolderEl.appendChild(this._Panel.Document.createElement('DIV'));E.className=E.originalClass='SC_Item';E.innerHTML=B;E.FCKItemID=A;E.FCKItemLabel=C||A;E.FCKSpecialCombo=this;E.Selected=false;if (FCKBrowserInfo.IsIE) E.style.width='100%';if (D) E.style.backgroundColor=D;E.onmouseover=FCKSpecialCombo_ItemOnMouseOver;E.onmouseout=FCKSpecialCombo_ItemOnMouseOut;E.onclick=FCKSpecialCombo_ItemOnClick;this.Items[A.toString().toLowerCase()]=E;return E;};FCKSpecialCombo.prototype.SelectItem=function(A){A=A?A.toString().toLowerCase():'';var B=this.Items[A];if (B){B.className=B.originalClass='SC_ItemSelected';B.Selected=true;}};FCKSpecialCombo.prototype.SelectItemByLabel=function(A,B){for (var C in this.Items){var D=this.Items[C];if (D.FCKItemLabel==A){D.className=D.originalClass='SC_ItemSelected';D.Selected=true;if (B) this.SetLabel(A);}}};FCKSpecialCombo.prototype.DeselectAll=function(A){for (var i in this.Items){this.Items[i].className=this.Items[i].originalClass='SC_Item';this.Items[i].Selected=false;};if (A) this.SetLabel('');};FCKSpecialCombo.prototype.SetLabelById=function(A){A=A?A.toString().toLowerCase():'';var B=this.Items[A];this.SetLabel(B?B.FCKItemLabel:'');};FCKSpecialCombo.prototype.SetLabel=function(A){this.Label=A.length==0?' ':A;if (this._LabelEl){this._LabelEl.innerHTML=this.Label;FCKTools.DisableSelection(this._LabelEl);}};FCKSpecialCombo.prototype.SetEnabled=function(A){this.Enabled=A;this._OuterTable.className=A?'':'SC_FieldDisabled';};FCKSpecialCombo.prototype.Create=function(A){var B=FCKTools.GetElementDocument(A);var C=this._OuterTable=A.appendChild(B.createElement('TABLE'));C.cellPadding=0;C.cellSpacing=0;C.insertRow(-1);var D;var E;switch (this.Style){case 0:D='TB_ButtonType_Icon';E=false;break;case 1:D='TB_ButtonType_Text';E=false;break;case 2:E=true;break;};if (this.Caption&&this.Caption.length>0&&E){var F=C.rows[0].insertCell(-1);F.innerHTML=this.Caption;F.className='SC_FieldCaption';};var G=FCKTools.AppendElement(C.rows[0].insertCell(-1),'div');if (E){G.className='SC_Field';G.style.width=this.FieldWidth+'px';G.innerHTML='
     
    ';this._LabelEl=G.getElementsByTagName('label')[0];this._LabelEl.innerHTML=this.Label;}else{G.className='TB_Button_Off';G.innerHTML='
    '+this.Caption+'
    ';};G.SpecialCombo=this;G.onmouseover=FCKSpecialCombo_OnMouseOver;G.onmouseout=FCKSpecialCombo_OnMouseOut;G.onclick=FCKSpecialCombo_OnClick;FCKTools.DisableSelection(this._Panel.Document.body);};function FCKSpecialCombo_Cleanup(){this._LabelEl=null;this._OuterTable=null;this._ItemsHolderEl=null;this._PanelBox=null;if (this.Items){for (var A in this.Items) this.Items[A]=null;}};function FCKSpecialCombo_OnMouseOver(){if (this.SpecialCombo.Enabled){switch (this.SpecialCombo.Style){case 0:this.className='TB_Button_On_Over';break;case 1:this.className='TB_Button_On_Over';break;case 2:this.className='SC_Field SC_FieldOver';break;}}};function FCKSpecialCombo_OnMouseOut(){switch (this.SpecialCombo.Style){case 0:this.className='TB_Button_Off';break;case 1:this.className='TB_Button_Off';break;case 2:this.className='SC_Field';break;}};function FCKSpecialCombo_OnClick(e){var A=this.SpecialCombo;if (A.Enabled){var B=A._Panel;var C=A._PanelBox;var D=A._ItemsHolderEl;var E=A.PanelMaxHeight;if (A.OnBeforeClick) A.OnBeforeClick(A);if (FCKBrowserInfo.IsIE) B.Preload(0,this.offsetHeight,this);if (D.offsetHeight>E) C.style.height=E+'px';else C.style.height='';B.Show(0,this.offsetHeight,this);}}; +var FCKToolbarSpecialCombo=function(){this.SourceView=false;this.ContextSensitive=true;this._LastValue=null;};function FCKToolbarSpecialCombo_OnSelect(A,B){FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).Execute(A,B);};FCKToolbarSpecialCombo.prototype.Create=function(A){this._Combo=new FCKSpecialCombo(this.GetLabel(),this.FieldWidth,this.PanelWidth,this.PanelMaxHeight,FCKBrowserInfo.IsIE?window:FCKTools.GetElementWindow(A).parent);this._Combo.Tooltip=this.Tooltip;this._Combo.Style=this.Style;this.CreateItems(this._Combo);this._Combo.Create(A);this._Combo.CommandName=this.CommandName;this._Combo.OnSelect=FCKToolbarSpecialCombo_OnSelect;};function FCKToolbarSpecialCombo_RefreshActiveItems(A,B){A.DeselectAll();A.SelectItem(B);A.SetLabelById(B);};FCKToolbarSpecialCombo.prototype.RefreshState=function(){var A;var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (B!=-1){A=1;if (this.RefreshActiveItems) this.RefreshActiveItems(this._Combo,B);else{if (this._LastValue!=B){this._LastValue=B;FCKToolbarSpecialCombo_RefreshActiveItems(this._Combo,B);}}}else A=-1;if (A==this.State) return;if (A==-1){this._Combo.DeselectAll();this._Combo.SetLabel('');};this.State=A;this._Combo.SetEnabled(A!=-1);};FCKToolbarSpecialCombo.prototype.Enable=function(){this.RefreshState();};FCKToolbarSpecialCombo.prototype.Disable=function(){this.State=-1;this._Combo.DeselectAll();this._Combo.SetLabel('');this._Combo.SetEnabled(false);}; +var FCKToolbarFontsCombo=function(A,B){this.CommandName='FontName';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarFontsCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontsCombo.prototype.GetLabel=function(){return FCKLang.Font;};FCKToolbarFontsCombo.prototype.CreateItems=function(A){var B=FCKConfig.FontNames.split(';');for (var i=0;i'+B[i]+'
    ');} +var FCKToolbarFontSizeCombo=function(A,B){this.CommandName='FontSize';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarFontSizeCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontSizeCombo.prototype.GetLabel=function(){return FCKLang.FontSize;};FCKToolbarFontSizeCombo.prototype.CreateItems=function(A){A.FieldWidth=70;var B=FCKConfig.FontSizes.split(';');for (var i=0;i'+C[1]+'',C[1]);}} +var FCKToolbarFontFormatCombo=function(A,B){this.CommandName='FontFormat';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;this.NormalLabel='Normal';this.PanelWidth=190;};FCKToolbarFontFormatCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontFormatCombo.prototype.GetLabel=function(){return FCKLang.FontFormat;};FCKToolbarFontFormatCombo.prototype.CreateItems=function(A){var B=A._Panel.Document;FCKTools.AppendStyleSheet(B,FCKConfig.ToolbarComboPreviewCSS);if (FCKConfig.BodyId&&FCKConfig.BodyId.length>0) B.body.id=FCKConfig.BodyId;if (FCKConfig.BodyClass&&FCKConfig.BodyClass.length>0) B.body.className+=' '+FCKConfig.BodyClass;var C=FCKLang['FontFormats'].split(';');var D={p:C[0],pre:C[1],address:C[2],h1:C[3],h2:C[4],h3:C[5],h4:C[6],h5:C[7],h6:C[8],div:C[9]};var E=FCKConfig.FontFormats.split(';');for (var i=0;i<'+F+'>'+G+'
    ',G);}};if (FCKBrowserInfo.IsIE){FCKToolbarFontFormatCombo.prototype.RefreshActiveItems=function(A,B){if (B==this.NormalLabel){if (A.Label!=' ') A.DeselectAll(true);}else{if (this._LastValue==B) return;A.SelectItemByLabel(B,true);};this._LastValue=B;}} +var FCKToolbarStyleCombo=function(A,B){this.CommandName='Style';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarStyleCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarStyleCombo.prototype.GetLabel=function(){return FCKLang.Style;};FCKToolbarStyleCombo.prototype.CreateItems=function(A){var B=A._Panel.Document;FCKTools.AppendStyleSheet(B,FCKConfig.ToolbarComboPreviewCSS);B.body.className+=' ForceBaseFont';if (FCKConfig.BodyId&&FCKConfig.BodyId.length>0) B.body.id=FCKConfig.BodyId;if (FCKConfig.BodyClass&&FCKConfig.BodyClass.length>0) B.body.className+=' '+FCKConfig.BodyClass;if (!(FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsGecko10)) A.OnBeforeClick=this.RefreshVisibleItems;var C=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).Styles;for (var s in C){var D=C[s];var E;if (D.IsObjectElement) E=A.AddItem(s,s);else E=A.AddItem(s,D.GetOpenerTag()+s+D.GetCloserTag());E.Style=D;}};FCKToolbarStyleCombo.prototype.RefreshActiveItems=function(A){A.DeselectAll();var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetActiveStyles();if (B.length>0){for (var i=0;i'+document.getElementById('xToolbarSpace').innerHTML+'');G.close();G.oncontextmenu=FCKTools.CancelEvent;FCKTools.AppendStyleSheet(G,FCKConfig.SkinPath+'fck_editor.css');B=D.__FCKToolbarSet=new FCKToolbarSet(G);B._IFrame=F;if (FCK.IECleanup) FCK.IECleanup.AddItem(D,FCKToolbarSet_Target_Cleanup);};B.CurrentInstance=FCK;FCK.AttachToOnSelectionChange(B.RefreshItemsState);return B;};function FCK_OnBlur(A){var B=A.ToolbarSet;if (B.CurrentInstance==A) B.Disable();};function FCK_OnFocus(A){var B=A.ToolbarSet;var C=A||FCK;B.CurrentInstance.FocusManager.RemoveWindow(B._IFrame.contentWindow);B.CurrentInstance=C;C.FocusManager.AddWindow(B._IFrame.contentWindow,true);B.Enable();};function FCKToolbarSet_Cleanup(){this._TargetElement=null;this._IFrame=null;};function FCKToolbarSet_Target_Cleanup(){this.__FCKToolbarSet=null;};var FCKToolbarSet=function(A){this._Document=A;this._TargetElement=A.getElementById('xToolbar');var B=A.getElementById('xExpandHandle');var C=A.getElementById('xCollapseHandle');B.title=FCKLang.ToolbarExpand;B.onclick=FCKToolbarSet_Expand_OnClick;C.title=FCKLang.ToolbarCollapse;C.onclick=FCKToolbarSet_Collapse_OnClick;if (!FCKConfig.ToolbarCanCollapse||FCKConfig.ToolbarStartExpanded) this.Expand();else this.Collapse();C.style.display=FCKConfig.ToolbarCanCollapse?'':'none';if (FCKConfig.ToolbarCanCollapse) C.style.display='';else A.getElementById('xTBLeftBorder').style.display='';this.Toolbars=[];this.IsLoaded=false;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarSet_Cleanup);};function FCKToolbarSet_Expand_OnClick(){FCK.ToolbarSet.Expand();};function FCKToolbarSet_Collapse_OnClick(){FCK.ToolbarSet.Collapse();};FCKToolbarSet.prototype.Expand=function(){this._ChangeVisibility(false);};FCKToolbarSet.prototype.Collapse=function(){this._ChangeVisibility(true);};FCKToolbarSet.prototype._ChangeVisibility=function(A){this._Document.getElementById('xCollapsed').style.display=A?'':'none';this._Document.getElementById('xExpanded').style.display=A?'none':'';if (FCKBrowserInfo.IsGecko){FCKTools.RunFunction(window.onresize);}};FCKToolbarSet.prototype.Load=function(A){this.Name=A;this.Items=[];this.ItemsWysiwygOnly=[];this.ItemsContextSensitive=[];this._TargetElement.innerHTML='';var B=FCKConfig.ToolbarSets[A];if (!B){alert(FCKLang.UnknownToolbarSet.replace(/%1/g,A));return;};this.Toolbars=[];for (var x=0;x0) A.deleteRow(0);}};FCKMenuBlock.prototype.Create=function(A){if (!this._ItemsTable){if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKMenuBlock_Cleanup);this._Window=FCKTools.GetElementWindow(A);var B=FCKTools.GetElementDocument(A);var C=A.appendChild(B.createElement('table'));C.cellPadding=0;C.cellSpacing=0;FCKTools.DisableSelection(C);var D=C.insertRow(-1).insertCell(-1);D.className='MN_Menu';var E=this._ItemsTable=D.appendChild(B.createElement('table'));E.cellPadding=0;E.cellSpacing=0;};for (var i=0;i0&&F.href.length==0);if (G) return;menu.AddSeparator();if (E) menu.AddItem('Link',FCKLang.EditLink,34);menu.AddItem('Unlink',FCKLang.RemoveLink,35);}}};case 'Image':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&!tag.getAttribute('_fckfakelement')){menu.AddSeparator();menu.AddItem('Image',FCKLang.ImageProperties,37);}}};case 'Anchor':return {AddItems:function(menu,tag,tagName){var F=FCKSelection.MoveToAncestorNode('A');var G=(F&&F.name.length>0);if (G||(tagName=='IMG'&&tag.getAttribute('_fckanchor'))){menu.AddSeparator();menu.AddItem('Anchor',FCKLang.AnchorProp,36);}}};case 'Flash':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckflash')){menu.AddSeparator();menu.AddItem('Flash',FCKLang.FlashProperties,38);}}};case 'Form':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('FORM')){menu.AddSeparator();menu.AddItem('Form',FCKLang.FormProp,48);}}};case 'Checkbox':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='checkbox'){menu.AddSeparator();menu.AddItem('Checkbox',FCKLang.CheckboxProp,49);}}};case 'Radio':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='radio'){menu.AddSeparator();menu.AddItem('Radio',FCKLang.RadioButtonProp,50);}}};case 'TextField':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='text'||tag.type=='password')){menu.AddSeparator();menu.AddItem('TextField',FCKLang.TextFieldProp,51);}}};case 'HiddenField':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='hidden'){menu.AddSeparator();menu.AddItem('HiddenField',FCKLang.HiddenFieldProp,56);}}};case 'ImageButton':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='image'){menu.AddSeparator();menu.AddItem('ImageButton',FCKLang.ImageButtonProp,55);}}};case 'Button':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='button'||tag.type=='submit'||tag.type=='reset')){menu.AddSeparator();menu.AddItem('Button',FCKLang.ButtonProp,54);}}};case 'Select':return {AddItems:function(menu,tag,tagName){if (tagName=='SELECT'){menu.AddSeparator();menu.AddItem('Select',FCKLang.SelectionFieldProp,53);}}};case 'Textarea':return {AddItems:function(menu,tag,tagName){if (tagName=='TEXTAREA'){menu.AddSeparator();menu.AddItem('Textarea',FCKLang.TextareaProp,52);}}};case 'BulletedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('UL')){menu.AddSeparator();menu.AddItem('BulletedList',FCKLang.BulletedListProp,27);}}};case 'NumberedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('OL')){menu.AddSeparator();menu.AddItem('NumberedList',FCKLang.NumberedListProp,26);}}};};return null;};function FCK_ContextMenu_OnBeforeOpen(){FCK.Events.FireEvent('OnSelectionChange');var A,sTagName;if ((A=FCKSelection.GetSelectedElement())) sTagName=A.tagName;var B=FCK.ContextMenu._InnerContextMenu;B.RemoveAllItems();var C=FCK.ContextMenu.Listeners;for (var i=0;i0){var A;if (this.AvailableLangs.IndexOf(FCKLanguageManager.ActiveLanguage.Code)>=0) A=FCKLanguageManager.ActiveLanguage.Code;else A=this.AvailableLangs[0];LoadScript(this.Path+'lang/'+A+'.js');};LoadScript(this.Path+'fckplugin.js');} +var FCKPlugins=FCK.Plugins={};FCKPlugins.ItemsCount=0;FCKPlugins.Items={};FCKPlugins.Load=function(){var A=FCKPlugins.Items;for (var i=0;i + + + + + + + + + + + +
    +

    FontFormats Localization

    +

    + IE has some limits when handling the "Font Format". It actually uses localized + strings to retrieve the current format value. This makes it very difficult to + make a system that works on every single computer in the world. +

    +

    + With FCKeditor, this problem impacts in the "Format" toolbar command that + doesn't reflects the format of the current cursor position. +

    +

    + There is only one way to make it work. We must localize FCKeditor using the + strings used by IE. In this way, we will have the expected behavior at least + when using FCKeditor in the same language as the browser. So, when localizing + FCKeditor, go to a computer with IE in the target language, open this page and + use the following string to the "FontFormats" value: +

    +
    + FontFormats : "", +
    +
    +
    +

     

    +
     
    +
     
    +

     

    +

     

    +

     

    +

     

    +
     
    +
     
    +
    + + diff --git a/fckeditor/editor/lang/_translationstatus.txt b/fckeditor/editor/lang/_translationstatus.txt new file mode 100755 index 0000000..9f35819 --- /dev/null +++ b/fckeditor/editor/lang/_translationstatus.txt @@ -0,0 +1,80 @@ +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * File Name: _translationstatus.txt + * Translations Status. + * + * File Authors: + * Frederico Caldeira Knabben (fredck@fckeditor.net) + */ + +af.js Found: 402 Missing: 0 +ar.js Found: 402 Missing: 0 +bg.js Found: 379 Missing: 23 +bn.js Found: 387 Missing: 15 +bs.js Found: 231 Missing: 171 +ca.js Found: 402 Missing: 0 +cs.js Found: 387 Missing: 15 +da.js Found: 387 Missing: 15 +de.js Found: 402 Missing: 0 +el.js Found: 402 Missing: 0 +en-au.js Found: 402 Missing: 0 +en-ca.js Found: 402 Missing: 0 +en-uk.js Found: 402 Missing: 0 +eo.js Found: 351 Missing: 51 +es.js Found: 387 Missing: 15 +et.js Found: 387 Missing: 15 +eu.js Found: 387 Missing: 15 +fa.js Found: 402 Missing: 0 +fi.js Found: 387 Missing: 15 +fo.js Found: 402 Missing: 0 +fr.js Found: 402 Missing: 0 +gl.js Found: 387 Missing: 15 +he.js Found: 402 Missing: 0 +hi.js Found: 402 Missing: 0 +hr.js Found: 402 Missing: 0 +hu.js Found: 402 Missing: 0 +it.js Found: 402 Missing: 0 +ja.js Found: 402 Missing: 0 +km.js Found: 376 Missing: 26 +ko.js Found: 374 Missing: 28 +lt.js Found: 382 Missing: 20 +lv.js Found: 387 Missing: 15 +mn.js Found: 231 Missing: 171 +ms.js Found: 357 Missing: 45 +nb.js Found: 402 Missing: 0 +nl.js Found: 402 Missing: 0 +no.js Found: 402 Missing: 0 +pl.js Found: 387 Missing: 15 +pt-br.js Found: 402 Missing: 0 +pt.js Found: 387 Missing: 15 +ro.js Found: 401 Missing: 1 +ru.js Found: 402 Missing: 0 +sk.js Found: 402 Missing: 0 +sl.js Found: 379 Missing: 23 +sr-latn.js Found: 374 Missing: 28 +sr.js Found: 374 Missing: 28 +sv.js Found: 382 Missing: 20 +th.js Found: 351 Missing: 51 +tr.js Found: 402 Missing: 0 +uk.js Found: 402 Missing: 0 +vi.js Found: 402 Missing: 0 +zh-cn.js Found: 402 Missing: 0 +zh.js Found: 402 Missing: 0 diff --git a/fckeditor/editor/lang/en-min.js b/fckeditor/editor/lang/en-min.js new file mode 100644 index 0000000..5c5a98a --- /dev/null +++ b/fckeditor/editor/lang/en-min.js @@ -0,0 +1,2 @@ +eval(function(p,a,c,k,e,d){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('aH 70={9a:"9i",9x:"aI 1j",dp:"8z 1j",30:"30",8F:"2C T",1m:"1m",2Z:"2Z",2K:"2K",K:"K",6U:"K as 57 1r",8y:"K 1X 1d",2J:"2J",7h:"W 19",6S:"13 2j",93:"g",6R:"d/G g",5A:"13 g",u:"d/G u",4y:"o",3N:"d/G o",6P:"Y",6O:"d/G Y",5c:"O",dn:"d/G O",6N:"3v",dl:"d 2d 3v",dj:"25 D",di:"d 25 D",5f:"1R",5g:"d 1R",27:"27 df",3q:"3q",2Y:"2Y",2c:"2c",db:"da d9",3r:"3r",2G:"2G",6F:"k 1h",d5:"1F 1h",d4:"m 1h",d3:"d2 1h",5n:"cZ 3n",6B:"cX 3n",1V:"1V",3l:"3l",cU:"1T P",cT:"d/13 1T P",cS:"1Z P",cR:"d/13 1Z P",6x:"1G O cP",cO:"1G cN",1z:"1z",6v:"2j",21:"21",5u:"1O",cJ:"j y",cI:"J y",3o:"3o",11:"11",l:"l",6s:"cF cE",cD:"6q cB",6p:"T 2L",cz:"d T 2L",1B:"1B",1J:"1J",cx:"3d p",cw:"j z",1U:"1U",6m:"3a z",p:"p",5F:"39 z",ct:"o p",cs:"cr 0 N 2w",6k:"G g",6j:"r",cn:"3i",cm:"3k",6h:"d 3i",cj:"R 18",6g:"d 3k",cg:"R 1a",cf:"d r",6e:"R 3f",cd:"6d 3f",6c:"c9 r",6b:"R O",6a:"r 7",5R:"O 7",c5:"o 7",c4:"Y 7",c3:"u 7",68:"p 7",67:"1J 7",5U:"3a z 7",bX:"3d p 7",64:"o p 7",5X:"j z 7",bT:"39 z 7",5Z:"1U 7",bO:"1B 7",bM:"2u;6u;2E;q 1;q 2;q 3;q 4;q 5;q 6;2u (bH)",bG:"bF 34. f 2t...",3h:"3h",bD:"1x 1r 1k 1g 9 1D 7w 9 be bB 1X 1d. 28 1k 1g 9 bA 1o bz 36?",by:"bx 33 bw 2e 1u bv 7Y 3w 5.5 82 bq. 28 1k 1g 9 1D 88 bo?",8a:"32 bm 8c \\"%1\\"",8e:"32 33 1y \\"%1\\"",bh:"bg v 8j",bd:"1j H \\"%1\\" 8q\'t 8s",8u:"16 U\'s 1t 1c 31 b8 8A 2l 8B 0 N. 29 1N b5 0 8C \\"8D 8E b1 15 8G-aZ\\". 29 aX aW 8K 15 8L 8O 2l.",aR:"1x 8P U 31 v be 8R. 2N 2T 1e 1I 1v 2V 2M 2S.",aN:"8S 3g v aL 9 2X 0 8V 2B. 2N 2T 1I 1v 2V 2M 2S.",8Z:"2R",aD:"aC",aB:"95",az:"97 1E",ax:"aw",av:"<1C>",au:"1s",9c:"f 9d 0 n",aq:"",9e:"2q",ao:"1w 3u",9f:"k 9 m (2b)",al:"m 9 k (2A)",9j:"1w 2y",aj:"ai ah",ag:"h",9n:"9o ad",ac:"ab 3b n",9q:"a9 a8",a7:"2n 3p",9t:"2n 2k w",a4:"a3 9z a1",a0:"1z",9C:"o 7",9X:"o 1s",9W:"3x 1o 9 0 1E",9V:"n",9U:"3t",9T:"9S j",9R:"14",9Q:"1f",9N:"9O 9P",9Y:"35 1O",a5:"17",a6:"aa",ae:"ak",am:"ap",ar:"k",ay:"2O 1i",aA:"2O 1M",aE:"2I",aJ:"1i",aK:"1M",aO:"m",aP:"j 10",aT:"10",aU:"1m",aY:"f 1n 0 b0 n",b6:"g",b7:"Y 7",ba:"bb bi",bj:"bl",bn:"bt Y 2r",bC:"bE",bJ:"1G 1I",bL:"x 17",bQ:"bR bU",bV:"g",bY:"g 1s",bZ:"24",c1:"g w",c2:"n",ca:"g 9 20 S 0 1r",cb:"E-2f",cc:"ce",ck:"",cp:"n",cq:"W an u",cy:"2p u h",cA:"2p cC 2q",cK:"(x cL 2e S 0 cQ)",cV:"E-2f 2E",cY:"3s d1",d6:"3s dc",de:"3t",dg:"3x 1o 9 0 1E",dk:"24",8x:"<4p>",3z:"<1v 2B>",8t:"2C F (8r)",4m:"8p F (8o)",8n:"4k F (8l)",8k:"4i F (3D)",4h:"24 8f h",4g:"2D F h",8d:"2D F 4e",89:"4d",87:"86 1P",85:"2r 1P",83:"4a 81",49:"7Z 1P",7X:"1j",7V:"7U 7T (7S)",7R:"7Q (7P)",7O:"14",7N:"1f",42:"k 37",7L:"10 37",7J:"f 1n 0 40 n",7H:"f 1n 0 e-7F 7E",7D:"f 2m an 20",7C:"1x 1v 1y 1N 7A 3c an 7y 4t 15 1N v 7v 7u",7t:"W y",7s:"7r",7q:"7p",7o:"2z",7n:"d a 1R",7k:"W 25 D",7i:"O 7",7g:"18",7f:"1a",7e:"17 2w",7c:"22",7b:"",4R:"k",79:"1F",78:"m",77:"14",76:"3y",75:"2x",74:"1f",73:"r 72",71:"r 4Z",6Z:"6Y",6X:"6W",6V:"r 7",6T:"14",58:"3y",6Q:"2x",5d:"1f",6M:"1d 6L",5h:"",6J:"6I",6H:"x",6G:"2d 22",6E:"",6D:"k",5o:"1F",6A:"m",6z:"6y 22",6w:"",5v:"10",6t:"1M",6r:"1i",5C:"2I",6o:"18 3j",6n:"1a 3j",6l:"J y",5I:"17 y",6i:"W...",5L:"11",6f:"11",5M:"1x 5Q 1r 3g v 2a.",69:"l",5T:"11 5V:",65:"l 3c:",5Y:"38 60",62:"l",63:"l 19",6C:"38 7j 2H",7l:"16 U 1t 1c 1L\'t 1W 0 N 9 26 1Y 36 1A. f 1Q 0 1p 1u 1e (1q+V).",7x:"16 U 1t 1c 1L\'t 1W 0 N 9 26 1Y 7K 1A. f 1Q 0 1p 1u 1e (1q+X).",80:"16 U 1t 1c 1L\'t 1W 0 N 9 26 1Y b9 1A. f 1Q 0 1p 1u 1e (1q+C).",8H:"K as 8J j",8M:"K 1X 1d",8T:"f 1D 8W 0 8Y 90 94 0 1p (<1b>1q+V) 15 9b <1b>2R.",9g:"1K 21 9k 2P",9m:"13 9p 2P",9s:"9u 2s 9y",9A:"9B",9D:"9F 2h...",9G:"12 7",9I:"u 7",9J:"u h",9Z:"f 1n 0 20 1y",at:"Q S aF",aM:"aQ 9",aV:"1K",b2:"1K 19",bc:"l",bk:"l 19",bu:"1V",bK:"- x bN -",bS:"M Z S bW...",c0:"M Z 1l: x c6 2a",ch:"M Z 1l: x 2F 23",co:"M Z 1l: cu 2H 23",cG:"M Z 1l: %1 2F 23",d0:"M dd v dh. 28 1k 1g 9 4n 1o 4l?",3C:"j (L)",4j:"w",3E:"p",3G:"4f",3H:"35",4c:"h",4b:"L",3K:"2z",48:"h",47:"46",45:"44",43:"h",3S:"L",41:"1O",7G:"3X",4o:"4q 7z 4u",4z:"4A 4C",4D:"j",4G:"L",4H:"4J",4K:"4O",4P:"2s",4S:"4V",4W:"1H as 50 54",55:"R",59:"h",5b:"1a",5e:"18",5j:"h",5k:"L",5m:"D 14",5q:"5r 5t",5w:"w",5B:"j",5D:"5E",5G:"h",5J:"L",5N:"1Z P 7",5S:"1T P 7",61:"66",7a:"w",7m:"7B",7M:"84",8b:"8g",8i:"8v (1, 2, 3)",8N:"8Q 2W (a, b, c)",96:"98 2W (A, B, C)",9r:"9v 2Q 2o (i, 9E, 9H)",9K:"a2 2Q 2o (I, aS, b3)",bf:"bp",bI:"J",bP:"2h 15 3m",ci:"cv cH",cM:"T 3p",d7:"1w 3u",dm:"k 9 m (2b)",3A:"m 9 k (2A)",3F:"1w 2y",3J:"D 1H 2g",3L:"3O 2v",3P:"3R 3T (3V)",3W:"4r",4s:"4B",4E:"4I",4L:"4Q",4T:"4X",4Y:"56 (5a-8)",5i:"5l 2v",5s:"1C D 1H 2g",5K:"12 w q",5O:"1C 12 w q",6K:"7I 34 8h",8m:"J y",8I:"J o n",99:"9h J",9w:"j",9L:"g",af:"aG g",b4:"bs g",c7:"T 3m",cW:"10",3B:"k",3I:"m",3Q:"1i",3Y:"12 4v 4F (4M 4U)",51:"12 3b",5p:"5x",5H:"5P",5W:"1m",1S:"1S",7W:"2k 1S",8X:"f 2m 0 9l 9 2X S 0 N
    (0 2U 3e d8 be 3M):",3U:"4w 2i 4N. f 2t...",5y:"(x 2i 8w)",91:"l 2U 3e",do:"27",3Z:"52 1s",7d:"8U",9M:"3w",4x:"5z 92 c8 53 9"};',62,832,'the|||||||Properties||to||||Insert||Please|Link|Name||Text|Left|Replace|Right|URL|Image|Button|Heading|Cell|||Anchor|not|Type|No|Color|Field||||Character||Window|Edit|set||Background|Paste|Value|Spell|editor|Table|List|Not|Delete|in|Page|browser||Select||Flash|check|Top|Find|Document|Remove|Width|and|Your|Border|Rows|All|Columns|strong|settings|Word|that|Height|want|Justify|Bottom|Toolbar|you|complete|Preview|type|it|keyboard|Ctrl|text|Info|security|for|popup|Language|The|name|Style|operations|Form|Other|paste|Server|Center|Show|Set|all|Checkbox|Ignore|don|Middle|must|Size|Bar|use|Smiley|Templates|Numbered|Textarea|Undo|permit|from|execute|Bulleted|anchor|Font|Alignment|changed|Target|Special|automatically|About|Do|You|found|LTR|Underline|Horizontal|available|Mail|Encoding|Colors|templates|Format|Content|features|select|Advisory|Numerals|By|Id|Menu|Up|wait|Normal|European|size|percent|Code|Selected|RTL|window|New|Popup|Address|words|Superscript|word|Baseline|Print|Copy|Break|are|Make|Abs|definitions|Roman|OK|disabled|sure|actual|blockers|Letters|open|Italic|Cut|Save|could|Unknown|command|XHTML|Reset|pasting|Position|Match|Selection|Hidden|Description|with|Radio|contents|Cells|was|Done|Row|Span|Column|Redo|Margins|Indent|Source|Title|Bold|Subscript|Message|Upload|Direction|Line|version|Send|pixels|DlgLnkTargetPopup|DlgDocLangDirRTL|DlgDocMaLeft|DlgButtonText|_top|DlgButtonTypeBtn|DlgDocLangCode|DlgButtonTypeSbm|DlgButtonTypeRst|DlgDocMaRight|DlgDocCharSet|DlgCheckboxSelected|DlgDocCharSetCE|lost|InsertImage|Central|DlgDocCharSetCT|DlgDocMaBottom|Chinese|DlgSelectValue|Traditional|DlgTemplatesLoading|Big5|DlgDocCharSetCR|lines|DlgDocMeIndex|DlgAboutBrowserInfoTab|link|DlgSelectSize|DlgLnkPopLeft|DlgSelectName|Method|DlgFormMethod|Action|DlgFormAction|DlgFormName|DlgLnkPopStatus|Scroll|DlgCheckboxValue|DlgCheckboxName|Resizable|Features|Submit|DlgLnkPopWinName|DlgLnkTargetFrameName|Topmost|DlgButtonType|Same|now|DlgLnkTargetParent|download|DlgSelectChkMulti|frame|Allow|Cyrillic|DlgDocCharSetGR|character|selections|Indexing|Loading|DlgAboutInfo|InsertImageLbl|DlgSelectOpAvail|Available|Greek|Options|DlgSelectOpText|DlgDocCharSetJP|Keywords|DlgSelectOpValue|DlgSelectBtnAdd|Japanese|Add|DlgSelectBtnModify|DlgDocCharSetKR|comma|list|Modify|DlgSelectBtnUp|Korean|DlgTableAlignLeft|DlgSelectBtnDown|DlgDocCharSetTR|separated|Down|DlgSelectBtnSetValue|Turkish|DlgDocCharSetUN|padding|selected|DlgDocMeDescr|Browser|go|value|DlgSelectBtnDelete|Unicode|plain|DlgCellWidthPx|DlgTextareaName|UTF|DlgTextareaCols|InsertTableLbl|DlgCellHeight|DlgTextareaRows|InsertSmileyLbl|InsertSmiley|DlgCellWordWrapNotSet|DlgDocCharSetWE|DlgTextName|DlgTextValue|Western|DlgTextCharWidth|DecreaseIndent|DlgCellHorAlignCenter|DlgDocMeAuthor|DlgTextMaxChars|Maximum|DlgDocCharSetOther|Characters|FontSize|DlgCellVerAlignTop|DlgTextType|Author|DlgTemplatesNoTpl|For|RemoveLink|DlgTextTypeText|DlgCellVerAlignBaseline|DlgTextTypePass|Password|SelectionField|DlgHiddenName|DlgDocMeCopy|DlgCellBorderColor|DlgHiddenValue|DlgDocDocType|DlgFindTitle|DlgFindNotFoundMsg|BulletedListProp|DlgDocDocTypeOther|Copyright|specified|TableProperties|NumberedListProp|DlgReplaceFindLbl|HiddenFieldProp|what|DlgDocPreview|TextFieldProp|DlgReplaceCaseChk|TextareaProp|case|DlgLstStart|DlgReplaceReplaceBtn|DlgReplaceReplAllBtn|ImageButtonProp|DlgReplaceReplaceLbl|Start|CheckboxProp|ButtonProp|DlgReplaceTitle|CellProperties|TableDelete|SplitCell|Merge|DeleteCells|DlgFindFindBtn|InsertColumn|InsertRow|DlgCellBtnSelect|CellCM|EditLink|DlgCellBackColor|HiddenField|DlgCellCollSpan|DlgCellRowSpan|PageBreakLbl|Universal|DlgCellVerAlignBottom|SpellCheck|DlgCellVerAlignMiddle|Formatted|FontFormat|DlgCellVerAlignNotSet|ShowTableBorders|Vertical|DlgCellVerAlign|DlgCellHorAlignRight|IncreaseIndent|DlgReplaceWordChk|DlgCellHorAlignLeft|DlgCellHorAlignNotSet|LeftJustify|DlgCellHorAlign|DlgCellWordWrapNo|Yes|DlgCellWordWrapYes|DlgDocIncXHTML|Wrap|DlgCellWordWrap|InsertLineLbl|InsertFlash|InsertFlashLbl|DlgCellWidthPc|InsertLink|RemoveFormat|DlgCellWidth|PasteText|DlgCellTitle|Summary|DlgTableSummary|Caption|DlgTableCaption|FCKLang|DlgTableCellPad|spacing|DlgTableCellSpace|DlgTableHeight|DlgTableWidthPc|DlgTableWidthPx|DlgTableWidth|DlgTableAlignRight|DlgTableAlignCenter|DlgLstType|DlgTableAlignNotSet|DlgTableAlign|DlgAboutLicenseTab|DlgTableBorder|DlgTableColumns|DlgTableRows|SelectAll|DlgTableTitle|whole|DlgSpecialCharTitle|PasteErrorPaste|DlgLstTypeCircle|DlgSmileyTitle|DlgColorSelected|Highlight|DlgColorHighlight|Clear|DlgColorBtnClear|DlgColorTitle|spaces|contain|seems|PasteErrorCut|alphabetic|multiple|begin|Circle|DlnLnkMsgInvPopName|DlnLnkMsgNoAnchor|address|mail|DlgSelectLines|DlnLnkMsgNoEMail|Include|DlnLnkMsgNoUrl|cutting|DlgLnkPopTop|DlgLstTypeDisc|DlgLnkPopHeight|DlgLnkPopWidth|Netscape|Dependent|DlgLnkPopDependent|IE|Screen|Full|DlgLnkPopFullScrn|DlgTemplatesTitle|DlgLnkPopToolbar|Explorer|Status|PasteErrorCopy|Bars|or|DlgLnkPopScroll|Disc|DlgLnkPopMenu|Location|DlgLnkPopLocation|without|DlgLnkPopResize|UnknownToolbarItem|DlgLstTypeSquare|item|DlgLnkPopWinFeat|UnknownCommand|Frame|Square|Declarations|DlgLstTypeNumbers|implemented|DlgLnkTargetTop|_self|DlgDocBgColor|DlgLnkTargetSelf|_parent|Parent|doesn|_blank|exist|DlgLnkTargetBlank|NoActiveX|Numbers|defined|DlgLnkTargetFrame|PasteWord|Expand|some|of|option|Run|ActiveX|NewPage|plug|PasteAsText|DlgDocBgImage|Plain|errors|notice|PasteFromWord|DlgLstTypeLCase|missing|resources|Lowercase|opened|It|DlgPasteMsg2|License|dialog|inside|DlgTemplatesSelMsg|following|DlgBtnOK|box|DlgTemplatesReplace|further|InsertLinkLbl|using|Close|DlgLstTypeUCase|Browse|Uppercase|DlgDocBgNoScroll|Dir|hit|DlgAlertUrl|insert|DlgGenId|DlgGenLangDirLtr|DlgPasteIgnoreFont|Nonscrolling|ltr|DlgGenLangCode|Face|template|DlgPasteRemoveStyles|DlgGenTabIndex|Tab|Styles|DlgGenClass|DlgLstTypeSRoman|DlgPasteCleanBox|DlgGenContType|Clean|Small|DlgDocCText|ToolbarCollapse|Box|Resource|ColorAutomatic|Automatic|DlgImgTitle|ColorMoreColors|ii|More|DocProps|iii|DlgAnchorTitle|DlgAnchorName|DlgLstTypeLRoman|DlgDocCLink|DlgAboutVersion|DlgImgLockRatio|Lock|Ratio|DlgImgHeight|DlgImgWidth|Alternative|DlgImgAlt|DlgImgUpload|DlgImgURL|DlgImgBtnUpload|DlgImgInfoTab|DlgBtnResetSize|DlgAnchorErrorName|DlgGenStyle|Charset|Large|Linked|DlgGenLinkCharset|DlgImgBorder|DlgImgHSpace|DlgGenTitle|Classes|Stylesheet|HSpace|Long|DlgGenLongDescr|Index|DlgImgVSpace|DlgDocCVisited|DlgGenName|Key|Access|DlgGenAccessKey|VSpace|DlgGenLangDirRtl|DlgImgAlign||DlgGenLangDir|Align|DlgGenNotSet|DlgImgAlignLeft||DlgSpellNotInDic|DlgInfoTab|DlgOpOther|Advanced|DlgAdvancedTag|DlgImgAlignAbsBottom|DlgBtnBrowseServer|DlgImgAlignAbsMiddle|DlgBtnClose|Cancel|DlgBtnCancel|DlgImgAlignBaseline|dictionary|Visited|var|Collapse|DlgImgAlignBottom|DlgImgAlignMiddle|possible|DlgSpellChangeTo|DialogBlocked|DlgImgAlignRight|DlgImgAlignTextTop|Change|BrowseServerBlocked|II|DlgImgAlignTop|DlgImgPreview|DlgSpellBtnIgnore|experience|may|DlgImgAlertUrl|ins|image|controls|DlgSpellBtnIgnoreAll|III|DlgDocCActive|enable|DlgImgLinkTab|DlgFlashTitle|limit|copying|DlgFlashChkPlay|Auto|DlgSpellBtnReplace|UnknownToolbarSet||DlgDocGeneralTab|Command|NotImplemented|Play|DlgFlashChkLoop|DlgSpellBtnReplaceAll|Loop|toolbar|DlgFlashChkMenu|cleaning|General|more||Active|Enable|DlgSpellBtnUndo|Internet|is|This|NotCompatiblePaste|before|clean|copied|DlgFlashScale|PasteWordConfirm|Scale|Processing|ProcessingXHTML|DIV|DlgDocBackTab|DlgFlashScaleAll|DlgSpellNoSuggestions|DlgFlashScaleNoBorder|FontFormats|suggestions|FormProp|DlgDocColorsTab|DlgFlashScaleFit|Exact|DlgSpellProgress|SelectionFieldProp|Fit|DlgLnkWindowTitle|progress|RadioButtonProp|DlgLnkInfoTab|DlgLnkTargetTab|DlgSpellNoMispell|DlgLnkType|DlgLnkTypeURL|AnchorProp|FlashProperties|ImageProperties|misspellings|DlgDocMargins|information|Split|DlgLnkTypeAnchor|DlgLnkTypeEMail|DlgLnkProto|MergeCells|Protocol|InsertCell|DeleteColumns|DlgSpellNoChanges|DlgDocMetaTab|DeleteRows|DlgLnkProtoOther|other|ColumnCM|RowCM|DlgSpellOneChange|DlgLnkURL|DlgLnkAnchorSel|Maximize|FitWindow|ImageButton|One|Meta|TextField|RadioButton|DlgLnkAnchorByName|PageBreak|DlgLnkAnchorById|Keyboard|Element|UniversalKeyboard|Spelling|Check|DlgSpellManyChanges|Data|BGColor|TextColor|DlgLnkNoAnchors|anchors|DlgDocPageTitle|Details|ShowDetails|Borders|document|BulletedList|BulletedListLbl|NumberedList|NumberedListLbl|DlgLnkEMail|DlgDocMaTop|Increase|DlgLnkEMailSubject|Decrease|IeSpellDownload|Subject|Block|BlockJustify|RightJustify|CenterJustify|DlgLnkEMailBody|DlgDocLangDir|will|Through|Strike|StrikeThrough|Body|checker|DlgLnkUpload|FCKeditor|DlgLnkBtnUpload|installed|InsertSpecialChar|InsertSpecialCharLbl|DlgLnkTarget|InsertLine|DlgDocLangDirLTR|InsertTable|DlgAboutAboutTab|ToolbarExpand'.split('|'),0,{})) + diff --git a/fckeditor/editor/lang/en.js b/fckeditor/editor/lang/en.js new file mode 100755 index 0000000..457258c --- /dev/null +++ b/fckeditor/editor/lang/en.js @@ -0,0 +1,508 @@ +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * File Name: en.js + * English language file. + * + * File Authors: + * Frederico Caldeira Knabben (www.fckeditor.net) + */ + +var FCKLang = +{ +// Language direction : "ltr" (left to right) or "rtl" (right to left). +Dir : "ltr", + +ToolbarCollapse : "Collapse Toolbar", +ToolbarExpand : "Expand Toolbar", + +// Toolbar Items and Context Menu +Save : "Save", +NewPage : "New Page", +Preview : "Preview", +Cut : "Cut", +Copy : "Copy", +Paste : "Paste", +PasteText : "Paste as plain text", +PasteWord : "Paste from Word", +Print : "Print", +SelectAll : "Select All", +RemoveFormat : "Remove Format", +InsertLinkLbl : "Link", +InsertLink : "Insert/Edit Link", +RemoveLink : "Remove Link", +Anchor : "Insert/Edit Anchor", +InsertImageLbl : "Image", +InsertImage : "Insert/Edit Image", +InsertFlashLbl : "Flash", +InsertFlash : "Insert/Edit Flash", +InsertTableLbl : "Table", +InsertTable : "Insert/Edit Table", +InsertLineLbl : "Line", +InsertLine : "Insert Horizontal Line", +InsertSpecialCharLbl: "Special Character", +InsertSpecialChar : "Insert Special Character", +InsertSmileyLbl : "Smiley", +InsertSmiley : "Insert Smiley", +About : "About FCKeditor", +Bold : "Bold", +Italic : "Italic", +Underline : "Underline", +StrikeThrough : "Strike Through", +Subscript : "Subscript", +Superscript : "Superscript", +LeftJustify : "Left Justify", +CenterJustify : "Center Justify", +RightJustify : "Right Justify", +BlockJustify : "Block Justify", +DecreaseIndent : "Decrease Indent", +IncreaseIndent : "Increase Indent", +Undo : "Undo", +Redo : "Redo", +NumberedListLbl : "Numbered List", +NumberedList : "Insert/Remove Numbered List", +BulletedListLbl : "Bulleted List", +BulletedList : "Insert/Remove Bulleted List", +ShowTableBorders : "Show Table Borders", +ShowDetails : "Show Details", +Style : "Style", +FontFormat : "Format", +Font : "Font", +FontSize : "Size", +TextColor : "Text Color", +BGColor : "Background Color", +Source : "Source", +Find : "Find", +Replace : "Replace", +SpellCheck : "Check Spelling", +UniversalKeyboard : "Universal Keyboard", +PageBreakLbl : "Page Break", +PageBreak : "Insert Page Break", + +Form : "Form", +Checkbox : "Checkbox", +RadioButton : "Radio Button", +TextField : "Text Field", +Textarea : "Textarea", +HiddenField : "Hidden Field", +Button : "Button", +SelectionField : "Selection Field", +ImageButton : "Image Button", + +FitWindow : "Maximize the editor size", + +// Context Menu +EditLink : "Edit Link", +CellCM : "Cell", +RowCM : "Row", +ColumnCM : "Column", +InsertRow : "Insert Row", +DeleteRows : "Delete Rows", +InsertColumn : "Insert Column", +DeleteColumns : "Delete Columns", +InsertCell : "Insert Cell", +DeleteCells : "Delete Cells", +MergeCells : "Merge Cells", +SplitCell : "Split Cell", +TableDelete : "Delete Table", +CellProperties : "Cell Properties", +TableProperties : "Table Properties", +ImageProperties : "Image Properties", +FlashProperties : "Flash Properties", + +AnchorProp : "Anchor Properties", +ButtonProp : "Button Properties", +CheckboxProp : "Checkbox Properties", +HiddenFieldProp : "Hidden Field Properties", +RadioButtonProp : "Radio Button Properties", +ImageButtonProp : "Image Button Properties", +TextFieldProp : "Text Field Properties", +SelectionFieldProp : "Selection Field Properties", +TextareaProp : "Textarea Properties", +FormProp : "Form Properties", + +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", //REVIEW : Check _getfontformat.html + +// Alerts and Messages +ProcessingXHTML : "Processing XHTML. Please wait...", +Done : "Done", +PasteWordConfirm : "The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?", +NotCompatiblePaste : "This command is available for Internet Explorer version 5.5 or more. Do you want to paste without cleaning?", +UnknownToolbarItem : "Unknown toolbar item \"%1\"", +UnknownCommand : "Unknown command name \"%1\"", +NotImplemented : "Command not implemented", +UnknownToolbarSet : "Toolbar set \"%1\" doesn't exist", +NoActiveX : "Your browser's security settings could limit some features of the editor. You must enable the option \"Run ActiveX controls and plug-ins\". You may experience errors and notice missing features.", +BrowseServerBlocked : "The resources browser could not be opened. Make sure that all popup blockers are disabled.", +DialogBlocked : "It was not possible to open the dialog window. Make sure all popup blockers are disabled.", + +// Dialogs +DlgBtnOK : "OK", +DlgBtnCancel : "Cancel", +DlgBtnClose : "Close", +DlgBtnBrowseServer : "Browse Server", +DlgAdvancedTag : "Advanced", +DlgOpOther : "", +DlgInfoTab : "Info", +DlgAlertUrl : "Please insert the URL", + +// General Dialogs Labels +DlgGenNotSet : "", +DlgGenId : "Id", +DlgGenLangDir : "Language Direction", +DlgGenLangDirLtr : "Left to Right (LTR)", +DlgGenLangDirRtl : "Right to Left (RTL)", +DlgGenLangCode : "Language Code", +DlgGenAccessKey : "Access Key", +DlgGenName : "Name", +DlgGenTabIndex : "Tab Index", +DlgGenLongDescr : "Long Description URL", +DlgGenClass : "Stylesheet Classes", +DlgGenTitle : "Advisory Title", +DlgGenContType : "Advisory Content Type", +DlgGenLinkCharset : "Linked Resource Charset", +DlgGenStyle : "Style", + +// Image Dialog +DlgImgTitle : "Image Properties", +DlgImgInfoTab : "Image Info", +DlgImgBtnUpload : "Send it to the Server", +DlgImgURL : "URL", +DlgImgUpload : "Upload", +DlgImgAlt : "Alternative Text", +DlgImgWidth : "Width", +DlgImgHeight : "Height", +DlgImgLockRatio : "Lock Ratio", +DlgBtnResetSize : "Reset Size", +DlgImgBorder : "Border", +DlgImgHSpace : "HSpace", +DlgImgVSpace : "VSpace", +DlgImgAlign : "Align", +DlgImgAlignLeft : "Left", +DlgImgAlignAbsBottom: "Abs Bottom", +DlgImgAlignAbsMiddle: "Abs Middle", +DlgImgAlignBaseline : "Baseline", +DlgImgAlignBottom : "Bottom", +DlgImgAlignMiddle : "Middle", +DlgImgAlignRight : "Right", +DlgImgAlignTextTop : "Text Top", +DlgImgAlignTop : "Top", +DlgImgPreview : "Preview", +DlgImgAlertUrl : "Please type the image URL", +DlgImgLinkTab : "Link", + +// Flash Dialog +DlgFlashTitle : "Flash Properties", +DlgFlashChkPlay : "Auto Play", +DlgFlashChkLoop : "Loop", +DlgFlashChkMenu : "Enable Flash Menu", +DlgFlashScale : "Scale", +DlgFlashScaleAll : "Show all", +DlgFlashScaleNoBorder : "No Border", +DlgFlashScaleFit : "Exact Fit", + +// Link Dialog +DlgLnkWindowTitle : "Link", +DlgLnkInfoTab : "Link Info", +DlgLnkTargetTab : "Target", + +DlgLnkType : "Link Type", +DlgLnkTypeURL : "URL", +DlgLnkTypeAnchor : "Link to anchor in the text", +DlgLnkTypeEMail : "E-Mail", +DlgLnkProto : "Protocol", +DlgLnkProtoOther : "", +DlgLnkURL : "URL", +DlgLnkAnchorSel : "Select an Anchor", +DlgLnkAnchorByName : "By Anchor Name", +DlgLnkAnchorById : "By Element Id", +DlgLnkNoAnchors : "(No anchors available in the document)", //REVIEW : Change < and > with ( and ) +DlgLnkEMail : "E-Mail Address", +DlgLnkEMailSubject : "Message Subject", +DlgLnkEMailBody : "Message Body", +DlgLnkUpload : "Upload", +DlgLnkBtnUpload : "Send it to the Server", + +DlgLnkTarget : "Target", +DlgLnkTargetFrame : "", +DlgLnkTargetPopup : "", +DlgLnkTargetBlank : "New Window (_blank)", +DlgLnkTargetParent : "Parent Window (_parent)", +DlgLnkTargetSelf : "Same Window (_self)", +DlgLnkTargetTop : "Topmost Window (_top)", +DlgLnkTargetFrameName : "Target Frame Name", +DlgLnkPopWinName : "Popup Window Name", +DlgLnkPopWinFeat : "Popup Window Features", +DlgLnkPopResize : "Resizable", +DlgLnkPopLocation : "Location Bar", +DlgLnkPopMenu : "Menu Bar", +DlgLnkPopScroll : "Scroll Bars", +DlgLnkPopStatus : "Status Bar", +DlgLnkPopToolbar : "Toolbar", +DlgLnkPopFullScrn : "Full Screen (IE)", +DlgLnkPopDependent : "Dependent (Netscape)", +DlgLnkPopWidth : "Width", +DlgLnkPopHeight : "Height", +DlgLnkPopLeft : "Left Position", +DlgLnkPopTop : "Top Position", + +DlnLnkMsgNoUrl : "Please type the link URL", +DlnLnkMsgNoEMail : "Please type the e-mail address", +DlnLnkMsgNoAnchor : "Please select an anchor", +DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", + +// Color Dialog +DlgColorTitle : "Select Color", +DlgColorBtnClear : "Clear", +DlgColorHighlight : "Highlight", +DlgColorSelected : "Selected", + +// Smiley Dialog +DlgSmileyTitle : "Insert a Smiley", + +// Special Character Dialog +DlgSpecialCharTitle : "Select Special Character", + +// Table Dialog +DlgTableTitle : "Table Properties", +DlgTableRows : "Rows", +DlgTableColumns : "Columns", +DlgTableBorder : "Border size", +DlgTableAlign : "Alignment", +DlgTableAlignNotSet : "", +DlgTableAlignLeft : "Left", +DlgTableAlignCenter : "Center", +DlgTableAlignRight : "Right", +DlgTableWidth : "Width", +DlgTableWidthPx : "pixels", +DlgTableWidthPc : "percent", +DlgTableHeight : "Height", +DlgTableCellSpace : "Cell spacing", +DlgTableCellPad : "Cell padding", +DlgTableCaption : "Caption", +DlgTableSummary : "Summary", + +// Table Cell Dialog +DlgCellTitle : "Cell Properties", +DlgCellWidth : "Width", +DlgCellWidthPx : "pixels", +DlgCellWidthPc : "percent", +DlgCellHeight : "Height", +DlgCellWordWrap : "Word Wrap", +DlgCellWordWrapNotSet : "", +DlgCellWordWrapYes : "Yes", +DlgCellWordWrapNo : "No", +DlgCellHorAlign : "Horizontal Alignment", +DlgCellHorAlignNotSet : "", +DlgCellHorAlignLeft : "Left", +DlgCellHorAlignCenter : "Center", +DlgCellHorAlignRight: "Right", +DlgCellVerAlign : "Vertical Alignment", +DlgCellVerAlignNotSet : "", +DlgCellVerAlignTop : "Top", +DlgCellVerAlignMiddle : "Middle", +DlgCellVerAlignBottom : "Bottom", +DlgCellVerAlignBaseline : "Baseline", +DlgCellRowSpan : "Rows Span", +DlgCellCollSpan : "Columns Span", +DlgCellBackColor : "Background Color", +DlgCellBorderColor : "Border Color", +DlgCellBtnSelect : "Select...", + +// Find Dialog +DlgFindTitle : "Find", +DlgFindFindBtn : "Find", +DlgFindNotFoundMsg : "The specified text was not found.", + +// Replace Dialog +DlgReplaceTitle : "Replace", +DlgReplaceFindLbl : "Find what:", +DlgReplaceReplaceLbl : "Replace with:", +DlgReplaceCaseChk : "Match case", +DlgReplaceReplaceBtn : "Replace", +DlgReplaceReplAllBtn : "Replace All", +DlgReplaceWordChk : "Match whole word", + +// Paste Operations / Dialog +PasteErrorPaste : "Your browser security settings don't permit the editor to automatically execute pasting operations. Please use the keyboard for that (Ctrl+V).", +PasteErrorCut : "Your browser security settings don't permit the editor to automatically execute cutting operations. Please use the keyboard for that (Ctrl+X).", +PasteErrorCopy : "Your browser security settings don't permit the editor to automatically execute copying operations. Please use the keyboard for that (Ctrl+C).", + +PasteAsText : "Paste as Plain Text", +PasteFromWord : "Paste from Word", + +DlgPasteMsg2 : "Please paste inside the following box using the keyboard (Ctrl+V) and hit OK.", +DlgPasteIgnoreFont : "Ignore Font Face definitions", +DlgPasteRemoveStyles : "Remove Styles definitions", +DlgPasteCleanBox : "Clean Up Box", + +// Color Picker +ColorAutomatic : "Automatic", +ColorMoreColors : "More Colors...", + +// Document Properties +DocProps : "Document Properties", + +// Anchor Dialog +DlgAnchorTitle : "Anchor Properties", +DlgAnchorName : "Anchor Name", +DlgAnchorErrorName : "Please type the anchor name", + +// Speller Pages Dialog +DlgSpellNotInDic : "Not in dictionary", +DlgSpellChangeTo : "Change to", +DlgSpellBtnIgnore : "Ignore", +DlgSpellBtnIgnoreAll : "Ignore All", +DlgSpellBtnReplace : "Replace", +DlgSpellBtnReplaceAll : "Replace All", +DlgSpellBtnUndo : "Undo", +DlgSpellNoSuggestions : "- No suggestions -", +DlgSpellProgress : "Spell check in progress...", +DlgSpellNoMispell : "Spell check complete: No misspellings found", +DlgSpellNoChanges : "Spell check complete: No words changed", +DlgSpellOneChange : "Spell check complete: One word changed", +DlgSpellManyChanges : "Spell check complete: %1 words changed", + +IeSpellDownload : "Spell checker not installed. Do you want to download it now?", + +// Button Dialog +DlgButtonText : "Text (Value)", +DlgButtonType : "Type", +DlgButtonTypeBtn : "Button", +DlgButtonTypeSbm : "Submit", +DlgButtonTypeRst : "Reset", + +// Checkbox and Radio Button Dialogs +DlgCheckboxName : "Name", +DlgCheckboxValue : "Value", +DlgCheckboxSelected : "Selected", + +// Form Dialog +DlgFormName : "Name", +DlgFormAction : "Action", +DlgFormMethod : "Method", + +// Select Field Dialog +DlgSelectName : "Name", +DlgSelectValue : "Value", +DlgSelectSize : "Size", +DlgSelectLines : "lines", +DlgSelectChkMulti : "Allow multiple selections", +DlgSelectOpAvail : "Available Options", +DlgSelectOpText : "Text", +DlgSelectOpValue : "Value", +DlgSelectBtnAdd : "Add", +DlgSelectBtnModify : "Modify", +DlgSelectBtnUp : "Up", +DlgSelectBtnDown : "Down", +DlgSelectBtnSetValue : "Set as selected value", +DlgSelectBtnDelete : "Delete", + +// Textarea Dialog +DlgTextareaName : "Name", +DlgTextareaCols : "Columns", +DlgTextareaRows : "Rows", + +// Text Field Dialog +DlgTextName : "Name", +DlgTextValue : "Value", +DlgTextCharWidth : "Character Width", +DlgTextMaxChars : "Maximum Characters", +DlgTextType : "Type", +DlgTextTypeText : "Text", +DlgTextTypePass : "Password", + +// Hidden Field Dialog +DlgHiddenName : "Name", +DlgHiddenValue : "Value", + +// Bulleted List Dialog +BulletedListProp : "Bulleted List Properties", +NumberedListProp : "Numbered List Properties", +DlgLstStart : "Start", +DlgLstType : "Type", +DlgLstTypeCircle : "Circle", +DlgLstTypeDisc : "Disc", +DlgLstTypeSquare : "Square", +DlgLstTypeNumbers : "Numbers (1, 2, 3)", +DlgLstTypeLCase : "Lowercase Letters (a, b, c)", +DlgLstTypeUCase : "Uppercase Letters (A, B, C)", +DlgLstTypeSRoman : "Small Roman Numerals (i, ii, iii)", +DlgLstTypeLRoman : "Large Roman Numerals (I, II, III)", + +// Document Properties Dialog +DlgDocGeneralTab : "General", +DlgDocBackTab : "Background", +DlgDocColorsTab : "Colors and Margins", +DlgDocMetaTab : "Meta Data", + +DlgDocPageTitle : "Page Title", +DlgDocLangDir : "Language Direction", +DlgDocLangDirLTR : "Left to Right (LTR)", +DlgDocLangDirRTL : "Right to Left (RTL)", +DlgDocLangCode : "Language Code", +DlgDocCharSet : "Character Set Encoding", +DlgDocCharSetCE : "Central European", +DlgDocCharSetCT : "Chinese Traditional (Big5)", +DlgDocCharSetCR : "Cyrillic", +DlgDocCharSetGR : "Greek", +DlgDocCharSetJP : "Japanese", +DlgDocCharSetKR : "Korean", +DlgDocCharSetTR : "Turkish", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "Western European", +DlgDocCharSetOther : "Other Character Set Encoding", + +DlgDocDocType : "Document Type Heading", +DlgDocDocTypeOther : "Other Document Type Heading", +DlgDocIncXHTML : "Include XHTML Declarations", +DlgDocBgColor : "Background Color", +DlgDocBgImage : "Background Image URL", +DlgDocBgNoScroll : "Nonscrolling Background", +DlgDocCText : "Text", +DlgDocCLink : "Link", +DlgDocCVisited : "Visited Link", +DlgDocCActive : "Active Link", +DlgDocMargins : "Page Margins", +DlgDocMaTop : "Top", +DlgDocMaLeft : "Left", +DlgDocMaRight : "Right", +DlgDocMaBottom : "Bottom", +DlgDocMeIndex : "Document Indexing Keywords (comma separated)", +DlgDocMeDescr : "Document Description", +DlgDocMeAuthor : "Author", +DlgDocMeCopy : "Copyright", +DlgDocPreview : "Preview", + +// Templates Dialog +Templates : "Templates", +DlgTemplatesTitle : "Content Templates", +DlgTemplatesSelMsg : "Please select the template to open in the editor
    (the actual contents will be lost):", +DlgTemplatesLoading : "Loading templates list. Please wait...", +DlgTemplatesNoTpl : "(No templates defined)", +DlgTemplatesReplace : "Replace actual contents", + +// About Dialog +DlgAboutAboutTab : "About", +DlgAboutBrowserInfoTab : "Browser Info", +DlgAboutLicenseTab : "License", +DlgAboutVersion : "version", +DlgAboutInfo : "For further information go to" +}; \ No newline at end of file diff --git a/fckeditor/editor/plugins/ImageManager/20062020_20061221.diff b/fckeditor/editor/plugins/ImageManager/20062020_20061221.diff new file mode 100644 index 0000000..0aa07f8 --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/20062020_20061221.diff @@ -0,0 +1,1692 @@ +diff -u -r /ImageManager_20062020/assets/editorFrame.js ./assets/editorFrame.js +--- /ImageManager_20062020/assets/editorFrame.js 2006-06-20 22:17:36.000000000 +0200 ++++ ./assets/editorFrame.js 2006-12-17 13:36:35.000000000 +0100 +@@ -1,8 +1,8 @@ + /** + * Javascript used by the editorFrame.php, it basically initializes the frame. +- * @author $Author: matrix $ +- * @author $Author: matrix $ - watermarking and replace code + several small enhancements +- * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ ++ * @author $Author: matrix $ ++ * @author $Author: matrix $ - watermarking and replace code + several small enhancements ++ * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ + * @package ImageManager + */ + +diff -u -r /ImageManager_20062020/Classes/api.watermark.php ./Classes/api.watermark.php +--- /ImageManager_20062020/Classes/api.watermark.php 2006-06-20 22:17:34.000000000 +0200 ++++ ./Classes/api.watermark.php 2006-12-16 22:38:13.000000000 +0100 +@@ -1,8 +1,9 @@ +- - small changes to place the watermark on a given coordinate and to only handle watermark area ++ * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ + * @package ImageManager + */ + +@@ -100,4 +101,4 @@ + } # EBD _get_image_color() + + } # END watermark API +-?> +\ Pas de fin de ligne à la fin du fichier. ++?> + +diff -u -r /ImageManager_20062020/Classes/Files.php ./Classes/Files.php +--- /ImageManager_20062020/Classes/Files.php 2006-06-20 22:17:34.000000000 +0200 ++++ ./Classes/Files.php 2006-12-16 22:38:13.000000000 +0100 +@@ -1,215 +1,215 @@ +-read())) +- { +- if ($entry != '.' && $entry != '..') +- { +- $obj = Files::fixPath($folder).$entry; +- //var_dump($obj); +- if (is_file($obj)) +- { +- $deleted &= Files::delFile($obj); +- } +- else if(is_dir($obj)) +- { +- $deleted &= Files::delFolder($obj, $recursive); +- } +- +- } +- } +- $d->close(); +- +- } +- +- //$folder= $folder.'/thumbs'; +- //var_dump($folder); +- if(is_dir($folder)) +- $deleted &= rmdir($folder); +- else +- $deleted &= false; +- +- Return $deleted; +- } +- +- /** +- * Append a / to the path if required. +- * @param string $path the path +- * @return string path with trailing / +- */ +- function fixPath($path) +- { +- //append a slash to the path if it doesn't exists. +- if(!(substr($path,-1) == '/')) +- $path .= '/'; +- Return $path; +- } +- +- /** +- * Concat two paths together. Basically $pathA+$pathB +- * @param string $pathA path one +- * @param string $pathB path two +- * @return string a trailing slash combinded path. +- */ +- function makePath($pathA, $pathB) +- { +- $pathA = Files::fixPath($pathA); +- if(substr($pathB,0,1)=='/') +- $pathB = substr($pathB,1); +- Return Files::fixPath($pathA.$pathB); +- } +- +- /** +- * Similar to makePath, but the second parameter +- * is not only a path, it may contain say a file ending. +- * @param string $pathA the leading path +- * @param string $pathB the ending path with file +- * @return string combined file path. +- */ +- function makeFile($pathA, $pathB) +- { +- $pathA = Files::fixPath($pathA); +- if(substr($pathB,0,1)=='/') +- $pathB = substr($pathB,1); +- +- Return $pathA.$pathB; +- } +- +- +- /** +- * Format the file size, limits to Mb. +- * @param int $size the raw filesize +- * @return string formated file size. +- */ +- function formatSize($size) +- { +- if($size < 1024) +- return $size.' bytes'; +- else if($size >= 1024 && $size < 1024*1024) +- return sprintf('%01.2f',$size/1024.0).' Kb'; +- else +- return sprintf('%01.2f',$size/(1024.0*1024)).' Mb'; ++class Files ++{ ++ ++ /** ++ * Copy a file from source to destination. If unique == true, then if ++ * the destination exists, it will be renamed by appending an increamenting ++ * counting number. ++ * @param string $source where the file is from, full path to the files required ++ * @param string $destination_file name of the new file, just the filename ++ * @param string $destination_dir where the files, just the destination dir, ++ * e.g., /www/html/gallery/ ++ * @param boolean $unique create unique destination file if true. ++ * @return string the new copied filename, else error if anything goes bad. ++ */ ++ function copyFile($source, $destination_dir, $destination_file, $unique=true) ++ { ++ if(!(file_exists($source) && is_file($source))) ++ return FILE_ERROR_NO_SOURCE; ++ ++ $destination_dir = Files::fixPath($destination_dir); ++ ++ if(!is_dir($destination_dir)) ++ Return FILE_ERROR_DST_DIR_FAILED; ++ ++ $filename = Files::escape($destination_file); ++ ++ if($unique) ++ { ++ $dotIndex = strrpos($destination_file, '.'); ++ $ext = ''; ++ if(is_int($dotIndex)) ++ { ++ $ext = substr($destination_file, $dotIndex); ++ $base = substr($destination_file, 0, $dotIndex); ++ } ++ $counter = 0; ++ while(is_file($destination_dir.$filename)) ++ { ++ $counter++; ++ $filename = $base.'_'.$counter.$ext; ++ } ++ } ++ ++ if (!copy($source, $destination_dir.$filename)) ++ return FILE_ERROR_COPY_FAILED; ++ ++ //verify that it copied, new file must exists ++ if (is_file($destination_dir.$filename)) ++ Return $filename; ++ else ++ return FILE_ERROR_COPY_FAILED; ++ } ++ ++ /** ++ * Create a new folder. ++ * @param string $newFolder specifiy the full path of the new folder. ++ * @return boolean true if the new folder is created, false otherwise. ++ */ ++ function createFolder($newFolder) ++ { ++ mkdir ($newFolder, 0777); ++ return chmod($newFolder, 0777); ++ } ++ ++ ++ /** ++ * Escape the filenames, any non-word characters will be ++ * replaced by an underscore. ++ * @param string $filename the orginal filename ++ * @return string the escaped safe filename ++ */ ++ function escape($filename) ++ { ++ Return preg_replace('/[^\w\._]/', '_', $filename); ++ } ++ ++ /** ++ * Delete a file. ++ * @param string $file file to be deleted ++ * @return boolean true if deleted, false otherwise. ++ */ ++ function delFile($file) ++ { ++ if(is_file($file)) ++ Return unlink($file); ++ else ++ Return false; ++ } ++ ++ /** ++ * Delete folder(s), can delete recursively. ++ * @param string $folder the folder to be deleted. ++ * @param boolean $recursive if true, all files and sub-directories ++ * are delete. If false, tries to delete the folder, can throw ++ * error if the directory is not empty. ++ * @return boolean true if deleted. ++ */ ++ function delFolder($folder, $recursive=false) ++ { ++ $deleted = true; ++ if($recursive) ++ { ++ $d = dir($folder); ++ while (false !== ($entry = $d->read())) ++ { ++ if ($entry != '.' && $entry != '..') ++ { ++ $obj = Files::fixPath($folder).$entry; ++ //var_dump($obj); ++ if (is_file($obj)) ++ { ++ $deleted &= Files::delFile($obj); ++ } ++ else if(is_dir($obj)) ++ { ++ $deleted &= Files::delFolder($obj, $recursive); ++ } ++ ++ } ++ } ++ $d->close(); ++ ++ } ++ ++ //$folder= $folder.'/thumbs'; ++ //var_dump($folder); ++ if(is_dir($folder)) ++ $deleted &= rmdir($folder); ++ else ++ $deleted &= false; ++ ++ Return $deleted; ++ } ++ ++ /** ++ * Append a / to the path if required. ++ * @param string $path the path ++ * @return string path with trailing / ++ */ ++ function fixPath($path) ++ { ++ //append a slash to the path if it doesn't exists. ++ if(!(substr($path,-1) == '/')) ++ $path .= '/'; ++ Return $path; ++ } ++ ++ /** ++ * Concat two paths together. Basically $pathA+$pathB ++ * @param string $pathA path one ++ * @param string $pathB path two ++ * @return string a trailing slash combinded path. ++ */ ++ function makePath($pathA, $pathB) ++ { ++ $pathA = Files::fixPath($pathA); ++ if(substr($pathB,0,1)=='/') ++ $pathB = substr($pathB,1); ++ Return Files::fixPath($pathA.$pathB); ++ } ++ ++ /** ++ * Similar to makePath, but the second parameter ++ * is not only a path, it may contain say a file ending. ++ * @param string $pathA the leading path ++ * @param string $pathB the ending path with file ++ * @return string combined file path. ++ */ ++ function makeFile($pathA, $pathB) ++ { ++ $pathA = Files::fixPath($pathA); ++ if(substr($pathB,0,1)=='/') ++ $pathB = substr($pathB,1); ++ ++ Return $pathA.$pathB; ++ } ++ ++ ++ /** ++ * Format the file size, limits to Mb. ++ * @param int $size the raw filesize ++ * @return string formated file size. ++ */ ++ function formatSize($size) ++ { ++ if($size < 1024) ++ return $size.' bytes'; ++ else if($size >= 1024 && $size < 1024*1024) ++ return sprintf('%01.2f',$size/1024.0).' Kb'; ++ else ++ return sprintf('%01.2f',$size/(1024.0*1024)).' Mb'; + } + } + +-?> +\ Pas de fin de ligne à la fin du fichier. ++?> +diff -u -r /ImageManager_20062020/Classes/ImageEditor.php ./Classes/ImageEditor.php +--- /ImageManager_20062020/Classes/ImageEditor.php 2006-06-20 22:17:34.000000000 +0200 ++++ ./Classes/ImageEditor.php 2006-12-20 19:34:11.000000000 +0100 +@@ -1,9 +1,9 @@ +- +- * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ ++ * @author Wei Zhuo ++ * @author Paul Moers - watermarking and replace code + several small enhancements ++ * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ + * @package ImageManager + */ + +@@ -11,8 +11,8 @@ + + /** + * Handles the basic image editing capbabilities. +- * @author $Author: matrix $ +- * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ ++ * @author Wei Zhuo ++ * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ + * @package ImageManager + * @subpackage Editor + */ +@@ -243,18 +243,18 @@ + //get unique filename just returns the filename, so + //we need to make the relative path again. + $newSaveFile = $this->makeRelative($relative, $newName); +- +- // forced new name? +- if ($oldSaveFile != $newSaveFile) +- { +- $this->forcedNewName = $newName; +- } +- else +- { +- $this->forcedNewName = false; +- } + } + ++ // forced new name? ++ if ($oldSaveFile != $newSaveFile) ++ { ++ $this->forcedNewName = $newName; ++ } ++ else ++ { ++ $this->forcedNewName = false; ++ } ++ + $newSaveFullpath = $this->manager->getFullPath($newSaveFile); + $img->save($newSaveFullpath, $values[0], $quality); + if(is_file($newSaveFullpath)) +@@ -582,4 +582,4 @@ + } + } + +-?> +\ Pas de fin de ligne à la fin du fichier. ++?> +diff -u -r /ImageManager_20062020/Classes/ImageManager.php ./Classes/ImageManager.php +--- /ImageManager_20062020/Classes/ImageManager.php 2006-06-20 22:17:34.000000000 +0200 ++++ ./Classes/ImageManager.php 2006-12-21 22:28:00.000000000 +0100 +@@ -1,17 +1,18 @@ +-getDirs(); +- if($path == '/') ++ if($path == '/' || $path == '') + Return true; + //check the path given in the url against the + //list of paths in the system. +@@ -430,6 +431,22 @@ + $path = Files::makePath($this->getBaseDir(),$relative); + $result = Files::copyFile($file['tmp_name'], $path, $file['name']); + ++ // constrain image size ++ if(!is_int($result)) ++ { ++ $img = Image_Transform::factory(IMAGE_CLASS); ++ $img->load($path . $result); ++ ++ // If maximum size is specified, constrain image to it. ++ if ($this->config['maxWidth'] > 0 && $this->config['maxHeight'] > 0 && ($img->img_x > $this->config['maxWidth'] || $img->img_y > $this->config['maxHeight'])) ++ { ++ $percentage = min($this->config['maxWidth']/$img->img_x, $this->config['maxHeight']/$img->img_y); ++ $img->scale($percentage); ++ } ++ $img->save($path . $result); ++ $img->free(); ++ } ++ + //no copy error + if(!is_int($result)) + { +@@ -674,4 +691,4 @@ + } + } + +-?> +\ Pas de fin de ligne à la fin du fichier. ++?> +diff -u -r /ImageManager_20062020/Classes/IM.php ./Classes/IM.php +--- /ImageManager_20062020/Classes/IM.php 2006-06-20 22:17:34.000000000 +0200 ++++ ./Classes/IM.php 2006-12-19 22:14:36.000000000 +0100 +@@ -25,7 +25,7 @@ + // | Authors: Peter Bowyer | + // +----------------------------------------------------------------------+ + // +-// $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ ++// $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ + // + // Image Transformation interface using command line ImageMagick + // +@@ -79,10 +79,14 @@ + */ + function _resize($new_x, $new_y) + { ++ // prevent illegal data ++ if (!is_numeric($new_x)) die("new X must be numeric"); ++ if (!is_numeric($new_y)) die("new Y must be numeric"); ++ + /*if (isset($this->command['resize'])) { + return PEAR::raiseError("You cannot scale or resize an image more than once without calling save or display", true); + }*/ +- $this->command['resize'] = "-geometry ${new_x}x${new_y}!"; ++ $this->command['resize'] = "-geometry {$new_x}x{$new_y}!"; + + $this->new_x = $new_x; + $this->new_y = $new_y; +@@ -98,6 +102,10 @@ + */ + function crop($crop_x, $crop_y, $crop_width, $crop_height) + { ++ if (!is_numeric($crop_x)) die("crop_x must be numeric"); ++ if (!is_numeric($crop_y)) die("crop_y must be numeric"); ++ if (!is_numeric($crop_width)) die("crop_width must be numeric"); ++ if (!is_numeric($crop_height)) die("crop_height must be numeric"); + $this->command['crop'] = "-crop {$crop_width}x{$crop_height}+{$crop_x}+{$crop_y}"; + } + +@@ -122,6 +130,7 @@ + */ + function rotate($angle, $options=null) + { ++ if (!is_numeric($angle)) die("angle must be numeric"); + if ('-' == $angle{0}) { + $angle = 360 - substr($angle, 1); + } +@@ -164,6 +173,13 @@ + } else { + $key = 'text'; + } ++ // test input params ++ if (!is_numeric($x)) die("x must be numeric"); ++ if (!is_numeric($y)) die("y must be numeric"); ++ // escape others ++ $font = escapeshellarg($font); ++ $color = escapeshellarg($color); ++ $text = escapeshellarg($text); + $this->command[$key] = "-font $font -fill $color -draw 'text $x,$y \"$text\"'"; + // Producing error: gs: not found gs: not found convert: Postscript delegate failed [No such file or directory]. + } // End addText +@@ -176,6 +192,7 @@ + * @return none + */ + function gamma($outputgamma=1.0) { ++ if (!is_numeric($outputgamma)) die("outputgamma must be numeric"); + $this->command['gamma'] = "-gamma $outputgamma"; + } + +@@ -190,6 +207,7 @@ + */ + function save($filename, $type='', $quality = 85) + { ++ if (!is_numeric($quality)) die("quality must be numeric"); + $type == '' ? $this->type : $type; + $cmd = '' . IMAGE_TRANSFORM_LIB_PATH . 'convert '; + $cmd .= implode(' ', $this->command) . " -quality $quality "; +@@ -210,6 +228,7 @@ + */ + function display($type = '', $quality = 75) + { ++ if (!is_numeric($quality)) die("quality must be numeric"); + if ($type == '') { + header('Content-type: image/' . $this->type); + passthru(IMAGE_TRANSFORM_LIB_PATH . 'convert ' . implode(' ', $this->command) . " -quality $quality " . escapeshellarg($this->image) . ' ' . strtoupper($this->type) . ":-"); +diff -u -r /ImageManager_20062020/Classes/Thumbnail.php ./Classes/Thumbnail.php +--- /ImageManager_20062020/Classes/Thumbnail.php 2006-06-20 22:17:34.000000000 +0200 ++++ ./Classes/Thumbnail.php 2006-12-16 22:38:13.000000000 +0100 +@@ -1,125 +1,125 @@ +-driver = Image_Transform::factory(IMAGE_CLASS); +- $this->width = $width; +- $this->height = $height; +- } +- +- /** +- * Create a thumbnail. +- * @param string $file the image for the thumbnail +- * @param string $thumbnail if not null, the thumbnail will be saved +- * as this parameter value. +- * @return boolean true if thumbnail is created, false otherwise +- */ +- function createThumbnail($file, $thumbnail=null) +- { +- if(!is_file($file)) +- Return false; +- +- //error_log('Creating Thumbs: '.$file); +- +- $this->driver->load($file); +- +- if($this->proportional) +- { +- $width = $this->driver->img_x; +- $height = $this->driver->img_y; +- +- if ($width > $height) +- $this->height = intval($this->width/$width*$height); +- else if ($height > $width) +- $this->width = intval($this->height/$height*$width); +- } +- +- $this->driver->resize($this->width, $this->height); +- +- if(is_null($thumbnail)) +- $this->save($file); +- else +- $this->save($thumbnail); +- +- +- $this->free(); +- +- if(is_file($thumbnail)) +- Return true; +- else +- Return false; +- } +- +- /** +- * Save the thumbnail file. +- * @param string $file file name to be saved as. +- */ +- function save($file) +- { +- $this->driver->save($file); +- } +- +- /** +- * Free up the graphic driver resources. +- */ +- function free() +- { +- $this->driver->free(); +- } ++class Thumbnail ++{ ++ /** ++ * Graphics driver, GD, NetPBM or ImageMagick. ++ */ ++ var $driver; ++ ++ /** ++ * Thumbnail default width. ++ */ ++ var $width = 96; ++ ++ /** ++ * Thumbnail default height. ++ */ ++ var $height = 96; ++ ++ /** ++ * Thumbnail default JPEG quality. ++ */ ++ var $quality = 85; ++ ++ /** ++ * Thumbnail is proportional ++ */ ++ var $proportional = true; ++ ++ /** ++ * Default image type is JPEG. ++ */ ++ var $type = 'jpeg'; ++ ++ /** ++ * Create a new Thumbnail instance. ++ * @param int $width thumbnail width ++ * @param int $height thumbnail height ++ */ ++ function Thumbnail($width=96, $height=96) ++ { ++ $this->driver = Image_Transform::factory(IMAGE_CLASS); ++ $this->width = $width; ++ $this->height = $height; ++ } ++ ++ /** ++ * Create a thumbnail. ++ * @param string $file the image for the thumbnail ++ * @param string $thumbnail if not null, the thumbnail will be saved ++ * as this parameter value. ++ * @return boolean true if thumbnail is created, false otherwise ++ */ ++ function createThumbnail($file, $thumbnail=null) ++ { ++ if(!is_file($file)) ++ Return false; ++ ++ //error_log('Creating Thumbs: '.$file); ++ ++ $this->driver->load($file); ++ ++ if($this->proportional) ++ { ++ $width = $this->driver->img_x; ++ $height = $this->driver->img_y; ++ ++ if ($width > $height) ++ $this->height = intval($this->width/$width*$height); ++ else if ($height > $width) ++ $this->width = intval($this->height/$height*$width); ++ } ++ ++ $this->driver->resize($this->width, $this->height); ++ ++ if(is_null($thumbnail)) ++ $this->save($file); ++ else ++ $this->save($thumbnail); ++ ++ ++ $this->free(); ++ ++ if(is_file($thumbnail)) ++ Return true; ++ else ++ Return false; ++ } ++ ++ /** ++ * Save the thumbnail file. ++ * @param string $file file name to be saved as. ++ */ ++ function save($file) ++ { ++ $this->driver->save($file); ++ } ++ ++ /** ++ * Free up the graphic driver resources. ++ */ ++ function free() ++ { ++ $this->driver->free(); ++ } + } + + +-?> +\ Pas de fin de ligne à la fin du fichier. ++?> +diff -u -r /ImageManager_20062020/config.inc.php ./config.inc.php +--- /ImageManager_20062020/config.inc.php 2006-06-20 22:17:32.000000000 +0200 ++++ ./config.inc.php 2006-12-20 19:39:39.000000000 +0100 +@@ -1,9 +1,9 @@ +- +- * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ ++ * @author Wei Zhuo ++ * @author Paul Moers - watermarking and replace code + several small enhancements ++ * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ + * @package ImageManager + */ + +@@ -16,7 +16,7 @@ + PHP must be able to create files in this directory. + Able to create directories is nice, but not necessary. + */ +-#$IMConfig['base_dir'] = '/var/www/FCKeditor/images/'; ++$IMConfig['base_dir'] = '/var/www/FCKeditor/images/'; + + /* + The URL to the above path, the web browser needs to be able to see it. +@@ -27,8 +27,7 @@ + in this directory and its subdirectories. + */ + $IMConfig['base_url'] = 'http://www.saulmade.nl/FCKeditor/images/'; +-//$IMConfig['base_dir'] = $_SERVER['DOCUMENT_ROOT'].$IMConfig['base_url']; +-$IMConfig['base_dir'] = '/home/saulmade.nl/www/FCKeditor/images/'; ++ + $IMConfig['server_name'] = $_SERVER['SERVER_NAME']; + + /* +@@ -152,10 +151,7 @@ + Specifying none will hide watermarking functionality. + */ + $IMConfig['watermarks'] = array ( +- "imageManager.png", +- "imageManager.jpg", +- "devshed.png", +- "natureWatermark.png" ++ "imageManager.png" + ); + + /* +@@ -194,4 +190,4 @@ + Image Editor temporary filename prefix. + */ + $IMConfig['tmp_prefix'] = '.editor_'; +-?> +\ Pas de fin de ligne à la fin du fichier. ++?> +diff -u -r /ImageManager_20062020/editorFrame.php ./editorFrame.php +--- /ImageManager_20062020/editorFrame.php 2006-06-20 22:17:32.000000000 +0200 ++++ ./editorFrame.php 2006-12-20 19:19:28.000000000 +0100 +@@ -1,9 +1,9 @@ +- +- * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ ++ * @author Wei Zhuo ++ * @author Paul Moers - watermarking and replace code + several small enhancements ++ * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ + * @package ImageManager + */ + +@@ -49,7 +49,7 @@ + + + + +- +\ Pas de fin de ligne à la fin du fichier. ++ +diff -u -r /ImageManager_20062020/editor.php ./editor.php +--- /ImageManager_20062020/editor.php 2006-06-20 22:17:32.000000000 +0200 ++++ ./editor.php 2006-12-17 14:53:34.000000000 +0100 +@@ -1,9 +1,9 @@ +- +- * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ ++ * @author Wei Zhuo ++ * @author Paul Moers - watermarking and replace code + several small enhancements ++ * @version $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ + * @package ImageManager + */ + +@@ -79,9 +79,9 @@ + + + + +- $dir) + { ?> + +- No Images Found + +
    +-
    ++ +   +- ++ +
    +
    +@@ -189,7 +189,7 @@ + + + +- ++ + | + + OK +@@ -219,32 +219,32 @@ + + + +
    +
    + +- >ReplaceReplace +- >WatermarkWatermark ++ >ReplaceReplace ++ >WatermarkWatermark + CropCrop + ResizeResize + RotateRotate +@@ -288,8 +288,8 @@ +
    +
    + +- ++ +
    +
    + +- +\ Pas de fin de ligne à la fin du fichier. ++ +diff -u -r /ImageManager_20062020/fckplugin.js ./fckplugin.js +--- /ImageManager_20062020/fckplugin.js 2006-06-20 22:17:32.000000000 +0200 ++++ ./fckplugin.js 2006-12-21 22:39:28.000000000 +0100 +@@ -8,6 +8,7 @@ + // PHP image manager http://www.zhuo.org/htmlarea/ + // ================================================ + // Revision: 1.0 Date: 06/03/2005 ++// $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ + // ================================================ + + +@@ -146,7 +147,8 @@ + im = FCK.CreateElement('IMG'); + } + +- // set image attributes ++ // set image attributes ++ setAttrib(im, "_fcksavedurl", param.f_url, true); + setAttrib(im, 'src', param.f_url, true); + setAttrib(im, 'alt', param.f_alt, true); + setAttrib(im, 'title', param.f_title, true); +@@ -174,7 +176,7 @@ + // Version 3.0 developed by Mihai Bazon. + // http://dynarch.com/mishoo + // +-// $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ ++// Id: dialog.js 26 2004-03-31 02:35:21Z Wei Zhuo + + // Though "Dialog" looks like an object, it isn't really an object. Instead + // it's just namespace for protecting global symbols. +diff -u -r /ImageManager_20062020/images.php ./images.php +--- /ImageManager_20062020/images.php 2006-06-20 22:17:32.000000000 +0200 ++++ ./images.php 2006-12-16 22:38:13.000000000 +0100 +@@ -1,8 +1,8 @@ +- $file) + { ?> +
    +- <? echo $entry; ?> - <? echo Files::formatSize($file['stat']['size']); ?> ++ <?php echo $entry; ?> - <?php echo Files::formatSize($file['stat']['size']); ?> +
    +- +- Trash +- +- Edit +- ++ ++ Trash ++ ++ Edit ++ +
    + +
    +- <? echo $dir['entry']; ?> ++ <?php echo $dir['entry']; ?> +
    +- Trash +- ++ Trash ++ +
    +- + + +- ++ + +
    Invalid base directory: config['base_dir']; ?>Invalid base directory: config['base_dir']; ?>
    +- +@@ -145,7 +145,7 @@ + hideMessage(); + var topDoc = window.top.document; + +- 0) + { selection.remove(0); } + +- selection.options[selection.length] = new Option("/",""); +- $fullpath) { ?> +- selection.options[selection.length] = new Option("",""); +- ++ selection.options[selection.length] = new Option("/",""); ++ $fullpath) { ?> ++ selection.options[selection.length] = new Option("",""); ++ + + for(var i = 0; i < selection.length; i++) + { +@@ -173,7 +173,7 @@ + break; + } + } +- ++ + } + + function editImage(image) +@@ -196,14 +196,14 @@ + + + +-isValidBase() == false) { drawErrorBase($manager); } ++isValidBase() == false) { drawErrorBase($manager); } + elseif(count($list[0]) > 0 || count($list[1]) > 0) { ?> + + +- +- ++ ++ + +
    +- ++ + +- +\ Pas de fin de ligne à la fin du fichier. ++ +diff -u -r /ImageManager_20062020/lang/fr.js ./lang/fr.js +--- /ImageManager_20062020/lang/fr.js 2006-06-20 22:17:46.000000000 +0200 ++++ ./lang/fr.js 2006-12-17 12:46:48.000000000 +0100 +@@ -1,7 +1,8 @@ + // I18N constants + + // LANG: "fr", ENCODING: UTF-8 +-// Author: ? ++// Author: Thierry Bothorel (update) ++// $Id: 20062020_20061221.diff,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ + // Updated for FCKeditor by: Paul Moers, http://fckplugins.saulmade.nl + + // FOR TRANSLATORS: +@@ -86,19 +87,19 @@ + "Padding:" : "Espacement:", + "Border:" : "Bordure:", + "Upload:" : "Télétransmission:", +- "File name was changed into " : "File name was changed into ", // not translated yet +- "start x coordinate" : "start x coordinate", // not translated yet +- "start y coordinate" : "start y coordinate", // not translated yet ++ "File name was changed into " : "Le nom du fichier a été changé en ", ++ "start x coordinate" : "début coordonnée x", ++ "start y coordinate" : "début coordonnée y", + "height" : "hauteur", + "width" : "longueur", + "angle" : "angle", + "opacity" : "opacité", +- "diagonal length" : "diagonal length", // not translated yet +- "Watermarking is disabled." : "Watermarking is disabled.", // not translated yet +- "No watermarks were found or all watermarks are to big for the target image." : "No watermarks were found or all watermarks are to big for the target image.", // not translated yet ++ "diagonal length" : "longueur diagonale", ++ "Watermarking is disabled." : "Filigranes désactivés.", ++ "No watermarks were found or all watermarks are to big for the target image." : "Aucun filigrane trouvé ou tous les filigranes sont trop grands pour cette image.", + "Please delete all files/folders inside the folder you wish to delete first." : "Veuillez tout d'abord supprimer tous les fichiers et répertoires contenus", + "Invalid folder name, please choose another folder name." : "Nom de répertoire invalide, veuillez choisir un autre nom", + "GIF format is not supported, image editing not supported." : "Format GIF non supporté, édition d'image non supportée", +- "Please do not close the window while uploading a new image! If you do, the original image gets deleted!" : "Please do not close the window while uploading a new image! If you do, the original image gets deleted!", // not translated yet +- "Error: Couldn't update editor window.\nAny image that was edited and saved will still be visible as the old version!\nPlease save and reload the editor content." : "Error: Couldn't update editor window.\nAny image that was edited and saved will still be visible as the old version!\nPlease save and reload the editor content." // not translated yet +-}; +\ Pas de fin de ligne à la fin du fichier. ++ "Please do not close the window while uploading a new image! If you do, the original image gets deleted!" : "Ne FERMEZ PAS CETTE FENETRE pendant l'envoi d'une nouvelle image sinon l'image originale sera quand même supprimée !", ++ "Error: Couldn't update editor window.\nAny image that was edited and saved will still be visible as the old version!\nPlease save and reload the editor content." : "Erreur: Impossible d'actualiser la fenêtre de l'éditeur.\nL'image qui a été éditée et sauvegardée apparaitra toujours comme non modifiée !\nVeuillez sauvegarder et recharger le contenu de l'éditeur." ++}; +diff -u -r /ImageManager_20062020/manager.php ./manager.php +--- /ImageManager_20062020/manager.php 2006-06-20 22:17:32.000000000 +0200 ++++ ./manager.php 2006-12-17 15:57:17.000000000 +0100 +@@ -1,8 +1,8 @@ +- + /*"; +- var base_url = "getBaseURL(); ?>"; +- var server_name = ""; ++ var thumbdir = ""; ++ var base_url = "getBaseURL(); ?>"; ++ var server_name = ""; + +- window.resizeTo(600, 460); ++ window.resizeTo(900, 500); + + if(window.opener.ImageManager && window.opener.ImageManager.I18N) + { +@@ -71,14 +71,14 @@ + + + Directory Up +- ++ + New Folder +- ++ + + +
    +@@ -105,7 +105,7 @@ + + + +- ++ + + + +@@ -115,9 +115,9 @@ + +
    + +- ++ + +- ++ + + + + + +- +\ Pas de fin de ligne à la fin du fichier. ++ +diff -u -r /ImageManager_20062020/thumbs.php ./thumbs.php +--- /ImageManager_20062020/thumbs.php 2006-06-20 22:17:32.000000000 +0200 ++++ ./thumbs.php 2006-12-16 22:38:13.000000000 +0100 +@@ -1,82 +1,82 @@ +-getBaseDir(),$image); +- +-//not a file, so exit +-if(!is_file($fullpath)) +- exit(); +- +-$imgInfo = @getImageSize($fullpath); +- +-//Not an image, send default thumbnail +-if(!is_array($imgInfo)) +-{ +- //show the default image, otherwise we quit! +- $default = $manager->getDefaultThumb(); +- if($default) +- { +- header('Location: '.$default); +- exit(); +- } +-} +-//if the image is less than the thumbnail dimensions +-//send the original image as thumbnail +-if ($imgInfo[0] <= $IMConfig['thumbnail_width'] +- && $imgInfo[1] <= $IMConfig['thumbnail_height']) +- { +- header('Location: '.$manager->getFileURL($image)); +- exit(); +- } +- +-//Check for thumbnails +-$thumbnail = $manager->getThumbName($fullpath); +-if(is_file($thumbnail)) +-{ +- //if the thumbnail is newer, send it +- if(filemtime($thumbnail) >= filemtime($fullpath)) +- { +- header('Location: '.$manager->getThumbURL($image)); +- exit(); +- } +-} +- +-//creating thumbnails +-$thumbnailer = new Thumbnail($IMConfig['thumbnail_width'],$IMConfig['thumbnail_height']); +-$thumbnailer->createThumbnail($fullpath, $thumbnail); +- +-//Check for NEW thumbnails +-if(is_file($thumbnail)) +-{ +- //send the new thumbnail +- header('Location: '.$manager->getThumbURL($image)); +- exit(); +-} +-else +-{ +- //show the default image, otherwise we quit! +- $default = $manager->getDefaultThumb(); ++require_once('config.inc.php'); ++require_once('Classes/ImageManager.php'); ++require_once('Classes/Thumbnail.php'); ++ ++//check for img parameter in the url ++if(!isset($_GET['img'])) ++ exit(); ++ ++ ++$manager = new ImageManager($IMConfig); ++ ++//get the image and the full path to the image ++$image = rawurldecode($_GET['img']); ++$fullpath = Files::makeFile($manager->getBaseDir(),$image); ++ ++//not a file, so exit ++if(!is_file($fullpath)) ++ exit(); ++ ++$imgInfo = @getImageSize($fullpath); ++ ++//Not an image, send default thumbnail ++if(!is_array($imgInfo)) ++{ ++ //show the default image, otherwise we quit! ++ $default = $manager->getDefaultThumb(); ++ if($default) ++ { ++ header('Location: '.$default); ++ exit(); ++ } ++} ++//if the image is less than the thumbnail dimensions ++//send the original image as thumbnail ++if ($imgInfo[0] <= $IMConfig['thumbnail_width'] ++ && $imgInfo[1] <= $IMConfig['thumbnail_height']) ++ { ++ header('Location: '.$manager->getFileURL($image)); ++ exit(); ++ } ++ ++//Check for thumbnails ++$thumbnail = $manager->getThumbName($fullpath); ++if(is_file($thumbnail)) ++{ ++ //if the thumbnail is newer, send it ++ if(filemtime($thumbnail) >= filemtime($fullpath)) ++ { ++ header('Location: '.$manager->getThumbURL($image)); ++ exit(); ++ } ++} ++ ++//creating thumbnails ++$thumbnailer = new Thumbnail($IMConfig['thumbnail_width'],$IMConfig['thumbnail_height']); ++$thumbnailer->createThumbnail($fullpath, $thumbnail); ++ ++//Check for NEW thumbnails ++if(is_file($thumbnail)) ++{ ++ //send the new thumbnail ++ header('Location: '.$manager->getThumbURL($image)); ++ exit(); ++} ++else ++{ ++ //show the default image, otherwise we quit! ++ $default = $manager->getDefaultThumb(); + if($default) + header('Location: '.$default); + } +-?> +\ Pas de fin de ligne à la fin du fichier. ++?> diff --git a/fckeditor/editor/plugins/ImageManager/ChangeLog b/fckeditor/editor/plugins/ImageManager/ChangeLog new file mode 100644 index 0000000..dff2a68 --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/ChangeLog @@ -0,0 +1,156 @@ +2006-12-21 Thierry Bothorel + + * Classes/ImageManager.php (1.4, Release-20061221): Bug fix: + missing include declaration Transform.php (PHP Fatal error: + Undefined class name 'image_transform' in ImageManager.php on line + 436) + +2006-12-21 Thierry Bothorel + + * Classes/ImageManager.php (1.3): Moved and extended contrain to + config size on upload to ImageManager.php (Paul + Moers) + +2006-12-21 Thierry Bothorel + + * fckplugin.js (1.4, Release-20061221): Bug fix: When picking + another image in the manager and confirming, the image in the + editorArea changed, but the src attribute didn't. The attribute + '_fcksavedurl' needed to be set too. (Paul Moers) + +2006-12-20 Thierry Bothorel + + * Classes/ImageEditor.php (1.3, Release-20061221, + Release-20061220): Bug fix: "PHP Notice: Undefined property: + forcedNewName" if "allow_overwrite" is true in config.inc.php (Alan + Pinstein ). + +2006-12-20 Thierry Bothorel + + * editorFrame.php (1.7, Release-20061221, Release-20061220): Bug + fix: watermarks trying to be loaded even if there are none defined + in config.inc.php (Undefined offset: 0) (Alan Pinstein + ). + +2006-12-19 Thierry Bothorel + + * Classes/IM.php (1.2, Release-20061221, Release-20061220): Escape + shell arguments for ImageMagick driver (to prevent security + issues). (Alan Pinstein ) + +2006-12-19 Thierry Bothorel + + * Classes/IM.php (1.1): initial Commit = Saulmade 20060620 version + +2006-12-19 Thierry Bothorel + + * editorFrame.php (1.6): Bug fix: PHP warning when opening an image + for editing. (Alan Pinstein + +2006-12-18 Thierry Bothorel + + * editorFrame.php (1.5): Bug fix: "Editor hangs on any rotating" + and "editor displays ghost image overlay" if watermark images are + defined in config.inc.php AND any of these images are missing in + the destination folder. + +2006-12-17 Thierry Bothorel + + * fckplugin.js (1.3, Release-20061220, Release-20061217): Restoring + Wei Zhuo Id + +2006-12-17 Thierry Bothorel + + * manager.php (1.4, Release-20061221, Release-20061220, + Release-20061217): window upgraded to 900pix wide to display all + content with non english strings and FF 1.5.0.8 + +2006-12-17 Thierry Bothorel + + * config.inc.php (1.4, Release-20061221, Release-20061220, + Release-20061217): clean-up for release + +2006-12-17 Thierry Bothorel + + * assets/editorFrame.js (1.2): File erroneously comitted + +2006-12-17 Thierry Bothorel + + * editor.php (1.3, Release-20061221, Release-20061220, + Release-20061217): Bug fix: editor hangs displaying 'rotating' if + no rotate setting entered. Added default '0' angle value. + +2006-12-17 Thierry Bothorel + + * editorFrame.php (1.4, Release-20061217): Bug fix: "tools not + displayed if action = flip". "tools_flip block" does not exist + +2006-12-17 Thierry Bothorel + + * assets/editorFrame.js (1.1, Saulmade-20060620): initial Commit = + Saulmade 20060620 version + +2006-12-17 Thierry Bothorel + + * lang/fr.js (1.2, Release-20061221, Release-20061220, + Release-20061217): Added missing french translations + +2006-12-17 Thierry Bothorel + + * lang/fr.js (1.1, Saulmade-20060620): initial Commit = Saulmade + 20060620 version + +2006-12-17 Thierry Bothorel + + * config.inc.php (1.3): Added a default "imageManager.png" + watermark image in /img/watermark/ so that at least on example + being provided with this plugin. + +2006-12-17 Thierry Bothorel + + * img/watermark/imageManager.png (1.2, Release-20061221, + Release-20061220, Release-20061217), img/watermark/imageManager.png + (1.1): Ajout de l'image watermark par défaut (pour qu'il y ait au + moins un exemple dans le plugin à l'installation) + +2006-12-17 Thierry Bothorel + + * editorFrame.php (1.3): - Bug fix: "syntax error, unexpected $end" + (no space after "php" in " dirname($_GET['img']) + +2006-12-16 Thierry Bothorel + + * config.inc.php (1.1), editor.php (1.1), editorFrame.php (1.1), + fckplugin.js (1.1), images.php (1.1), manager.php (1.1), thumbs.php + (1.1), Classes/Files.php (1.1), Classes/ImageEditor.php (1.1), + Classes/ImageManager.php (1.1), Classes/Thumbnail.php (1.1), + Classes/api.watermark.php (1.1) (utags: Saulmade-20060620): initial + Commit = Saulmade 20060620 version + diff --git a/fckeditor/editor/plugins/ImageManager/Classes/Files.php b/fckeditor/editor/plugins/ImageManager/Classes/Files.php new file mode 100644 index 0000000..9be380d --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/Classes/Files.php @@ -0,0 +1,215 @@ +read())) + { + if ($entry != '.' && $entry != '..') + { + $obj = Files::fixPath($folder).$entry; + //var_dump($obj); + if (is_file($obj)) + { + $deleted &= Files::delFile($obj); + } + else if(is_dir($obj)) + { + $deleted &= Files::delFolder($obj, $recursive); + } + + } + } + $d->close(); + + } + + //$folder= $folder.'/thumbs'; + //var_dump($folder); + if(is_dir($folder)) + $deleted &= rmdir($folder); + else + $deleted &= false; + + Return $deleted; + } + + /** + * Append a / to the path if required. + * @param string $path the path + * @return string path with trailing / + */ + function fixPath($path) + { + //append a slash to the path if it doesn't exists. + if(!(substr($path,-1) == '/')) + $path .= '/'; + Return $path; + } + + /** + * Concat two paths together. Basically $pathA+$pathB + * @param string $pathA path one + * @param string $pathB path two + * @return string a trailing slash combinded path. + */ + function makePath($pathA, $pathB) + { + $pathA = Files::fixPath($pathA); + if(substr($pathB,0,1)=='/') + $pathB = substr($pathB,1); + Return Files::fixPath($pathA.$pathB); + } + + /** + * Similar to makePath, but the second parameter + * is not only a path, it may contain say a file ending. + * @param string $pathA the leading path + * @param string $pathB the ending path with file + * @return string combined file path. + */ + function makeFile($pathA, $pathB) + { + $pathA = Files::fixPath($pathA); + if(substr($pathB,0,1)=='/') + $pathB = substr($pathB,1); + + Return $pathA.$pathB; + } + + + /** + * Format the file size, limits to Mb. + * @param int $size the raw filesize + * @return string formated file size. + */ + function formatSize($size) + { + if($size < 1024) + return $size.' bytes'; + else if($size >= 1024 && $size < 1024*1024) + return sprintf('%01.2f',$size/1024.0).' Kb'; + else + return sprintf('%01.2f',$size/(1024.0*1024)).' Mb'; + } +} + +?> diff --git a/fckeditor/editor/plugins/ImageManager/Classes/GD.php b/fckeditor/editor/plugins/ImageManager/Classes/GD.php new file mode 100644 index 0000000..31181fe --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/Classes/GD.php @@ -0,0 +1,508 @@ + +** Filename......: GD.php +** Last changed..: 30 Aug 2003 +** Notes.........: Orginal is from PEAR +**/ +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Authors: Peter Bowyer | +// | Alan Knowles | +// +----------------------------------------------------------------------+ +// +// Usage : +// $img = new Image_Transform_GD(); +// $angle = -78; +// $img->load('magick.png'); +// +// if($img->rotate($angle,array('autoresize'=>true,'color_mask'=>array(255,0,0)))){ +// $img->addText(array('text'=>"Rotation $angle",'x'=>0,'y'=>100,'font'=>'/usr/share/fonts/default/TrueType/cogb____.ttf')); +// $img->display(); +// } else { +// echo "Error"; +// } +// +// +// $Id: GD.php,v 1.1.1.1 2009/09/17 20:08:59 matrix Exp $ +// +// Image Transformation interface using the GD library +// + +require_once "Transform.php"; + +Class Image_Transform_Driver_GD extends Image_Transform +{ + /** + * Holds the image file for manipulation + */ + var $imageHandle = ''; + + /** + * Holds the original image file + */ + var $old_image = ''; + + /** + * Check settings + * + * @return mixed true or or a PEAR error object on error + * + * @see PEAR::isError() + */ + function Image_Transform_GD() + { + return; + } // End function Image + + /** + * Load image + * + * @param string filename + * + * @return mixed none or a PEAR error object on error + * @see PEAR::isError() + */ + function load($image) + { + $this->uid = md5($_SERVER['REMOTE_ADDR']); + $this->image = $image; + $this->_get_image_details($image); + $functionName = 'ImageCreateFrom' . $this->type; + if(function_exists($functionName)) + { + $this->imageHandle = $functionName($this->image); + } + } // End load + + /** + * addText + * + * @param array options Array contains options + * array( + * 'text' The string to draw + * 'x' Horizontal position + * 'y' Vertical Position + * 'Color' Font color + * 'font' Font to be used + * 'size' Size of the fonts in pixel + * 'resize_first' Tell if the image has to be resized + * before drawing the text + * ) + * + * @return none + * @see PEAR::isError() + */ + function addText($params) + { + $default_params = array( + 'text' => 'This is Text', + 'x' => 10, + 'y' => 20, + 'color' => array(255,0,0), + 'font' => 'Arial.ttf', + 'size' => '12', + 'angle' => 0, + 'resize_first' => false // Carry out the scaling of the image before annotation? Not used for GD + ); + $params = array_merge($default_params, $params); + extract($params); + + if( !is_array($color) ){ + if ($color[0]=='#'){ + $this->colorhex2colorarray( $color ); + } else { + include_once('Image/Transform/Driver/ColorsDefs.php'); + $color = isset($colornames[$color])?$colornames[$color]:false; + } + } + + $c = imagecolorresolve ($this->imageHandle, $color[0], $color[1], $color[2]); + + if ('ttf' == substr($font, -3)) { + ImageTTFText($this->imageHandle, $size, $angle, $x, $y, $c, $font, $text); + } else { + ImagePSText($this->imageHandle, $size, $angle, $x, $y, $c, $font, $text); + } + return true; + } // End addText + + + /** + * Rotate image by the given angle + * Uses a fast rotation algorythm for custom angles + * or lines copy for multiple of 90 degrees + * + * @param int $angle Rotation angle + * @param array $options array( 'autoresize'=>true|false, + * 'color_mask'=>array(r,g,b), named color or #rrggbb + * ) + * @author Pierre-Alain Joye + * @return mixed none or a PEAR error object on error + * @see PEAR::isError() + */ + function rotate($angle, $options=null) + { + if(function_exists('imagerotate') && false) { + $white = imagecolorallocate ($this->imageHandle, 255, 255, 255); + $this->imageHandle = imagerotate($this->imageHandle, $angle, $white); + return true; + } + + if ( $options==null ){ + $autoresize = true; + $color_mask = array(255,255,0); + } else { + extract( $options ); + } + + while ($angle <= -45) { + $angle += 360; + } + while ($angle > 270) { + $angle -= 360; + } + + $t = deg2rad($angle); + + if( !is_array($color_mask) ){ + if ($color[0]=='#'){ + $this->colorhex2colorarray( $color_mask ); + } else { + include_once('Image/Transform/Driver/ColorDefs.php'); + $color = isset($colornames[$color_mask])?$colornames[$color_mask]:false; + } + } + + // Do not round it, too much lost of quality + $cosT = cos($t); + $sinT = sin($t); + + $img =& $this->imageHandle; + + $width = $max_x = $this->img_x; + $height = $max_y = $this->img_y; + $min_y = 0; + $min_x = 0; + + $x1 = round($max_x/2,0); + $y1 = round($max_y/2,0); + + if ( $autoresize ){ + $t = abs($t); + $a = round($angle,0); + switch((int)($angle)){ + case 0: + $width2 = $width; + $height2 = $height; + break; + case 90: + $width2 = $height; + $height2 = $width; + break; + case 180: + $width2 = $width; + $height2 = $height; + break; + case 270: + $width2 = $height; + $height2 = $width; + break; + default: + $width2 = (int)(abs(sin($t) * $height + cos($t) * $width)); + $height2 = (int)(abs(cos($t) * $height+sin($t) * $width)); + } + + $width2 -= $width2%2; + $height2 -= $height2%2; + + $d_width = abs($width - $width2); + $d_height = abs($height - $height2); + $x_offset = $d_width/2; + $y_offset = $d_height/2; + $min_x2 = -abs($x_offset); + $min_y2 = -abs($y_offset); + $max_x2 = $width2; + $max_y2 = $height2; + } + + if(function_exists('ImageCreateTrueColor')){ + $img2 =ImageCreateTrueColor($width2,$height2); + } else { + $img2 =ImageCreate($width2,$height2); + } + + + if ( !is_resource($img2) ){ + return false;/*PEAR::raiseError('Cannot create buffer for the rotataion.', + null, PEAR_ERROR_TRIGGER, E_USER_NOTICE);*/ + } + + $this->img_x = $width2; + $this->img_y = $height2; + + + imagepalettecopy($img2,$img); + + $mask = imagecolorresolve($img2,$color_mask[0],$color_mask[1],$color_mask[2]); + + // use simple lines copy for axes angles + switch((int)($angle)){ + case 0: + imagefill ($img2, 0, 0,$mask); + for ($y=0; $y < $max_y; $y++) { + for ($x = $min_x; $x < $max_x; $x++){ + $c = @imagecolorat ( $img, $x, $y); + imagesetpixel($img2,$x+$x_offset,$y+$y_offset,$c); + } + } + break; + case 90: + imagefill ($img2, 0, 0,$mask); + for ($x = $min_x; $x < $max_x; $x++){ + for ($y=$min_y; $y < $max_y; $y++) { + $c = imagecolorat ( $img, $x, $y); + imagesetpixel($img2,$max_y-$y-1,$x,$c); + } + } + break; + case 180: + imagefill ($img2, 0, 0,$mask); + for ($y=0; $y < $max_y; $y++) { + for ($x = $min_x; $x < $max_x; $x++){ + $c = @imagecolorat ( $img, $x, $y); + imagesetpixel($img2, $max_x2-$x-1, $max_y2-$y-1, $c); + } + } + break; + case 270: + imagefill ($img2, 0, 0,$mask); + for ($y=0; $y < $max_y; $y++) { + for ($x = $max_x; $x >= $min_x; $x--){ + $c = @imagecolorat ( $img, $x, $y); + imagesetpixel($img2,$y,$max_x-$x-1,$c); + } + } + break; + // simple reverse rotation algo + default: + $i=0; + for ($y = $min_y2; $y < $max_y2; $y++){ + + // Algebra :) + $x2 = round((($min_x2-$x1) * $cosT) + (($y-$y1) * $sinT + $x1),0); + $y2 = round((($y-$y1) * $cosT - ($min_x2-$x1) * $sinT + $y1),0); + + for ($x = $min_x2; $x < $max_x2; $x++){ + + // Check if we are out of original bounces, if we are + // use the default color mask + if ( $x2>=0 && $x2<$max_x && $y2>=0 && $y2<$max_y ){ + $c = imagecolorat ( $img, $x2, $y2); + } else { + $c = $mask; + } + imagesetpixel($img2,$x+$x_offset,$y+$y_offset,$c); + + // round verboten! + $x2 += $cosT; + $y2 -= $sinT; + } + } + break; + } + $this->old_image = $this->imageHandle; + $this->imageHandle = $img2; + return true; + } + + + /** + * Resize Action + * + * For GD 2.01+ the new copyresampled function is used + * It uses a bicubic interpolation algorithm to get far + * better result. + * + * @param $new_x int new width + * @param $new_y int new height + * + * @return true on success or pear error + * @see PEAR::isError() + */ + function _resize($new_x, $new_y) { + if ($this->resized === true) { + return false; /*PEAR::raiseError('You have already resized the image without saving it. Your previous resizing will be overwritten', null, PEAR_ERROR_TRIGGER, E_USER_NOTICE);*/ + } + if(function_exists('ImageCreateTrueColor')){ + $new_img =ImageCreateTrueColor($new_x,$new_y); + } else { + $new_img =ImageCreate($new_x,$new_y); + } + if(function_exists('ImageCopyResampled')){ + ImageCopyResampled($new_img, $this->imageHandle, 0, 0, 0, 0, $new_x, $new_y, $this->img_x, $this->img_y); + } else { + ImageCopyResized($new_img, $this->imageHandle, 0, 0, 0, 0, $new_x, $new_y, $this->img_x, $this->img_y); + } + $this->old_image = $this->imageHandle; + $this->imageHandle = $new_img; + $this->resized = true; + + $this->new_x = $new_x; + $this->new_y = $new_y; + return true; + } + + /** + * Crop the image + * + * @param int $crop_x left column of the image + * @param int $crop_y top row of the image + * @param int $crop_width new cropped image width + * @param int $crop_height new cropped image height + */ + function crop($new_x, $new_y, $new_width, $new_height) + { + if(function_exists('ImageCreateTrueColor')){ + $new_img =ImageCreateTrueColor($new_width,$new_height); + } else { + $new_img =ImageCreate($new_width,$new_height); + } + if(function_exists('ImageCopyResampled')){ + ImageCopyResampled($new_img, $this->imageHandle, 0, 0, $new_x, $new_y,$new_width,$new_height,$new_width,$new_height); + } else { + ImageCopyResized($new_img, $this->imageHandle, 0, 0, $new_x, $new_y, $new_width,$new_height,$new_width,$new_height); + } + $this->old_image = $this->imageHandle; + $this->imageHandle = $new_img; + $this->resized = true; + + $this->new_x = $new_x; + $this->new_y = $new_y; + return true; + } + + /** + * Flip the image horizontally or vertically + * + * @param boolean $horizontal true if horizontal flip, vertical otherwise + */ + function flip($horizontal) + { + if(!$horizontal) { + $this->rotate(180); + } + + $width = imagesx($this->imageHandle); + $height = imagesy($this->imageHandle); + + for ($j = 0; $j < $height; $j++) { + $left = 0; + $right = $width-1; + + + while ($left < $right) { + //echo " j:".$j." l:".$left." r:".$right."\n
    "; + $t = imagecolorat($this->imageHandle, $left, $j); + imagesetpixel($this->imageHandle, $left, $j, imagecolorat($this->imageHandle, $right, $j)); + imagesetpixel($this->imageHandle, $right, $j, $t); + $left++; $right--; + } + + } + + return true; + } + + + /** + * Adjust the image gamma + * + * @param float $outputgamma + * + * @return none + */ + function gamma($outputgamma=1.0) { + ImageGammaCorrect($this->imageHandle, 1.0, $outputgamma); + } + + /** + * Save the image file + * + * @param $filename string the name of the file to write to + * @param $quality int output DPI, default is 85 + * @param $types string define the output format, default + * is the current used format + * + * @return none + */ + function save($filename, $type = '', $quality = 85) + { + $type = $type==''? $this->type : $type; + $functionName = 'image' . $type; + + if(function_exists($functionName)) + { + $this->old_image = $this->imageHandle; + if($type=='jpeg') + $functionName($this->imageHandle, $filename, $quality); + else + $functionName($this->imageHandle, $filename); + $this->imageHandle = $this->old_image; + $this->resized = false; + } + } // End save + + + /** + * Display image without saving and lose changes + * + * @param string type (JPG,PNG...); + * @param int quality 75 + * + * @return none + */ + function display($type = '', $quality = 75) + { + if ($type != '') { + $this->type = $type; + } + $functionName = 'Image' . $this->type; + if(function_exists($functionName)) + { + header('Content-type: image/' . strtolower($this->type)); + $functionName($this->imageHandle, '', $quality); + $this->imageHandle = $this->old_image; + $this->resized = false; + ImageDestroy($this->old_image); + $this->free(); + } + } + + /** + * Destroy image handle + * + * @return none + */ + function free() + { + if ($this->imageHandle){ + ImageDestroy($this->imageHandle); + } + } + +} // End class ImageGD +?> diff --git a/fckeditor/editor/plugins/ImageManager/Classes/IM.php b/fckeditor/editor/plugins/ImageManager/Classes/IM.php new file mode 100644 index 0000000..594d78c --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/Classes/IM.php @@ -0,0 +1,253 @@ + +** Filename......: IM.php +** Last changed..: 30 Aug 2003 +** Notes.........: Orginal is from PEAR +**/ + +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Authors: Peter Bowyer | +// +----------------------------------------------------------------------+ +// +// $Id: IM.php,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ +// +// Image Transformation interface using command line ImageMagick +// + +require_once "Transform.php"; + +Class Image_Transform_Driver_IM extends Image_Transform +{ + /** + * associative array commands to be executed + * @var array + */ + var $command = array(); + + /** + * + * + */ + function Image_Transform_Driver_IM() + { + return true; + } // End Image_IM + + /** + * Load image + * + * @param string filename + * + * @return mixed none or a PEAR error object on error + * @see PEAR::isError() + */ + function load($image) + { + + $this->uid = md5($_SERVER['REMOTE_ADDR']); + /*if (!file_exists($image)) { + return PEAR::raiseError('The image file ' . $image . ' does\'t exist', true); + }*/ + $this->image = $image; + $this->_get_image_details($image); + } // End load + + /** + * Resize Action + * + * @param int new_x new width + * @param int new_y new height + * + * @return none + * @see PEAR::isError() + */ + function _resize($new_x, $new_y) + { + // prevent illegal data + if (!is_numeric($new_x)) die("new X must be numeric"); + if (!is_numeric($new_y)) die("new Y must be numeric"); + + /*if (isset($this->command['resize'])) { + return PEAR::raiseError("You cannot scale or resize an image more than once without calling save or display", true); + }*/ + $this->command['resize'] = "-geometry {$new_x}x{$new_y}!"; + + $this->new_x = $new_x; + $this->new_y = $new_y; + } // End resize + + /** + * Crop the image + * + * @param int $crop_x left column of the image + * @param int $crop_y top row of the image + * @param int $crop_width new cropped image width + * @param int $crop_height new cropped image height + */ + function crop($crop_x, $crop_y, $crop_width, $crop_height) + { + if (!is_numeric($crop_x)) die("crop_x must be numeric"); + if (!is_numeric($crop_y)) die("crop_y must be numeric"); + if (!is_numeric($crop_width)) die("crop_width must be numeric"); + if (!is_numeric($crop_height)) die("crop_height must be numeric"); + $this->command['crop'] = "-crop {$crop_width}x{$crop_height}+{$crop_x}+{$crop_y}"; + } + + /** + * Flip the image horizontally or vertically + * + * @param boolean $horizontal true if horizontal flip, vertical otherwise + */ + function flip($horizontal) + { + if($horizontal) + $this->command['flop'] = "-flop"; + else + $this->command['flip'] = "-flip"; + } + /** + * rotate + * + * @param int angle rotation angle + * @param array options no option allowed + * + */ + function rotate($angle, $options=null) + { + if (!is_numeric($angle)) die("angle must be numeric"); + if ('-' == $angle{0}) { + $angle = 360 - substr($angle, 1); + } + $this->command['rotate'] = "-rotate $angle"; + } // End rotate + + /** + * addText + * + * @param array options Array contains options + * array( + * 'text' The string to draw + * 'x' Horizontal position + * 'y' Vertical Position + * 'Color' Font color + * 'font' Font to be used + * 'size' Size of the fonts in pixel + * 'resize_first' Tell if the image has to be resized + * before drawing the text + * ) + * + * @return none + * @see PEAR::isError() + */ + function addText($params) + { + $default_params = array( + 'text' => 'This is Text', + 'x' => 10, + 'y' => 20, + 'color' => 'red', + 'font' => 'Arial.ttf', + 'resize_first' => false // Carry out the scaling of the image before annotation? + ); + $params = array_merge($default_params, $params); + extract($params); + if (true === $resize_first) { + // Set the key so that this will be the last item in the array + $key = 'ztext'; + } else { + $key = 'text'; + } + // test input params + if (!is_numeric($x)) die("x must be numeric"); + if (!is_numeric($y)) die("y must be numeric"); + // escape others + $font = escapeshellarg($font); + $color = escapeshellarg($color); + $text = escapeshellarg($text); + $this->command[$key] = "-font $font -fill $color -draw 'text $x,$y \"$text\"'"; + // Producing error: gs: not found gs: not found convert: Postscript delegate failed [No such file or directory]. + } // End addText + + /** + * Adjust the image gamma + * + * @param float $outputgamma + * + * @return none + */ + function gamma($outputgamma=1.0) { + if (!is_numeric($outputgamma)) die("outputgamma must be numeric"); + $this->command['gamma'] = "-gamma $outputgamma"; + } + + /** + * Save the image file + * + * @param $filename string the name of the file to write to + * @param $quality quality image dpi, default=75 + * @param $type string (JPG,PNG...) + * + * @return none + */ + function save($filename, $type='', $quality = 85) + { + if (!is_numeric($quality)) die("quality must be numeric"); + $type == '' ? $this->type : $type; + $cmd = '' . IMAGE_TRANSFORM_LIB_PATH . 'convert '; + $cmd .= implode(' ', $this->command) . " -quality $quality "; + $cmd .= '"'.($this->image) . '" "' . ($filename) . '" 2>&1'; + + //$cmd = str_replace('/', '\\', $cmd); + //echo($cmd.'
    '); + exec($cmd,$retval); + } // End save + + /** + * Display image without saving and lose changes + * + * @param string type (JPG,PNG...); + * @param int quality 75 + * + * @return none + */ + function display($type = '', $quality = 75) + { + if (!is_numeric($quality)) die("quality must be numeric"); + if ($type == '') { + header('Content-type: image/' . $this->type); + passthru(IMAGE_TRANSFORM_LIB_PATH . 'convert ' . implode(' ', $this->command) . " -quality $quality " . escapeshellarg($this->image) . ' ' . strtoupper($this->type) . ":-"); + } else { + header('Content-type: image/' . $type); + passthru(IMAGE_TRANSFORM_LIB_PATH . 'convert ' . implode(' ', $this->command) . " -quality $quality " . escapeshellarg($this->image) . ' ' . strtoupper($type) . ":-"); + } + } + + + /** + * Destroy image handle + * + * @return none + */ + function free() + { + return true; + } + +} // End class ImageIM +?> diff --git a/fckeditor/editor/plugins/ImageManager/Classes/ImageEditor.php b/fckeditor/editor/plugins/ImageManager/Classes/ImageEditor.php new file mode 100644 index 0000000..04eb3de --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/Classes/ImageEditor.php @@ -0,0 +1,585 @@ + - watermarking and replace code + several small enhancements + * @version $Id: ImageEditor.php,v 1.1.1.1 2009/09/17 20:08:59 matrix Exp $ + * @package ImageManager + */ + +require_once('Transform.php'); + +/** + * Handles the basic image editing capbabilities. + * @author Wei Zhuo + * @version $Id: ImageEditor.php,v 1.1.1.1 2009/09/17 20:08:59 matrix Exp $ + * @package ImageManager + * @subpackage Editor + */ +class ImageEditor +{ + /** + * ImageManager instance. + */ + var $manager; + + /** + * user based on IP address + */ + var $_uid; + + /** + * tmp file storage time. + */ + var $lapse_time =900; //15 mins + + var $filesaved = 0; + + /** + * Create a new ImageEditor instance. Editing requires a + * tmp file, which is saved in the current directory where the + * image is edited. The tmp file is assigned by md5 hash of the + * user IP address. This hashed is used as an ID for cleaning up + * the tmp files. In addition, any tmp files older than the + * the specified period will be deleted. + * @param ImageManager $manager the image manager, we need this + * for some file and path handling functions. + */ + function ImageEditor($manager) + { + $this->manager = $manager; + $this->_uid = md5($_SERVER['REMOTE_ADDR']); + } + + /** + * Did we save a file? + * @return int 1 if the file was saved sucessfully, + * 0 no save operation, -1 file save error. + */ + function isFileSaved() + { + Return $this->filesaved; + } + + /** + * Process the image, if not action, just display the image. + * @return array with image information, empty array if not an image. + * array('src'=>'url of the image', 'dimensions'=>'width="xx" height="yy"', + * 'file'=>'image file, relative', 'fullpath'=>'full path to the image'); + */ + function processImage($uploadedRelative) + { + if (isset($uploadedRelative) && $uploadedRelative != "") + { + $relative = $uploadedRelative; + } + elseif(isset($_GET['img'])) + { + $relative = rawurldecode($_GET['img']); + } + else + { + Return array(); + } + + $imgURL = $this->manager->getFileURL($relative); + $fullpath = $this->manager->getFullPath($relative); + + $imgInfo = @getImageSize($fullpath); + if(!is_array($imgInfo)) + Return array(); + + $action = $this->getAction(); + + if(!is_null($action)) + { + $image = $this->processAction($action, $relative, $fullpath); + } + else + { + $image['src'] = $imgURL; + $image['dimensions'] = $imgInfo[3]; + $image['width'] = $imgInfo[0]; + $image['height'] = $imgInfo[1]; + $image['file'] = $relative; + $image['fullpath'] = $fullpath; + } + + Return $image; + } + + + /** + * Process the actions, crop, scale(resize), rotate, flip, and save. + * When ever an action is performed, the result is save into a + * temporary image file, see createUnique on the filename specs. + * It does not return the saved file, alway returning the tmp file. + * @param string $action, should be 'crop', 'scale', 'rotate','flip', or 'save' + * @param string $relative the relative image filename + * @param string $fullpath the fullpath to the image file + * @return array with image information + * array('src'=>'url of the image', 'dimensions'=>'width="xx" height="yy"', + * 'file'=>'image file, relative', 'fullpath'=>'full path to the image'); + */ + function processAction($action, $relative, $fullpath) + { + $params = ''; + + if(isset($_GET['params'])) + $params = $_GET['params']; + + $values = explode(',',$params,4); + $saveFile = $this->getSaveFileName($values[0]); + + $img = Image_Transform::factory(IMAGE_CLASS); + $img->load($fullpath); + + switch ($action) + { + case 'replace': + + // 'ImageManager.php' handled the uploaded file, it's now on the server. + // If maximum size is specified, constrain image to it. + if ($this->manager->config['maxWidth'] > 0 && $this->manager->config['maxHeight'] > 0 && ($img->img_x > $this->manager->config['maxWidth'] || $img->img_y > $this->manager->config['maxHeight'])) + { + $percentage = min($this->manager->config['maxWidth']/$img->img_x, $this->manager->config['maxHeight']/$img->img_y); + $img->scale($percentage); + } + + break; + + case 'watermark': + + // loading target image + $functionName = 'ImageCreateFrom' . $img->type; + if(function_exists($functionName)) + { + $imageResource = $functionName($fullpath); + } + else + { + echo ""; + return false; + } + + // loading watermark + $watermarkFullPath = $_GET['watermarkFullPath']; + $watermarkImageType = strtolower(substr($watermarkFullPath, strrpos($watermarkFullPath, ".") + 1)); + if ($watermarkImageType == "jpg") { $watermarkImageType = "jpeg"; } + if ($watermarkImageType == "tif") { $watermarkImageType = "tiff"; } + $functionName = 'ImageCreateFrom' . $watermarkImageType; + if(function_exists($functionName)) + { + $watermarkResource = $functionName($watermarkFullPath); + } + else + { + echo ""; + return false; + } + + $numberOfColors = imagecolorstotal($watermarkResource); + + $watermarkX = isset($_GET['watermarkX']) ? $_GET['watermarkX'] : -1; + $watermarkY = isset($_GET['watermarkY']) ? $_GET['watermarkY'] : -1; + $opacity = $_GET['opacity']; + + // PNG24 watermark on GIF target needs special handling + // PNG24 watermark with alpha transparency on other targets need also this handling + if ($watermarkImageType == "png" && $numberOfColors == 0 && ($img->type == "gif" || $opacity < 100)) + { + require_once('Classes/api.watermark.php'); + + $watermarkAPI = new watermark(); + $imageResource = $watermarkAPI->create_watermark($imageResource, $watermarkResource, $opacity, $watermarkX, $watermarkY); + } + // PNG24 watermark without alpha transparency on other targets than GIF can use 'imagecopy' + elseif ($watermarkImageType == "png" && $numberOfColors == 0 && $opacity == 100) + { + $watermark_width = imagesx($watermarkResource); + $watermark_height = imagesy($watermarkResource); + + imagecopy($imageResource, $watermarkResource, $watermarkX, $watermarkY, 0, 0, $watermark_width, $watermark_height); + } + // Other watermarks can be appllied no swet on all targets + else + { + $watermark_width = imagesx($watermarkResource); + $watermark_height = imagesy($watermarkResource); + + imagecopymerge($imageResource, $watermarkResource, $watermarkX, $watermarkY, 0, 0, $watermark_width, $watermark_height, $opacity); + } + + break; + + case 'crop': + $img->crop(intval($values[0]),intval($values[1]), + intval($values[2]),intval($values[3])); + break; + case 'scale': + $img->resize(intval($values[0]),intval($values[1])); + break; + case 'rotate': + $img->rotate(floatval($values[0])); + break; + case 'flip': + if ($values[0] == 'hoz') + $img->flip(true); + else if($values[0] == 'ver') + $img->flip(false); + break; + case 'save': + if(!is_null($saveFile)) + { + $quality = intval($values[1]); + if($quality <0) $quality = 85; + $newSaveFile = $this->makeRelative($relative, $saveFile); + $oldSaveFile = $newSaveFile; + + if ($this->manager->config['allow_newFileName'] && $this->manager->config['allow_overwrite'] == false) + { + // check whether a file already exist and if there is, create a variant of the filename + $newName = $this->getUniqueFilename($newSaveFile); + //get unique filename just returns the filename, so + //we need to make the relative path again. + $newSaveFile = $this->makeRelative($relative, $newName); + } + + // forced new name? + if ($oldSaveFile != $newSaveFile) + { + $this->forcedNewName = $newName; + } + else + { + $this->forcedNewName = false; + } + + $newSaveFullpath = $this->manager->getFullPath($newSaveFile); + $img->save($newSaveFullpath, $values[0], $quality); + if(is_file($newSaveFullpath)) + $this->filesaved = 1; + else + $this->filesaved = -1; + } + break; + } + + //create the tmp image file + $filename = $this->createUnique($fullpath); + $newRelative = $this->makeRelative($relative, $filename); + $newFullpath = $this->manager->getFullPath($newRelative); + $newURL = $this->manager->getFileURL($newRelative); + + // when uploaded and not resized, rename and don't save + if ($action == "replace" && $percentage <= 0) + { + rename($fullpath, $newFullpath); + } + // when watermarked, save to new filename + elseif ($action == "watermark") + { + // save image + $functionName = 'image' . $img->type; + if(function_exists($functionName)) + { + if($type=='jpeg') + $functionName($imageResource, $newFullpath, 100); + else + $functionName($imageResource, $newFullpath); + } + else + { + echo ""; + return false; + } + } + else + { + //save the file. + $img->save($newFullpath); + $img->free(); + } + + // when uploaded was resized and saved, remove original + if ($action == "replace" && $percentage > 0) + { + unlink($fullpath); + } + + //get the image information + $imgInfo = @getimagesize($newFullpath); + + $image['src'] = $newURL; + $image['dimensions'] = $imgInfo[3]; + $image['width'] = $imgInfo[0]; + $image['height'] = $imgInfo[1]; + $image['file'] = $newRelative; + $image['fullpath'] = $newFullpath; + + + Return $image; + + } + + + + /** + * Get the file name base on the save name + * and the save type. + * @param string $type image type, 'jpeg', 'png', or 'gif' + * @return string the filename according to save type + */ + function getSaveFileName($type) + { + if(!isset($_GET['file'])) + Return null; + + $filename = Files::escape(rawurldecode($_GET['file'])); + $index = strrpos($filename,'.'); + $base = substr($filename,0,$index); + $ext = strtolower(substr($filename,$index+1,strlen($filename))); + + if($type == 'jpeg' && !($ext=='jpeg' || $ext=='jpg')) + { + Return $base.'.jpeg'; + } + if($type=='png' && $ext != 'png') + Return $base.'.png'; + if($type=='gif' && $ext != 'gif') + Return $base.'.gif'; + + Return $filename; + } + + /** + * Get the default save file name, used by editor.php. + * @return string a suggestive filename, this should be unique + */ + function getDefaultSaveFile() + { + if(isset($_GET['img'])) + $relative = rawurldecode($_GET['img']); + else + Return null; + + Return $this->getUniqueFilename($relative); + } + + /** + * Get a unique filename. If the file exists, the filename + * base is appended with an increasing integer. + * @param string $relative the relative filename to the base_dir + * @return string a unique filename in the current path + */ + function getUniqueFilename($relative) + { + $fullpath = $this->manager->getFullPath($relative); + + $pathinfo = pathinfo($fullpath); + + $path = Files::fixPath($pathinfo['dirname']); + $file = Files::escape($pathinfo['basename']); + + $filename = $file; + + $dotIndex = strrpos($file, '.'); + $ext = ''; + + if(is_int($dotIndex)) + { + $ext = substr($file, $dotIndex); + $base = substr($file, 0, $dotIndex); + } + + $counter = 0; + while(is_file($path.$filename)) + { + $counter++; + $filename = $base.'_'.$counter.$ext; + } + + Return $filename; + + } + + /** + * Specifiy the original relative path, a new filename + * and return the new filename with relative path. + * i.e. $pathA (-filename) + $file + * @param string $pathA the relative file + * @param string $file the new filename + * @return string relative path with the new filename + */ + function makeRelative($pathA, $file) + { + $index = strrpos($pathA,'/'); + if(!is_int($index)) + Return $file; + + $path = substr($pathA, 0, $index); + Return Files::fixPath($path).$file; + } + + /** + * Get the action GET parameter + * @return string action parameter + */ + function getAction() + { + $action = null; + if(isset($_GET['action'])) + $action = $_GET['action']; + Return $action; + } + + /** + * Generate a unique string based on md5(microtime()). + * Well not so uniqe, as it is limited to 6 characters + * @return string unique string. + */ + function uniqueStr() + { + return substr(md5(microtime()),0,6); + } + + /** + * Create unique tmp image file name. + * The filename is based on the tmp file prefix + * specified in config.inc.php plus + * the UID (basically a md5 of the remote IP) + * and some random 6 character string. + * This function also calls to clean up the tmp files. + * @param string $file the fullpath to a file + * @return string a unique filename for that path + * NOTE: it only returns the filename, path no included. + */ + function createUnique($file) + { + $pathinfo = pathinfo($file); + $path = Files::fixPath($pathinfo['dirname']); + $imgType = $this->getImageType($file); + + $unique_str = $this->manager->getTmpPrefix().$this->_uid.'_'.$this->uniqueStr().".".$imgType; + + //make sure the the unique temp file does not exists + while (file_exists($path.$unique_str)) + { + $unique_str = $this->manager->getTmpPrefix().$this->_uid.'_'.$this->uniqueStr().".".$imgType; + } + + $this->cleanUp($path,$pathinfo['basename']); + + Return $unique_str; + } + + /** + * Delete any tmp image files. + * @param string $path the full path + * where the clean should take place. + */ + function cleanUp($path,$file) + { + $path = Files::fixPath($path); + + if(!is_dir($path)) + Return false; + + $d = @dir($path); + + $tmp = $this->manager->getTmpPrefix(); + $tmpLen = strlen($tmp); + + $prefix = $tmp.$this->_uid; + $len = strlen($prefix); + + while (false !== ($entry = $d->read())) + { + //echo $entry."
    "; + if(is_file($path.$entry) && $this->manager->isTmpFile($entry)) + { + if(substr($entry,0,$len)==$prefix && $entry != $file) + Files::delFile($path.$entry); + else if(substr($entry,0,$tmpLen)==$tmp && $entry != $file) + { + if(filemtime($path.$entry)+$this->lapse_time < time()) + Files::delFile($path.$entry); + } + } + } + $d->close(); + } + + /** + * Get the image type base on an image file. + * @param string $file the full path to the image file. + * @return string of either 'gif', 'jpeg', 'png' or 'bmp' + * otherwise it will return null. + */ + function getImageType($file) + { + $imageInfo = @getImageSize($file); + + if(!is_array($imageInfo)) + Return null; + + switch($imageInfo[2]) + { + case 1: + Return 'gif'; + case 2: + Return 'jpeg'; + case 3: + Return 'png'; + case 6: + Return 'bmp'; + } + + Return null; + } + + /** + * Check if the specified image can be edit by GD + * mainly to check that GD can read and save GIFs + * @return int 0 if it is not a GIF file, 1 is GIF is editable, -1 if not editable. + */ + function isGDEditable() + { + if(isset($_GET['img'])) + $relative = rawurldecode($_GET['img']); + else + Return 0; + if(IMAGE_CLASS != 'GD') + Return 0; + + $fullpath = $this->manager->getFullPath($relative); + + $type = $this->getImageType($fullpath); + if($type != 'gif') + Return 0; + + if(function_exists('ImageCreateFrom'+$type) + && function_exists('image'+$type)) + Return 1; + else + Return -1; + } + + /** + * Check if GIF can be edit by GD. + * @return int 0 if it is not using the GD library, 1 is GIF is editable, -1 if not editable. + */ + function isGDGIFAble() + { + if(IMAGE_CLASS != 'GD') + Return 0; + + if(function_exists('ImageCreateFromGif') + && function_exists('imagegif')) + Return 1; + else + Return -1; + } +} + +?> diff --git a/fckeditor/editor/plugins/ImageManager/Classes/ImageManager.php b/fckeditor/editor/plugins/ImageManager/Classes/ImageManager.php new file mode 100644 index 0000000..02f5cb6 --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/Classes/ImageManager.php @@ -0,0 +1,694 @@ +config = $config; + } + + /** + * Get the base directory. + * @return string base dir, see config.inc.php + */ + function getBaseDir() + { + Return $this->config['base_dir']; + } + + /** + * Get the base URL. + * @return string base url, see config.inc.php + */ + function getBaseURL() + { + Return $this->config['base_url']; + } + + function isValidBase() + { + return is_dir($this->getBaseDir()); + } + + /** + * Get the tmp file prefix. + * @return string tmp file prefix. + */ + function getTmpPrefix() + { + Return $this->config['tmp_prefix']; + } + + /** + * Get the sub directories in the base dir. + * Each array element contain + * the relative path (relative to the base dir) as key and the + * full path as value. + * @return array of sub directries + * array('path name' => 'full directory path', ...) + */ + function getDirs() + { + if(is_null($this->dirs)) + { + $dirs = $this->_dirs($this->getBaseDir(),'/'); + ksort($dirs); + $this->dirs = $dirs; + } + return $this->dirs; + } + + /** + * Recursively travese the directories to get a list + * of accessable directories. + * @param string $base the full path to the current directory + * @param string $path the relative path name + * @return array of accessiable sub-directories + * array('path name' => 'full directory path', ...) + */ + function _dirs($base, $path) + { + $base = Files::fixPath($base); + $dirs = array(); + + if($this->isValidBase() == false) + return $dirs; + + $d = @dir($base); + + while (false !== ($entry = $d->read())) + { + //If it is a directory, and it doesn't start with + // a dot, and if is it not the thumbnail directory + if(is_dir($base.$entry) + && substr($entry,0,1) != '.' + && $this->isThumbDir($entry) == false) + { + $relative = Files::fixPath($path.$entry); + $fullpath = Files::fixPath($base.$entry); + $dirs[$relative] = $fullpath; + $dirs = array_merge($dirs, $this->_dirs($fullpath, $relative)); + } + } + $d->close(); + + Return $dirs; + } + + /** + * Get all the files and directories of a relative path. + * @param string $path relative path to be base path. + * @return array of file and path information. + * array(0=>array('relative'=>'fullpath',...), 1=>array('filename'=>fileinfo array(),...) + * fileinfo array: array('url'=>'full url', + * 'relative'=>'relative to base', + * 'fullpath'=>'full file path', + * 'image'=>imageInfo array() false if not image, + * 'stat' => filestat) + */ + function getFiles($path) + { + $files = array(); + $dirs = array(); + + if($this->isValidBase() == false) + return array($files,$dirs); + + $path = Files::fixPath($path); + $base = Files::fixPath($this->getBaseDir()); + $fullpath = Files::makePath($base,$path); + + + $d = @dir($fullpath); + + while (false !== ($entry = $d->read())) + { + //not a dot file or directory + if(substr($entry,0,1) != '.') + { + if(is_dir($fullpath.$entry) + && $this->isThumbDir($entry) == false) + { + $relative = Files::fixPath($path.$entry); + $full = Files::fixPath($fullpath.$entry); + $count = $this->countFiles($full); + $dirs[$relative] = array('fullpath'=>$full,'entry'=>$entry,'count'=>$count); + } + else if(is_file($fullpath.$entry) && $this->isThumb($entry)==false && $this->isTmpFile($entry) == false) + { + $img = $this->getImageInfo($fullpath.$entry); + + if(!(!is_array($img)&&$this->config['validate_images'])) + { + $file['url'] = Files::makePath($this->config['base_url'],$path).$entry; + $file['relative'] = $path.$entry; + $file['fullpath'] = $fullpath.$entry; + $file['image'] = $img; + $file['stat'] = stat($fullpath.$entry); + $files[$entry] = $file; + } + } + } + } + $d->close(); + ksort($dirs); + ksort($files); + + Return array($dirs, $files); + } + + /** + * Count the number of files and directories in a given folder + * minus the thumbnail folders and thumbnails. + */ + function countFiles($path) + { + $total = 0; + + if(is_dir($path)) + { + $d = @dir($path); + + while (false !== ($entry = $d->read())) + { + //echo $entry."
    "; + if(substr($entry,0,1) != '.' + && $this->isThumbDir($entry) == false + && $this->isTmpFile($entry) == false + && $this->isThumb($entry) == false) + { + $total++; + } + } + $d->close(); + } + return $total; + } + + /** + * Get image size information. + * @param string $file the image file + * @return array of getImageSize information, + * false if the file is not an image. + */ + function getImageInfo($file) + { + Return @getImageSize($file); + } + + /** + * Check if the file contains the thumbnail prefix. + * @param string $file filename to be checked + * @return true if the file contains the thumbnail prefix, false otherwise. + */ + function isThumb($file) + { + $len = strlen($this->config['thumbnail_prefix']); + if(substr($file,0,$len)==$this->config['thumbnail_prefix']) + Return true; + else + Return false; + } + + /** + * Check if the given directory is a thumbnail directory. + * @param string $entry directory name + * @return true if it is a thumbnail directory, false otherwise + */ + function isThumbDir($entry) + { + if($this->config['thumbnail_dir'] == false + || strlen(trim($this->config['thumbnail_dir'])) == 0) + Return false; + else + Return ($entry == $this->config['thumbnail_dir']); + } + + /** + * Check if the given file is a tmp file. + * @param string $file file name + * @return boolean true if it is a tmp file, false otherwise + */ + function isTmpFile($file) + { + $len = strlen($this->config['tmp_prefix']); + if(substr($file,0,$len)==$this->config['tmp_prefix']) + Return true; + else + Return false; + } + + /** + * For a given image file, get the respective thumbnail filename + * no file existence check is done. + * @param string $fullpathfile the full path to the image file + * @return string of the thumbnail file + */ + function getThumbName($fullpathfile) + { + $path_parts = pathinfo($fullpathfile); + + $thumbnail = $this->config['thumbnail_prefix'].$path_parts['basename']; + + if($this->config['safe_mode'] == true + || strlen(trim($this->config['thumbnail_dir'])) == 0) + { + Return Files::makeFile($path_parts['dirname'],$thumbnail); + } + else + { + if(strlen(trim($this->config['thumbnail_dir'])) > 0) + { + $path = Files::makePath($path_parts['dirname'],$this->config['thumbnail_dir']); + if(!is_dir($path)) + Files::createFolder($path); + Return Files::makeFile($path,$thumbnail); + } + else //should this ever happen? + { + //error_log('ImageManager: Error in creating thumbnail name'); + } + } + } + + /** + * Similar to getThumbName, but returns the URL, base on the + * given base_url in config.inc.php + * @param string $relative the relative image file name, + * relative to the base_dir path + * @return string the url of the thumbnail + */ + function getThumbURL($relative) + { + $path_parts = pathinfo($relative); + $thumbnail = $this->config['thumbnail_prefix'].$path_parts['basename']; + if($path_parts['dirname']=='\\') $path_parts['dirname']='/'; + + if($this->config['safe_mode'] == true + || strlen(trim($this->config['thumbnail_dir'])) == 0) + { + Return Files::makeFile($this->getBaseURL(),$thumbnail); + } + else + { + if(strlen(trim($this->config['thumbnail_dir'])) > 0) + { + $path = Files::makePath($path_parts['dirname'],$this->config['thumbnail_dir']); + $url_path = Files::makePath($this->getBaseURL(), $path); + Return Files::makeFile($url_path,$thumbnail); + } + else //should this ever happen? + { + //error_log('ImageManager: Error in creating thumbnail url'); + } + + } + } + + /** + * Check if the given path is part of the subdirectories + * under the base_dir. + * @param string $path the relative path to be checked + * @return boolean true if the path exists, false otherwise + */ + function validRelativePath($path) + { + $dirs = $this->getDirs(); + if($path == '/' || $path == '') + Return true; + //check the path given in the url against the + //list of paths in the system. + for($i = 0; $i < count($dirs); $i++) + { + $key = key($dirs); + //we found the path + if($key == $path) + Return true; + + next($dirs); + } + Return false; + } + + /** + * Process uploaded files, assumes the file is in + * $_FILES['upload'] and $_POST['dir'] is set. + * The dir must be relative to the base_dir and exists. + * If 'validate_images' is set to true, only file with + * image dimensions will be accepted. + * @return null + */ + function processUploads() + { + if($this->isValidBase() == false) + return; + + $relative = null; + + if(isset($_POST['dir'])) + $relative = rawurldecode($_POST['dir']); + else + return; + + //check for the file, and must have valid relative path + if(isset($_FILES['upload']) && $this->validRelativePath($relative)) + { + return $this->_processFiles($relative, $_FILES['upload']); + } + } + + /** + * Process upload files. The file must be an + * uploaded file. If 'validate_images' is set to + * true, only images will be processed. Any duplicate + * file will be renamed. See Files::copyFile for details + * on renaming. + * @param string $relative the relative path where the file + * should be copied to. + * @param array $file the uploaded file from $_FILES + * @return boolean true if the file was processed successfully, + * false otherwise + */ + function _processFiles($relative, $file) + { + + if($file['error']!=0) + { + Return false; + } + + if(!is_file($file['tmp_name'])) + { + Return false; + } + + if(!is_uploaded_file($file['tmp_name'])) + { + Files::delFile($file['tmp_name']); + Return false; + } + + + if($this->config['validate_images'] == true) + { + $imgInfo = @getImageSize($file['tmp_name']); + if(!is_array($imgInfo)) + { + Files::delFile($file['tmp_name']); + Return false; + } + } + + //now copy the file + $path = Files::makePath($this->getBaseDir(),$relative); + $result = Files::copyFile($file['tmp_name'], $path, $file['name']); + + // constrain image size + if(!is_int($result)) + { + $img = Image_Transform::factory(IMAGE_CLASS); + $img->load($path . $result); + + // If maximum size is specified, constrain image to it. + if ($this->config['maxWidth'] > 0 && $this->config['maxHeight'] > 0 && ($img->img_x > $this->config['maxWidth'] || $img->img_y > $this->config['maxHeight'])) + { + $percentage = min($this->config['maxWidth']/$img->img_x, $this->config['maxHeight']/$img->img_y); + $img->scale($percentage); + } + $img->save($path . $result); + $img->free(); + } + + //no copy error + if(!is_int($result)) + { + Files::delFile($file['tmp_name']); + Return $result; + } + + //delete tmp files. + Files::delFile($file['tmp_name']); + Return false; + } + + /** + * Get the URL of the relative file. + * basically appends the relative file to the + * base_url given in config.inc.php + * @param string $relative a file the relative to the base_dir + * @return string the URL of the relative file. + */ + function getFileURL($relative) + { + Return Files::makeFile($this->getBaseURL(),$relative); + } + + /** + * Get the fullpath to a relative file. + * @param string $relative the relative file. + * @return string the full path, .ie. the base_dir + relative. + */ + function getFullPath($relative) + { + Return Files::makeFile($this->getBaseDir(),$relative);; + } + + /** + * Get the default thumbnail. + * @return string default thumbnail, empty string if + * the thumbnail doesn't exist. + */ + function getDefaultThumb() + { + if(is_file($this->config['default_thumbnail'])) + Return $this->config['default_thumbnail']; + else + Return ''; + } + + + /** + * Get the thumbnail url to be displayed. + * If the thumbnail exists, and it is up-to-date + * the thumbnail url will be returns. If the + * file is not an image, a default image will be returned. + * If it is an image file, and no thumbnail exists or + * the thumbnail is out-of-date (i.e. the thumbnail + * modified time is less than the original file) + * then a thumbs.php?img=filename.jpg is returned. + * The thumbs.php url will generate a new thumbnail + * on the fly. If the image is less than the dimensions + * of the thumbnails, the image will be display instead. + * @param string $relative the relative image file. + * @return string the url of the thumbnail, be it + * actually thumbnail or a script to generate the + * thumbnail on the fly. + */ + function getThumbnail($relative) + { + $fullpath = Files::makeFile($this->getBaseDir(),$relative); + + //not a file??? + if(!is_file($fullpath)) + Return $this->getDefaultThumb(); + + $imgInfo = @getImageSize($fullpath); + + //not an image + if(!is_array($imgInfo)) + Return $this->getDefaultThumb(); + + //the original image is smaller than thumbnails, + //so just return the url to the original image. + if ($imgInfo[0] <= $this->config['thumbnail_width'] + && $imgInfo[1] <= $this->config['thumbnail_height']) + Return $this->getFileURL($relative); + + $thumbnail = $this->getThumbName($fullpath); + + //check for thumbnails, if exists and + // it is up-to-date, return the thumbnail url + if(is_file($thumbnail)) + { + if(filemtime($thumbnail) >= filemtime($fullpath)) + Return $this->getThumbURL($relative); + } + + //well, no thumbnail was found, so ask the thumbs.php + //to generate the thumbnail on the fly. + Return 'thumbs.php?img='.rawurlencode($relative); + } + + /** + * Delete and specified files. + * @return boolean true if delete, false otherwise + */ + function deleteFiles() + { + if(isset($_GET['delf'])) + $this->_delFile(rawurldecode($_GET['delf'])); + } + + /** + * Delete and specified directories. + * @return boolean true if delete, false otherwise + */ + function deleteDirs() + { + if(isset($_GET['deld'])) + return $this->_delDir(rawurldecode($_GET['deld'])); + else + Return false; + } + + /** + * Delete the relative file, and any thumbnails. + * @param string $relative the relative file. + * @return boolean true if deleted, false otherwise. + */ + function _delFile($relative) + { + $fullpath = Files::makeFile($this->getBaseDir(),$relative); + + //check that the file is an image + if($this->config['validate_images'] == true) + { + if(!is_array($this->getImageInfo($fullpath))) + return false; //hmmm not an Image!!??? + } + + $thumbnail = $this->getThumbName($fullpath); + + if(Files::delFile($fullpath)) + Return Files::delFile($thumbnail); + else + Return false; + } + + /** + * Delete directories recursively. + * @param string $relative the relative path to be deleted. + * @return boolean true if deleted, false otherwise. + */ + function _delDir($relative) + { + $fullpath = Files::makePath($this->getBaseDir(),$relative); + if($this->countFiles($fullpath) <= 0) + return Files::delFolder($fullpath,true); //delete recursively. + else + Return false; + } + + /** + * Create new directories. + * If in safe_mode, nothing happens. + * @return boolean true if created, false otherwise. + */ + function processNewDir() + { + if($this->config['safe_mode'] == true) + Return false; + + if(isset($_GET['newDir']) && isset($_GET['dir'])) + { + $newDir = rawurldecode($_GET['newDir']); + $dir = rawurldecode($_GET['dir']); + $path = Files::makePath($this->getBaseDir(),$dir); + $fullpath = Files::makePath($path, Files::escape($newDir)); + if(is_dir($fullpath)) + Return false; + + Return Files::createFolder($fullpath); + } + } + + /** + * Do some graphic library method checkings + * @param string $library the graphics library, GD, NetPBM, or IM. + * @param string $method the method to check. + * @return boolean true if able, false otherwise. + */ + function validGraphicMethods($library,$method) + { + switch ($library) + { + case 'GD': + return $this->_checkGDLibrary($method); + break; + case 'NetPBM': + return $this->_checkNetPBMLibrary($method); + break; + case 'IM': + return $this->_checkIMLibrary($method); + } + return false; + } + + function _checkIMLibrary($method) + { + //ImageMagick goes throught 1 single executable + if(is_file(Files::fixPath(IMAGE_TRANSFORM_LIB_PATH).'convert')) + return true; + else + return false; + } + + /** + * Check the GD library functionality. + * @param string $library the graphics library, GD, NetPBM, or IM. + * @return boolean true if able, false otherwise. + */ + function _checkGDLibrary($method) + { + $errors = array(); + switch($method) + { + case 'create': + $errors['createjpeg'] = function_exists('imagecreatefromjpeg'); + $errors['creategif'] = function_exists('imagecreatefromgif'); + $errors['createpng'] = function_exists('imagecreatefrompng'); + break; + case 'modify': + $errors['create'] = function_exists('ImageCreateTrueColor') || function_exists('ImageCreate'); + $errors['copy'] = function_exists('ImageCopyResampled') || function_exists('ImageCopyResized'); + break; + case 'save': + $errors['savejpeg'] = function_exists('imagejpeg'); + $errors['savegif'] = function_exists('imagegif'); + $errors['savepng'] = function_exists('imagepng'); + break; + } + + return $errors; + } +} + +?> diff --git a/fckeditor/editor/plugins/ImageManager/Classes/NetPBM.php b/fckeditor/editor/plugins/ImageManager/Classes/NetPBM.php new file mode 100644 index 0000000..9590dfb --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/Classes/NetPBM.php @@ -0,0 +1,257 @@ + +** Filename......: NetPBM.php +** Last changed..: 30 Aug 2003 +** Notes.........: Orginal is from PEAR +**/ + +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Authors: Peter Bowyer | +// +----------------------------------------------------------------------+ +// +// $Id: NetPBM.php,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ +// +// Image Transformation interface using command line NetPBM + +require_once "Transform.php"; + +Class Image_Transform_Driver_NetPBM extends Image_Transform +{ + + /** + * associative array commands to be executed + * @var array + */ + var $command = array(); + + /** + * Class Constructor + */ + function Image_Transform_Driver_NetPBM() + { + $this->uid = md5($_SERVER['REMOTE_ADDR']); + + return true; + } // End function Image_NetPBM + + /** + * Load image + * + * @param string filename + * + * @return mixed none or a PEAR error object on error + * @see PEAR::isError() + */ + function load($image) + { + //echo $image; + $this->image = $image; + $this->_get_image_details($image); + } // End load + + /** + * Resizes the image + * + * @return none + * @see PEAR::isError() + */ + function _resize($new_x, $new_y) + { + // there's no technical reason why resize can't be called multiple + // times...it's just silly to do so + + $this->command[] = IMAGE_TRANSFORM_LIB_PATH . + "pnmscale -width $new_x -height $new_y"; + + $this->_set_new_x($new_x); + $this->_set_new_y($new_y); + } // End resize + + /** + * Crop the image + * + * @param int $crop_x left column of the image + * @param int $crop_y top row of the image + * @param int $crop_width new cropped image width + * @param int $crop_height new cropped image height + */ + function crop($crop_x, $crop_y, $crop_width, $crop_height) + { + $this->command[] = IMAGE_TRANSFORM_LIB_PATH . + "pnmcut -left $crop_x -top $crop_y -width $crop_width -height $crop_height"; + } + + /** + * Rotates the image + * + * @param int $angle The angle to rotate the image through + */ + function rotate($angle) + { + $angle = -1*floatval($angle); + + if($angle > 90) + { + $this->command[] = IMAGE_TRANSFORM_LIB_PATH . "pnmrotate -noantialias 90"; + $this->rotate(-1*($angle-90)); + } + else if ($angle < -90) + { + $this->command[] = IMAGE_TRANSFORM_LIB_PATH . "pnmrotate -noantialias -90"; + $this->rotate(-1*($angle+90)); + } + else + $this->command[] = IMAGE_TRANSFORM_LIB_PATH . "pnmrotate -noantialias $angle"; + } // End rotate + + /** + * Flip the image horizontally or vertically + * + * @param boolean $horizontal true if horizontal flip, vertical otherwise + */ + function flip($horizontal) + { + if($horizontal) + $this->command[] = IMAGE_TRANSFORM_LIB_PATH . "pnmflip -lr"; + else + $this->command[] = IMAGE_TRANSFORM_LIB_PATH . "pnmflip -tb"; + } + + /** + * Adjust the image gamma + * + * @param float $outputgamma + * + * @return none + */ + function gamma($outputgamma = 1.0) { + $this->command[13] = IMAGE_TRANSFORM_LIB_PATH . "pnmgamma $outputgamma"; + } + + /** + * adds text to an image + * + * @param array options Array contains options + * array( + * 'text' // The string to draw + * 'x' // Horizontal position + * 'y' // Vertical Position + * 'Color' // Font color + * 'font' // Font to be used + * 'size' // Size of the fonts in pixel + * 'resize_first' // Tell if the image has to be resized + * // before drawing the text + * ) + * + * @return none + */ + function addText($params) + { + $default_params = array('text' => 'This is Text', + 'x' => 10, + 'y' => 20, + 'color' => 'red', + 'font' => 'Arial.ttf', + 'size' => '12', + 'angle' => 0, + 'resize_first' => false); + // we ignore 'resize_first' since the more logical approach would be + // for the user to just call $this->_resize() _first_ ;) + extract(array_merge($default_params, $params)); + $this->command[] = "ppmlabel -angle $angle -colour $color -size " + ."$size -x $x -y ".$y+$size." -text \"$text\""; + } // End addText + + function _postProcess($type, $quality, $save_type) + { + $type = is_null($type) || $type==''? $this->type : $type; + $save_type = is_null($save_type) || $save_type==''? $this->type : $save_type; + //echo "TYPE:". $this->type; + array_unshift($this->command, IMAGE_TRANSFORM_LIB_PATH + . $type.'topnm '. $this->image); + $arg = ''; + switch(strtolower($save_type)){ + case 'gif': + $this->command[] = IMAGE_TRANSFORM_LIB_PATH . "ppmquant 256"; + $this->command[] = IMAGE_TRANSFORM_LIB_PATH . "ppmto$save_type"; + break; + case 'jpg': + case 'jpeg': + $arg = "--quality=$quality"; + $this->command[] = IMAGE_TRANSFORM_LIB_PATH . "ppmto$save_type $arg"; + break; + default: + $this->command[] = IMAGE_TRANSFORM_LIB_PATH . "pnmto$save_type $arg"; + break; + } // switch + return implode('|', $this->command); + } + + /** + * Save the image file + * + * @param $filename string the name of the file to write to + * @param string $type (jpeg,png...); + * @param int $quality 75 + * @return none + */ + function save($filename, $type=null, $quality = 85) + { + $cmd = $this->_postProcess('', $quality, $type) . ">$filename"; + + //if we have windows server + if(isset($_ENV['OS']) && eregi('window',$_ENV['OS'])) + $cmd = ereg_replace('/','\\',$cmd); + //echo $cmd."##"; + $output = system($cmd); + error_log('NETPBM: '.$cmd); + //error_log($output); + $this->command = array(); + } // End save + + + /** + * Display image without saving and lose changes + * + * @param string $type (jpeg,png...); + * @param int $quality 75 + * @return none + */ + function display($type = null, $quality = 75) + { + header('Content-type: image/' . $type); + $cmd = $this->_postProcess($type, $quality); + + passthru($cmd); + $this->command = array(); + } + + /** + * Destroy image handle + * + * @return none + */ + function free() + { + // there is no image handle here + return true; + } + + +} // End class NetPBM +?> diff --git a/fckeditor/editor/plugins/ImageManager/Classes/Thumbnail.php b/fckeditor/editor/plugins/ImageManager/Classes/Thumbnail.php new file mode 100644 index 0000000..7527dc7 --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/Classes/Thumbnail.php @@ -0,0 +1,125 @@ +driver = Image_Transform::factory(IMAGE_CLASS); + $this->width = $width; + $this->height = $height; + } + + /** + * Create a thumbnail. + * @param string $file the image for the thumbnail + * @param string $thumbnail if not null, the thumbnail will be saved + * as this parameter value. + * @return boolean true if thumbnail is created, false otherwise + */ + function createThumbnail($file, $thumbnail=null) + { + if(!is_file($file)) + Return false; + + //error_log('Creating Thumbs: '.$file); + + $this->driver->load($file); + + if($this->proportional) + { + $width = $this->driver->img_x; + $height = $this->driver->img_y; + + if ($width > $height) + $this->height = intval($this->width/$width*$height); + else if ($height > $width) + $this->width = intval($this->height/$height*$width); + } + + $this->driver->resize($this->width, $this->height); + + if(is_null($thumbnail)) + $this->save($file); + else + $this->save($thumbnail); + + + $this->free(); + + if(is_file($thumbnail)) + Return true; + else + Return false; + } + + /** + * Save the thumbnail file. + * @param string $file file name to be saved as. + */ + function save($file) + { + $this->driver->save($file); + } + + /** + * Free up the graphic driver resources. + */ + function free() + { + $this->driver->free(); + } +} + + +?> diff --git a/fckeditor/editor/plugins/ImageManager/Classes/Transform.php b/fckeditor/editor/plugins/ImageManager/Classes/Transform.php new file mode 100644 index 0000000..ea1642d --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/Classes/Transform.php @@ -0,0 +1,569 @@ + +** Filename......: Transform.php +** Last changed..: 30 Aug 2003 +** Notes.........: Orginal is from PEAR + + Added a few extra, + - create unique filename in a particular directory, + used for temp image files. + - added cropping to GD, NetPBM, ImageMagick +**/ + +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Authors: Peter Bowyer | +// | Alan Knowles | +// | Vincent Oostindie | +// +----------------------------------------------------------------------+ +// +// $Id: Transform.php,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ +// +// Image Transformation interface +// + + +/** + * The main "Image_Resize" class is a container and base class which + * provides the static methods for creating Image objects as well as + * some utility functions (maths) common to all parts of Image Resize. + * + * The object model of DB is as follows (indentation means inheritance): + * + * Image_Resize The base for each Image implementation. Provides default + * | implementations (in OO lingo virtual methods) for + * | the actual Image implementations as well as a bunch of + * | maths methods. + * | + * +-Image_GD The Image implementation for the PHP GD extension . Inherits + * Image_Resize + * When calling DB::setup for GD images the object returned is an + * instance of this class. + * + * @package Image Resize + * @version 1.00 + * @author Peter Bowyer + * @since PHP 4.0 + */ +Class Image_Transform +{ + /** + * Name of the image file + * @var string + */ + var $image = ''; + /** + * Type of the image file (eg. jpg, gif png ...) + * @var string + */ + var $type = ''; + /** + * Original image width in x direction + * @var int + */ + var $img_x = ''; + /** + * Original image width in y direction + * @var int + */ + var $img_y = ''; + /** + * New image width in x direction + * @var int + */ + var $new_x = ''; + /** + * New image width in y direction + * @var int + */ + var $new_y = ''; + /** + * Path the the library used + * e.g. /usr/local/ImageMagick/bin/ or + * /usr/local/netpbm/ + */ + var $lib_path = ''; + /** + * Flag to warn if image has been resized more than once before displaying + * or saving. + */ + var $resized = false; + + + var $uid = ''; + + var $lapse_time =900; //15 mins + + /** + * Create a new Image_resize object + * + * @param string $driver name of driver class to initialize + * + * @return mixed a newly created Image_Transform object, or a PEAR + * error object on error + * + * @see PEAR::isError() + * @see Image_Transform::setOption() + */ + function &factory($driver) + { + if ('' == $driver) { + die("No image library specified... aborting. You must call ::factory() with one parameter, the library to load."); + + } + $this->uid = md5($_SERVER['REMOTE_ADDR']); + + include_once "$driver.php"; + + $classname = "Image_Transform_Driver_{$driver}"; + $obj =& new $classname; + return $obj; + } + + + /** + * Resize the Image in the X and/or Y direction + * If either is 0 it will be scaled proportionally + * + * @access public + * + * @param mixed $new_x (0, number, percentage 10% or 0.1) + * @param mixed $new_y (0, number, percentage 10% or 0.1) + * + * @return mixed none or PEAR_error + */ + function resize($new_x = 0, $new_y = 0) + { + // 0 means keep original size + $new_x = (0 == $new_x) ? $this->img_x : $this->_parse_size($new_x, $this->img_x); + $new_y = (0 == $new_y) ? $this->img_y : $this->_parse_size($new_y, $this->img_y); + // Now do the library specific resizing. + return $this->_resize($new_x, $new_y); + } // End resize + + + /** + * Scale the image to have the max x dimension specified. + * + * @param int $new_x Size to scale X-dimension to + * @return none + */ + function scaleMaxX($new_x) + { + $new_y = round(($new_x / $this->img_x) * $this->img_y, 0); + return $this->_resize($new_x, $new_y); + } // End resizeX + + /** + * Scale the image to have the max y dimension specified. + * + * @access public + * @param int $new_y Size to scale Y-dimension to + * @return none + */ + function scaleMaxY($new_y) + { + $new_x = round(($new_y / $this->img_y) * $this->img_x, 0); + return $this->_resize($new_x, $new_y); + } // End resizeY + + /** + * Scale Image to a maximum or percentage + * + * @access public + * @param mixed (number, percentage 10% or 0.1) + * @return mixed none or PEAR_error + */ + function scale($size) + { + if ((strlen($size) > 1) && (substr($size,-1) == '%')) { + return $this->scaleByPercentage(substr($size, 0, -1)); + } elseif ($size < 1) { + return $this->scaleByFactor($size); + } else { + return $this->scaleByLength($size); + } + } // End scale + + /** + * Scales an image to a percentage of its original size. For example, if + * my image was 640x480 and I called scaleByPercentage(10) then the image + * would be resized to 64x48 + * + * @access public + * @param int $size Percentage of original size to scale to + * @return none + */ + function scaleByPercentage($size) + { + return $this->scaleByFactor($size / 100); + } // End scaleByPercentage + + /** + * Scales an image to a factor of its original size. For example, if + * my image was 640x480 and I called scaleByFactor(0.5) then the image + * would be resized to 320x240. + * + * @access public + * @param float $size Factor of original size to scale to + * @return none + */ + function scaleByFactor($size) + { + $new_x = round($size * $this->img_x, 0); + $new_y = round($size * $this->img_y, 0); + return $this->_resize($new_x, $new_y); + } // End scaleByFactor + + /** + * Scales an image so that the longest side has this dimension. + * + * @access public + * @param int $size Max dimension in pixels + * @return none + */ + function scaleByLength($size) + { + if ($this->img_x >= $this->img_y) { + $new_x = $size; + $new_y = round(($new_x / $this->img_x) * $this->img_y, 0); + } else { + $new_y = $size; + $new_x = round(($new_y / $this->img_y) * $this->img_x, 0); + } + return $this->_resize($new_x, $new_y); + } // End scaleByLength + + + /** + * + * @access public + * @return void + */ + function _get_image_details($image) + { + //echo $image; + $data = @GetImageSize($image); + #1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(motorola byte order, + # 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC + if (is_array($data)){ + switch($data[2]){ + case 1: + $type = 'gif'; + break; + case 2: + $type = 'jpeg'; + break; + case 3: + $type = 'png'; + break; + case 4: + $type = 'swf'; + break; + case 5: + $type = 'psd'; + case 6: + $type = 'bmp'; + case 7: + case 8: + $type = 'tiff'; + default: + echo("We do not recognize this image format"); + } + $this->img_x = $data[0]; + $this->img_y = $data[1]; + $this->type = $type; + + return true; + } else { + echo("Cannot fetch image or images details."); + return null; + } + /* + $output = array( + 'width' => $data[0], + 'height' => $data[1], + 'type' => $type + ); + return $output; + */ + } + + + /** + * Parse input and convert + * If either is 0 it will be scaled proportionally + * + * @access private + * + * @param mixed $new_size (0, number, percentage 10% or 0.1) + * @param int $old_size + * + * @return mixed none or PEAR_error + */ + function _parse_size($new_size, $old_size) + { + if ('%' == $new_size) { + $new_size = str_replace('%','',$new_size); + $new_size = $new_size / 100; + } + if ($new_size > 1) { + return (int) $new_size; + } elseif ($new_size == 0) { + return (int) $old_size; + } else { + return (int) round($new_size * $old_size, 0); + } + } + + + function uniqueStr() + { + return substr(md5(microtime()),0,6); + } + + //delete old tmp files, and allow only 1 file per remote host. + function cleanUp($id, $dir) + { + $d = dir($dir); + $id_length = strlen($id); + + while (false !== ($entry = $d->read())) { + if (is_file($dir.'/'.$entry) && substr($entry,0,1) == '.' && !ereg($entry, $this->image)) + { + //echo filemtime($this->directory.'/'.$entry)."
    "; + //echo time(); + + if (filemtime($dir.'/'.$entry) + $this->lapse_time < time()) + unlink($dir.'/'.$entry); + + if (substr($entry, 1, $id_length) == $id) + { + if (is_file($dir.'/'.$entry)) + unlink($dir.'/'.$entry); + } + } + } + $d->close(); + } + + + function createUnique($dir) + { + $unique_str = '.'.$this->uid.'_'.$this->uniqueStr().".".$this->type; + + //make sure the the unique temp file does not exists + while (file_exists($dir.$unique_str)) + { + $unique_str = '.'.$this->uid.'_'.$this->uniqueStr().".".$this->type; + } + + $this->cleanUp($this->uid, $dir); + + return $unique_str; + } + + + /** + * Set the image width + * @param int $size dimension to set + * @since 29/05/02 13:36:31 + * @return + */ + function _set_img_x($size) + { + $this->img_x = $size; + } + + /** + * Set the image height + * @param int $size dimension to set + * @since 29/05/02 13:36:31 + * @return + */ + function _set_img_y($size) + { + $this->img_y = $size; + } + + /** + * Set the image width + * @param int $size dimension to set + * @since 29/05/02 13:36:31 + * @return + */ + function _set_new_x($size) + { + $this->new_x = $size; + } + + /** + * Set the image height + * @param int $size dimension to set + * @since 29/05/02 13:36:31 + * @return + */ + function _set_new_y($size) + { + $this->new_y = $size; + } + + /** + * Get the type of the image being manipulated + * + * @return string $this->type the image type + */ + function getImageType() + { + return $this->type; + } + + /** + * + * @access public + * @return string web-safe image type + */ + function getWebSafeFormat() + { + switch($this->type){ + case 'gif': + case 'png': + return 'png'; + break; + default: + return 'jpeg'; + } // switch + } + + /** + * Place holder for the real resize method + * used by extended methods to do the resizing + * + * @access private + * @return PEAR_error + */ + function _resize() { + return null; //PEAR::raiseError("No Resize method exists", true); + } + + /** + * Place holder for the real load method + * used by extended methods to do the resizing + * + * @access public + * @return PEAR_error + */ + function load($filename) { + return null; //PEAR::raiseError("No Load method exists", true); + } + + /** + * Place holder for the real display method + * used by extended methods to do the resizing + * + * @access public + * @param string filename + * @return PEAR_error + */ + function display($type, $quality) { + return null; //PEAR::raiseError("No Display method exists", true); + } + + /** + * Place holder for the real save method + * used by extended methods to do the resizing + * + * @access public + * @param string filename + * @return PEAR_error + */ + function save($filename, $type, $quality) { + return null; //PEAR::raiseError("No Save method exists", true); + } + + /** + * Place holder for the real free method + * used by extended methods to do the resizing + * + * @access public + * @return PEAR_error + */ + function free() { + return null; //PEAR::raiseError("No Free method exists", true); + } + + /** + * Reverse of rgb2colorname. + * + * @access public + * @return PEAR_error + * + * @see rgb2colorname + */ + function colorhex2colorarray($colorhex) { + $r = hexdec(substr($colorhex, 1, 2)); + $g = hexdec(substr($colorhex, 3, 2)); + $b = hexdec(substr($colorhex, 4, 2)); + return array($r,$g,$b); + } + + /** + * Reverse of rgb2colorname. + * + * @access public + * @return PEAR_error + * + * @see rgb2colorname + */ + function colorarray2colorhex($color) { + $color = '#'.dechex($color[0]).dechex($color[1]).dechex($color[2]); + return strlen($color)>6?false:$color; + } + + + /* Methods to add to the driver classes in the future */ + function addText() + { + return null; //PEAR::raiseError("No addText method exists", true); + } + + function addDropShadow() + { + return null; //PEAR::raiseError("No AddDropShadow method exists", true); + } + + function addBorder() + { + return null; //PEAR::raiseError("No addBorder method exists", true); + } + + function crop() + { + return null; //PEAR::raiseError("No crop method exists", true); + } + + function flip() + { + return null; + } + + function gamma() + { + return null; //PEAR::raiseError("No gamma method exists", true); + } +} +?> diff --git a/fckeditor/editor/plugins/ImageManager/Classes/api.watermark.php b/fckeditor/editor/plugins/ImageManager/Classes/api.watermark.php new file mode 100644 index 0000000..5422af9 --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/Classes/api.watermark.php @@ -0,0 +1,104 @@ + - small changes to place the watermark on a given coordinate and to only handle watermark area + * @version $Id: api.watermark.php,v 1.1.1.1 2009/09/17 20:08:58 matrix Exp $ + * @package ImageManager + */ + +class watermark{ + + # given two images, return a blended watermarked image + function create_watermark( $main_img_obj, $watermark_img_obj, $alpha_level = 100, $watermarkX = -1, $watermarkY = -1 ) { + $alpha_level /= 100; # convert 0-100 (%) alpha to decimal + + # calculate our images dimensions + $main_img_obj_w = imagesx( $main_img_obj ); + $main_img_obj_h = imagesy( $main_img_obj ); + $watermark_img_obj_w = imagesx( $watermark_img_obj ); + $watermark_img_obj_h = imagesy( $watermark_img_obj ); + + # determine watermark area for given coordinates + if ($watermarkX > - 1 && $watermarkY > -1) + { + $main_img_obj_min_x = $watermarkX; + $main_img_obj_max_x = $watermarkX + $watermark_img_obj_w; + $main_img_obj_min_y = $watermarkY; + $main_img_obj_max_y = $watermarkY + $watermark_img_obj_h; + } + # determine watermark area when centered + else + { + $main_img_obj_min_x = floor( ( $main_img_obj_w / 2 ) - ( $watermark_img_obj_w / 2 ) ); + $main_img_obj_max_x = ceil( ( $main_img_obj_w / 2 ) + ( $watermark_img_obj_w / 2 ) ); + $main_img_obj_min_y = floor( ( $main_img_obj_h / 2 ) - ( $watermark_img_obj_h / 2 ) ); + $main_img_obj_max_y = ceil( ( $main_img_obj_h / 2 ) + ( $watermark_img_obj_h / 2 ) ); + } + + # create image copy to hold merged changes + $return_img = $main_img_obj; + + # walk through the watermark area + for( $y = $main_img_obj_min_y; $y < $main_img_obj_max_y; $y++ ) { + for( $x = $main_img_obj_min_x; $x < $main_img_obj_max_x; $x++ ) { + $return_color = NULL; + + # determine the correct pixel location within our watermark + $watermark_x = $x - $main_img_obj_min_x; + $watermark_y = $y - $main_img_obj_min_y; + + # fetch color information for both of our images + $main_rgb = imagecolorsforindex( $main_img_obj, imagecolorat( $main_img_obj, $x, $y ) ); + + # if our watermark has a non-transparent value at this pixel intersection + # and we're still within the bounds of the watermark image + if ( $watermark_x >= 0 && $watermark_x < $watermark_img_obj_w && + $watermark_y >= 0 && $watermark_y < $watermark_img_obj_h ) { + $watermark_rbg = imagecolorsforindex( $watermark_img_obj, imagecolorat( $watermark_img_obj, $watermark_x, $watermark_y ) ); + + # using image alpha, and user specified alpha, calculate average + $watermark_alpha = round( ( ( 127 - $watermark_rbg['alpha'] ) / 127 ), 2 ); + $watermark_alpha = $watermark_alpha * $alpha_level; + + # calculate the color 'average' between the two - taking into account the specified alpha level + $avg_red = $this->_get_ave_color( $main_rgb['red'], $watermark_rbg['red'], $watermark_alpha ); + $avg_green = $this->_get_ave_color( $main_rgb['green'], $watermark_rbg['green'], $watermark_alpha ); + $avg_blue = $this->_get_ave_color( $main_rgb['blue'], $watermark_rbg['blue'], $watermark_alpha ); + + # calculate a color index value using the average RGB values we've determined + $return_color = $this->_get_image_color( $return_img, $avg_red, $avg_green, $avg_blue ); + + # if we're not dealing with an average color here, then let's just copy over the main color + } else { + $return_color = imagecolorat( $main_img_obj, $x, $y ); + + } # END if watermark + + # draw the appropriate color onto the return image + imagesetpixel( $return_img, $x, $y, $return_color ); + + } # END for each X pixel + } # END for each Y pixel + + # return the resulting, watermarked image for display + return $return_img; + + } # END create_watermark() + + # average two colors given an alpha + function _get_ave_color( $color_a, $color_b, $alpha_level ) { + return round( ( ( $color_a * ( 1 - $alpha_level ) ) + ( $color_b * $alpha_level ) ) ); + } # END _get_ave_color() + + # return closest pallette-color match for RGB values + function _get_image_color($im, $r, $g, $b) { + $c=imagecolorexact($im, $r, $g, $b); + if ($c>0) return $c; + $c=imagecolorallocate($im, $r, $g, $b); + if ($c>0) return $c; + return imagecolorclosest($im, $r, $g, $b); + } # EBD _get_image_color() + +} # END watermark API +?> diff --git a/fckeditor/editor/plugins/ImageManager/Classes/package.xml b/fckeditor/editor/plugins/ImageManager/Classes/package.xml new file mode 100644 index 0000000..96ebab2 --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/Classes/package.xml @@ -0,0 +1,49 @@ + + + + Image_Transform + Provides a standard interface to manipulate images using different libraries + This package was written to provide a simpler and cross-library interface to doing image transformations and manipulations. +It provides : + +* support for GD, ImageMagick, Imagick and NetPBM +* files related functions +* addText +* Scale (by length, percentage, maximum X/Y) +* Resize +* Rotate (custom angle) +* Add border (soon) +* Add shadow (soon) + + + reywob + Peter Bowyer + peter@mapledesign.co.uk + lead + + + pajoye + Pierre-Alain Joye + paj@pearfr.org + lead + + + + 0.8 + 2003-12-29 + PHP License + alpha + Second public release, hopefully much more stable. API nearly fixed. NOT NECESSARILY COMPATIBLE WITH 0.1 - be warned! + + + + + + + + + + + + + diff --git a/fckeditor/editor/plugins/ImageManager/README.txt b/fckeditor/editor/plugins/ImageManager/README.txt new file mode 100644 index 0000000..8ad79b5 --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/README.txt @@ -0,0 +1,47 @@ +Below are the steps required to setup the Wei Zhuo's Image Manager (http://www.zhuo.org/htmlarea/) +as a plugin for FCKeditor. + +----------------------------- +SETTING UP THE IMAGE MANAGER: +----------------------------- + +- Firstly extract the archive to the editor/plugins directory +- Edit the file 'editor/plugins/ImageManager/config.inc.php' to configure the plugin. + +--------------------------- +INSTALLING AS A FCK PLUGIN: +--------------------------- + +The required fckplugin.js file is already in the archive, so all you need to do is update fckconfig.js (in the root directory) and make the following updates: + +- The language for the plugin and to directEdit option must be set in its 'editor/plugins/ImageManager/fckplugin.js' file. +- Add the plugin to your FCKeditor by opening you 'fckconfig.js' file and update the 'FCKConfig.ToolbarSets' you're using by replacing 'Image' with 'ImageManager'; + Register the plugin with the following statement: "FCKConfig.Plugins.Add('ImageManager');" +- Done. (Should the toolbar icon not appear, try to clear your browser's cache) + + +-------------------------------------------------------------- +UPDATING THE CONTEXT MENU FOR IMAGES TO USE THE IMAGE MANAGER: +-------------------------------------------------------------- + +Copy an icon for the image manager for the popup context menu +cp /editor/skins/default/toolbar/image.gif /editor/skins/default/toolbar/imagemanager.gif + +edit editor/_source/internals/fckcontextmenu.js + - search for 'FCKLang.ImageProperties' + - replace the string in the parameter before the above mentioned one from 'Image' to 'ImageManager'. + the line should now read: return new FCKContextMenuGroup( true, this, 'ImageManager', FCKLang.ImageProperties, true ) ; + +This updates the _source context menu to use the image manager. However to avoid having to recompile the whole thing, also need to update the compiled versions too so also repeat the above on the following files: + + - editor/js/fckeditorcode_gecko_2.js + - editor/js/fckeditorcode_ie_2.js + + +Enjoy! +Brent Kelly +Zeald.com +http://www.zeald.com + +Paul Moers +http://www.saulmade.nl \ No newline at end of file diff --git a/fckeditor/editor/plugins/ImageManager/assets/EditorContent.js b/fckeditor/editor/plugins/ImageManager/assets/EditorContent.js new file mode 100644 index 0000000..bd7aae0 --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/assets/EditorContent.js @@ -0,0 +1,744 @@ +/*********************************************************************** +** Title.........: Online Image Editor Interface +** Version.......: 1.0 +** Author........: Xiang Wei ZHUO +** Filename......: EditorContents.js +** Last changed..: 31 Mar 2004 +** Notes.........: Handles most of the interface routines for the ImageEditor. +* +* Added: 29 Mar 2004 - Constrainted resizing/scaling +**/ + + +function MM_findObj(n, d) { //v4.01 + var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { + d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} + if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i-1 && navigator.appVersion.indexOf("Mac")>-1)) { + ox=0;oy=0;if(g.style.left){x=parseInt(g.style.left);y=parseInt(g.style.top); + }else{var w1=parseInt(el.style.width);bx=(a<0)?-5-w1:-10; + a=(Math.abs(a)<1000)?0:a;b=(Math.abs(b)<1000)?0:b; + //alert(event.clientX); + if (window.event == null) x=document.body.scrollLeft + bx; + else x=document.body.scrollLeft + event.clientX + bx; + if (window.event == null) y=document.body.scrollTop; + else y=document.body.scrollTop + event.clientY;}} + }else if (document.layers) {x=g.x;y=g.y;var q0=document.layers,dd=""; + for(var s=0;s4){xx+="px";yy+="px";} + if(navigator.appVersion.indexOf("MSIE 5")>-1 && navigator.appVersion.indexOf("Mac")>-1){ + xx+=parseInt(document.body.leftMargin);yy+=parseInt(document.body.topMargin); + xx+="px";yy+="px";}e.left=xx;e.top=yy;} + pic_x = parseInt(xx); pic_y = parseInt(yy); + //alert(xx+":"+yy); + } +} + +var ie=document.all +var ns6=document.getElementById&&!document.all + +var dragapproved=false +var z,x,y,status, ant, canvas, content, pic_width, pic_height, image, resizeHandle, oa_w, oa_h, oa_x, oa_y, mx2, my2; + + +function init_resize() +{ + if(mode == "scale") + { + P7_Snap('theImage','ant',0,0); + + if (canvas == null) + canvas = MM_findObj("imgCanvas"); + + if (pic_width == null || pic_height == null) + { + image = MM_findObj("theImage"); + pic_width = image.width; + pic_height = image.height; + } + + if (ant == null) + ant = MM_findObj("ant"); + + ant.style.left = pic_x; ant.style.top = pic_y; + ant.style.width = pic_width; ant.style.height = pic_height; + ant.style.visibility = "visible"; + + drawBoundHandle(); + jg_doc.paint(); + } +} + +initEditor = function () +{ + init_crop(); + init_resize(); + var markerImg = MM_findObj('markerImg', window.top.document); + + if (markerImg.src.indexOf("img/t_white.gif")>0) + toggleMarker() ; +} + +function init_crop() +{ + //if(mode == "crop") { + P7_Snap('theImage','ant',0,0); + //} +} + +function setMode(newMode) +{ + mode = newMode; + reset(); +} + +function reset() +{ + if (ant == null) + ant = MM_findObj("ant"); + + ant.style.visibility = "hidden"; + ant.style.left = 0; + ant.style.top = 0; + ant.style.width = 0; + ant.style.height = 0; + + mx2 = null; + my2 = null; + + jg_doc.clear(); + if(mode != 'measure') + showStatus(); + + if(mode == "scale") { + init_resize(); + } + + P7_Snap('theImage','ant',0,0); +} + +function toggleMarker() +{ + //alert("Toggle"); + if (ant == null) + ant = MM_findObj("ant"); + + if(ant.className=="selection") + ant.className="selectionWhite"; + else + ant.className="selection"; + + if (jg_doc.getColor() == "#000000") + jg_doc.setColor("#FFFFFF"); + else + jg_doc.setColor("#000000"); + + drawBoundHandle + jg_doc.paint(); +} + + +function move(e) +{ + if (dragapproved) + { + //z.style.left=ns6? temp1+e.clientX-x: temp1+event.clientX-x + //z.style.top=ns6? temp2+e.clientY-y : temp2+event.clientY-y + var w = ns6? temp1+e.clientX - x : temp1+event.clientX - x; + var h = ns6? temp2+e.clientY - y : temp2+event.clientY - y; + + //alert(canvas.style.left); + /*if (status !=null) + { + status.innerHTML = "x:"+x+" y:"+y+" w:"+w+" h:"+h+" can_h:"+pic_height; + status.innerHTML += " can_w:"+pic_width+" px:"+pic_x+" py:"+pic_y; + status.innerHTML += " pix:"+image.style.left+" piy:"+image.style.top+" obj:"+obj.id; + }*/ + + /*jg_doc.clear(); + jg_doc.fillRectPattern(0,0,Math.abs(w),Math.abs(h),pattern); + jg_doc.paint(); +*/ + if (ant != null) + { + if (w >= 0) + { + ant.style.left = x; + ant.style.width = w; + } + else + { + ant.style.left = x+w; + ant.style.width = -1*w; + } + + if (h >= 0) + { + ant.style.top = y; + ant.style.height = h; + } + else + { + ant.style.top = y+h; + ant.style.height = -1*h + } + } + + showStatus(); + return false + } +} + +function moveContent(e) +{ + if (dragapproved) + { + + var dx =ns6? oa_x + e.clientX-x: oa_x + event.clientX-x + var dy =ns6? oa_y + e.clientY-y : oa_y + event.clientY-y + + + /*if (status !=null) + { + status.innerHTML = "x:"+x+" y:"+y+" dx:"+dx+" dy:"+dy; + }*/ + + ant.style.left = dx; + ant.style.top = dy; + + showStatus(); + + return false; + } +} + +//Code add for constraints by Frédéric Klee +function moveHandle(e) +{ + if (dragapproved) + { + var w = ns6? e.clientX - x : event.clientX - x; + var h = ns6? e.clientY - y : event.clientY - y; + + var constrained = MM_findObj('constProp', window.top.document); + var orginal_height = document.theImage.height ; + var orginal_width = document.theImage.width ; + rapp = orginal_width/orginal_height ; + rapp_inv = orginal_height / orginal_width ; + + switch(resizeHandle) + { + + case "s-resize": + if (oa_h + h >= 0) + { + ant.style.height = oa_h + h; + if(constrained.checked) + { + ant.style.width = rapp * (oa_h + h) ; + ant.style.left = oa_x - rapp * h/2; + } + + } + break; + case "e-resize": + if(oa_w + w >= 0) + { + ant.style.width = oa_w + w; + if(constrained.checked) + { + ant.style.height = rapp_inv * (oa_w + w) ; + ant.style.top = oa_y - rapp_inv * w/2; + } + + } + break; + case "n-resize": + if (oa_h - h >= 0) + { + ant.style.top = oa_y + h; + ant.style.height = oa_h - h; + if(constrained.checked) + { + ant.style.width = rapp * (oa_h - h) ; + ant.style.left = oa_x + rapp * h/2; + } + + } + break; + case "w-resize": + if(oa_w - w >= 0) + { + ant.style.left = oa_x + w; + ant.style.width = oa_w - w; + if(constrained.checked) + { + ant.style.height = rapp_inv * (oa_w - w) ; + ant.style.top = oa_y + rapp_inv * w/2; + } + + }break; + case "nw-resize": + if(oa_h - h >= 0 && oa_w - w >= 0) { + ant.style.left = oa_x + w; + ant.style.width = oa_w - w; + ant.style.top = oa_y + h; + if(constrained.checked) + ant.style.height = rapp_inv * (oa_w - w) ; + else + ant.style.height = oa_h - h; + } + break; + case "ne-resize": + if (oa_h - h >= 0 && oa_w + w >= 0){ + ant.style.top = oa_y + h; + ant.style.width = oa_w + w; + if(constrained.checked) + ant.style.height = rapp_inv * (oa_w + w) ; + else + ant.style.height = oa_h - h; + } + break; + case "se-resize": + if (oa_h + h >= 0 && oa_w + w >= 0) + { + ant.style.width = oa_w + w; + if(constrained.checked) + ant.style.height = rapp_inv * (oa_w + w) ; + else + ant.style.height = oa_h + h; + } + break; + case "sw-resize": + if (oa_h + h >= 0 && oa_w - w >= 0) + { + ant.style.left = oa_x + w; + ant.style.width = oa_w - w; + if(constrained.checked) + ant.style.height = rapp_inv * (oa_w - w) ; + else + ant.style.height = oa_h + h; + } + } + + showStatus(); + return false; + + } +} + +function drags(e) +{ + if (!ie&&!ns6) + return + + var firedobj=ns6? e.target : event.srcElement + var topelement=ns6? "HTML" : "BODY" + + while (firedobj.tagName!=topelement&& + !(firedobj.className=="crop" + || firedobj.className=="handleBox" + || firedobj.className=="selection" || firedobj.className=="selectionWhite")) + { + firedobj=ns6? firedobj.parentNode : firedobj.parentElement + } + + if(firedobj.className=="handleBox") { + + if(content != null) { + if(content.width != null && content.height != null) { + content.width = 0; + content.height = 0; + } + //alert(content.width+":"+content.height); + } + resizeHandle = firedobj.id; + + /*if(status!=null) { + status.innerHTML = " obj:"+firedobj.id; + }*/ + + x=ns6? e.clientX: event.clientX + y=ns6? e.clientY: event.clientY + + oa_w = parseInt(ant.style.width); + oa_h = parseInt(ant.style.height); + oa_x = parseInt(ant.style.left); + oa_y = parseInt(ant.style.top); + + dragapproved=true + document.onmousemove=moveHandle; + return false; + } + else + if((firedobj.className == "selection" || firedobj.className=="selectionWhite")&& mode == "crop") { + + x=ns6? e.clientX: event.clientX + y=ns6? e.clientY: event.clientY + + oa_x = parseInt(ant.style.left); + oa_y = parseInt(ant.style.top); + + dragapproved=true + document.onmousemove=moveContent; + return false; + } + else + if (firedobj.className=="crop" && mode == "crop") + { + if(content != null) { + if(content.width != null && content.height != null) { + content.width = 0; + content.height = 0; + } + //alert(content.width+":"+content.height); + } + + if (status == null) + status = MM_findObj("status"); + + if (ant == null) + ant = MM_findObj("ant"); + + if (canvas == null) + canvas = MM_findObj("imgCanvas"); + if(content == null) { + content = MM_findObj("cropContent"); + } + + if (pic_width == null || pic_height == null) + { + image = MM_findObj("theImage"); + pic_width = image.width; + pic_height = image.height; + } + + ant.style.visibility = "visible"; + + obj = firedobj; + dragapproved=true + z=firedobj + temp1=parseInt(z.style.left+0) + temp2=parseInt(z.style.top+0) + x=ns6? e.clientX: event.clientX + y=ns6? e.clientY: event.clientY + document.onmousemove=move + return false + } + else if(firedobj.className=="crop" && mode == "measure") { + + if (ant == null) + ant = MM_findObj("ant"); + + if (canvas == null) + canvas = MM_findObj("imgCanvas"); + + x=ns6? e.clientX: event.clientX + y=ns6? e.clientY: event.clientY + + //jg_doc.draw + dragapproved=true + document.onmousemove=measure + + return false + } +} + +function measure(e) +{ + if (dragapproved) + { + mx2 = ns6? e.clientX : event.clientX; + my2 = ns6? e.clientY : event.clientY; + + jg_doc.clear(); + jg_doc.setStroke(Stroke.DOTTED); + jg_doc.drawLine(x,y,mx2,my2); + jg_doc.paint(); + showStatus(); + return false; + } +} + +function setMarker(nx,ny,nw,nh) +{ + if (ant == null) + ant = MM_findObj("ant"); + + if (canvas == null) + canvas = MM_findObj("imgCanvas"); + if(content == null) { + content = MM_findObj("cropContent"); + } + + if (pic_width == null || pic_height == null) + { + image = MM_findObj("theImage"); + pic_width = image.width; + pic_height = image.height; + } + + ant.style.visibility = "visible"; + + nx = pic_x + nx; + ny = pic_y + ny; + + if (nw >= 0) + { + ant.style.left = nx; + ant.style.width = nw; + } + else + { + ant.style.left = nx+nw; + ant.style.width = -1*nw; + } + + if (nh >= 0) + { + ant.style.top = ny; + ant.style.height = nh; + } + else + { + ant.style.top = ny+nh; + ant.style.height = -1*nh + } + + +} + +function max(x,y) +{ + if(y > x) + return x; + else + return y; +} + +function drawBoundHandle() +{ + if(ant == null || ant.style == null) + return false; + + var ah = parseInt(ant.style.height); + var aw = parseInt(ant.style.width); + var ax = parseInt(ant.style.left); + var ay = parseInt(ant.style.top); + + jg_doc.drawHandle(ax-15,ay-15,30,30,"nw-resize"); //upper left + jg_doc.drawHandle(ax-15,ay+ah-15,30,30,"sw-resize"); //lower left + jg_doc.drawHandle(ax+aw-15,ay-15,30,30,"ne-resize"); //upper right + jg_doc.drawHandle(ax+aw-15,ay+ah-15,30,30,"se-resize"); //lower right + + jg_doc.drawHandle(ax+max(15,aw/10),ay-8,aw-2*max(15,aw/10),8,"n-resize"); //top middle + jg_doc.drawHandle(ax+max(15,aw/10),ay+ah,aw-2*max(15,aw/10),8,"s-resize"); //bottom middle + jg_doc.drawHandle(ax-8, ay+max(15,ah/10),8,ah-2*max(15,ah/10),"w-resize"); //left middle + jg_doc.drawHandle(ax+aw, ay+max(15,ah/10),8,ah-2*max(15,ah/10),"e-resize"); //right middle + + + + jg_doc.drawHandleBox(ax-4,ay-4,8,8,"nw-resize"); //upper left + jg_doc.drawHandleBox(ax-4,ay+ah-4,8,8,"sw-resize"); //lower left + jg_doc.drawHandleBox(ax+aw-4,ay-4,8,8,"ne-resize"); //upper right + jg_doc.drawHandleBox(ax+aw-4,ay+ah-4,8,8,"se-resize"); //lower right + + jg_doc.drawHandleBox(ax+aw/2-4,ay-4,8,8,"n-resize"); //top middle + jg_doc.drawHandleBox(ax+aw/2-4,ay+ah-4,8,8,"s-resize"); //bottom middle + jg_doc.drawHandleBox(ax-4, ay+ah/2-4,8,8,"w-resize"); //left middle + jg_doc.drawHandleBox(ax+aw-4, ay+ah/2-4,8,8,"e-resize"); //right middle + + //jg_doc.paint(); +} + +function showStatus() +{ + if(ant == null || ant.style == null) { + return false; + } + + if(mode == "measure") { + //alert(pic_x); + mx1 = x - pic_x; + my1 = y - pic_y; + + mw = mx2 - x; + mh = my2 - y; + + md = parseInt(Math.sqrt(mw*mw + mh*mh)*100)/100; + + ma = (Math.atan(-1*mh/mw)/Math.PI)*180; + if(mw < 0 && mh < 0) + ma = ma+180; + + if (mw <0 && mh >0) + ma = ma - 180; + + ma = parseInt(ma*100)/100; + + if (m_sx != null && !isNaN(mx1)) + m_sx.value = mx1+"px"; + if (m_sy != null && !isNaN(my1)) + m_sy.value = my1+"px"; + if(m_w != null && !isNaN(mw)) + m_w.value = mw + "px"; + if(m_h != null && !isNaN(mh)) + m_h.value = mh + "px"; + + if(m_d != null && !isNaN(md)) + m_d.value = md + "px"; + if(m_a != null && !isNaN(ma)) + m_a.value = ma + ""; + + if(r_ra != null &&!isNaN(ma)) + r_ra.value = ma; + + //alert("mx1:"+mx1+" my1"+my1); + return false; + } + + var ah = parseInt(ant.style.height); + var aw = parseInt(ant.style.width); + var ax = parseInt(ant.style.left); + var ay = parseInt(ant.style.top); + + var cx = ax-pic_x<0?0:ax-pic_x; + var cy = ay-pic_y<0?0:ay-pic_y; + cx = cx>pic_width?pic_width:cx; + cy = cy>pic_height?pic_height:cy; + + var cw = ax-pic_x>0?aw:aw-(pic_x-ax); + var ch = ay-pic_y>0?ah:ah-(pic_y-ay); + + ch = ay+ah0 && s_sh.value.indexOf('%')>0) + { + sw = cw/pic_width; + sh = ch/pic_height; + } + if (s_sw != null) + s_sw.value = sw; + if (s_sh != null) + s_sh.value = sh; + } + +} + +function dragStopped() +{ + dragapproved=false; + + if(ant == null || ant.style == null) { + return false; + } + + if(mode == "measure") { + jg_doc.drawLine(x-4,y,x+4,y); + jg_doc.drawLine(x,y-4,x,y+4); + jg_doc.drawLine(mx2-4,my2,mx2+4,my2); + jg_doc.drawLine(mx2,my2-4,mx2,my2+4); + + jg_doc.paint(); + showStatus(); + return false; + } + var ah = parseInt(ant.style.height); + var aw = parseInt(ant.style.width); + var ax = parseInt(ant.style.left); + var ay = parseInt(ant.style.top); + jg_doc.clear(); + + if(content != null) { + if(content.width != null && content.height != null) { + content.width = aw-1; + content.height = ah-1; + } + //alert(content.width+":"+content.height); + } + if(mode == "crop") { + //alert(pic_y); + jg_doc.fillRectPattern(pic_x,pic_y,pic_width,ay-pic_y,pattern); + + var h1 = ah; + var y1 = ay; + if (ah+ay >= pic_height+pic_y) + h1 = pic_height+pic_y-ay; + else if (ay <= pic_y) + { + h1 = ay+ah-pic_y; + y1 = pic_y; + } + jg_doc.fillRectPattern(pic_x,y1,ax-pic_x,h1,pattern); + jg_doc.fillRectPattern(ax+aw,y1,pic_x+pic_width-ax-aw,h1,pattern); + jg_doc.fillRectPattern(pic_x,ay+ah,pic_width,pic_height+pic_y-ay-ah,pattern); + } + else if(mode == "scale") { + //alert("Resizing: iw:"+image.width+" nw:"+aw); + document.theImage.height = ah; + document.theImage.width = aw; + document.theImage.style.height = ah+" px"; + document.theImage.style.width = aw+" px"; + + P7_Snap('theImage','ant',0,0); + + //alert("After Resizing: iw:"+image.width+" nw:"+aw); + } + + drawBoundHandle(); + jg_doc.paint(); + + showStatus(); + return false; +} + +document.onmousedown=drags +document.onmouseup=dragStopped; + diff --git a/fckeditor/editor/plugins/ImageManager/assets/ImageEditor.css b/fckeditor/editor/plugins/ImageManager/assets/ImageEditor.css new file mode 100644 index 0000000..7cefe46 --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/assets/ImageEditor.css @@ -0,0 +1,76 @@ +.icons { + font: 11px Tahoma,Verdana,sans-serif; + color: #666699; + text-align: center; + text-decoration: none; + border: 1px solid #EEEEFF; + -Moz-Border-Radius: 6px 6px 6px 6px; +} + +body, td, p { + font: 11px Tahoma,Verdana,sans-serif; +} +.iconsOver { + font: 11px Tahoma,Verdana,sans-serif; + color: #666699; + text-align: center; + text-decoration: none; + background-color: #F9F9FF; + border: 1px solid #666699; + -Moz-Border-Radius: 6px 6px 6px 6px; +} +.topBar { + font: 11px Tahoma,Verdana,sans-serif; + color: #666699; +} +.iconsSel { + font: 11px Tahoma,Verdana,sans-serif; + color: #666699; + text-align: center; + text-decoration: none; + border: 1px solid #666699; + -Moz-Border-Radius: 6px 6px 6px 6px; +} +.iconText { + font: 11px Tahoma,Verdana,sans-serif; + color: #666699; + text-decoration: none; + text-align: center; +} +.measureStats{ + width: 50px; +} + +#slidercasing { + /*border:1px solid #CCCCCC; + background-color:#FFFFFF;*/ + width:100px; + height:5px; + position:relative; + z-index:4; + padding:10px; +} + + +#slidertrack { + position:relative; + border:1px solid #CCCCCC; + background-color:#FFFFCC; + z-index:5; + height:5px; +} + + +#sliderbar { + position:absolute; + z-index:6; + border:1px solid #CCCCCC; + background-color:#DDDDDD; + width:15px; + padding:0px; + height:20px; + cursor: pointer; + top:2px; +} + +select, input, button { font: 11px Tahoma,Verdana,sans-serif; } diff --git a/fckeditor/editor/plugins/ImageManager/assets/blank.gif b/fckeditor/editor/plugins/ImageManager/assets/blank.gif new file mode 100644 index 0000000..75b945d Binary files /dev/null and b/fckeditor/editor/plugins/ImageManager/assets/blank.gif differ diff --git a/fckeditor/editor/plugins/ImageManager/assets/dialog.js b/fckeditor/editor/plugins/ImageManager/assets/dialog.js new file mode 100644 index 0000000..8babe27 --- /dev/null +++ b/fckeditor/editor/plugins/ImageManager/assets/dialog.js @@ -0,0 +1,111 @@ +// Dialog v3.0 - Copyright (c) 2003-2004 interactivetools.com, inc. +// This copyright notice MUST stay intact for use (see license.txt). +// +// Portions (c) dynarch.com, 2003-2004 +// +// A free WYSIWYG editor replacement for " ; + } + + $Html .= '
    ' ; + + return $Html ; + } + + function IsCompatible() + { + global $HTTP_USER_AGENT ; + + if ( isset( $HTTP_USER_AGENT ) ) + $sAgent = $HTTP_USER_AGENT ; + else + $sAgent = $_SERVER['HTTP_USER_AGENT'] ; + + if ( strpos($sAgent, 'MSIE') !== false && strpos($sAgent, 'mac') === false && strpos($sAgent, 'Opera') === false ) + { + $iVersion = (float)substr($sAgent, strpos($sAgent, 'MSIE') + 5, 3) ; + return ($iVersion >= 5.5) ; + } + else if ( strpos($sAgent, 'Gecko/') !== false ) + { + $iVersion = (int)substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8) ; + return ($iVersion >= 20030210) ; + } + else + return false ; + } + + function GetConfigFieldString() + { + $sParams = '' ; + $bFirst = true ; + + foreach ( $this->Config as $sKey => $sValue ) + { + if ( $bFirst == false ) + $sParams .= '&' ; + else + $bFirst = false ; + + if ( $sValue === true ) + $sParams .= $this->EncodeConfig( $sKey ) . '=true' ; + else if ( $sValue === false ) + $sParams .= $this->EncodeConfig( $sKey ) . '=false' ; + else + $sParams .= $this->EncodeConfig( $sKey ) . '=' . $this->EncodeConfig( $sValue ) ; + } + + return $sParams ; + } + + function EncodeConfig( $valueToEncode ) + { + $chars = array( + '&' => '%26', + '=' => '%3D', + '"' => '%22' ) ; + + return strtr( $valueToEncode, $chars ) ; + } +} + +?> \ No newline at end of file diff --git a/fckeditor/fckeditor_php5-1.php b/fckeditor/fckeditor_php5-1.php new file mode 100644 index 0000000..3ef704c --- /dev/null +++ b/fckeditor/fckeditor_php5-1.php @@ -0,0 +1,164 @@ +) + function __construct( $instanceName ) + { + $this->InstanceName = $instanceName ; + $this->BasePath = '/fckeditor/' ; + $this->Width = '100%' ; + $this->Height = '200' ; + $this->ToolbarSet = 'Default' ; + $this->Value = '' ; + + $this->Config = array() ; + } + + function Create() + { + echo $this->CreateHtml() ; + } + + function CreateHtml() + { + $HtmlValue = htmlspecialchars( $this->Value ) ; + + $Html = '
    ' ; + + if ( $this->IsCompatible() ) + { + if ( isset( $_GET['fcksource'] ) && $_GET['fcksource'] == "true" ) + $File = 'fckeditor.original.html' ; + else + $File = 'fckeditor2.html' ; + + $Link = "{$this->BasePath}editor/{$File}?InstanceName={$this->InstanceName}" ; + + if ( $this->ToolbarSet != '' ) + $Link .= "&Toolbar={$this->ToolbarSet}" ; + + // Render the linked hidden field. + $Html .= "InstanceName}\" name=\"{$this->InstanceName}\" value=\"{$HtmlValue}\" style=\"display:none\" />" ; + + // Render the configurations hidden field. + $Html .= "InstanceName}___Config\" value=\"" . $this->GetConfigFieldString() . "\" style=\"display:none\" />" ; + + // Render the editor IFRAME. + $Html .= "" ; + } + else + { + if ( strpos( $this->Width, '%' ) === false ) + $WidthCSS = $this->Width . 'px' ; + else + $WidthCSS = $this->Width ; + + if ( strpos( $this->Height, '%' ) === false ) + $HeightCSS = $this->Height . 'px' ; + else + $HeightCSS = $this->Height ; + + $Html .= "" ; + } + + $Html .= '
    ' ; + + return $Html ; + } + + function IsCompatible() + { + global $HTTP_USER_AGENT ; + + if ( isset( $HTTP_USER_AGENT ) ) + $sAgent = $HTTP_USER_AGENT ; + else + $sAgent = $_SERVER['HTTP_USER_AGENT'] ; + + if ( strpos($sAgent, 'MSIE') !== false && strpos($sAgent, 'mac') === false && strpos($sAgent, 'Opera') === false ) + { + $iVersion = (float)substr($sAgent, strpos($sAgent, 'MSIE') + 5, 3) ; + return ($iVersion >= 5.5) ; + } + else if ( strpos($sAgent, 'Gecko/') !== false ) + { + $iVersion = (int)substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8) ; + return ($iVersion >= 20030210) ; + } + else + return false ; + } + + function GetConfigFieldString() + { + $sParams = '' ; + $bFirst = true ; + + foreach ( $this->Config as $sKey => $sValue ) + { + if ( $bFirst == false ) + $sParams .= '&' ; + else + $bFirst = false ; + + if ( $sValue === true ) + $sParams .= $this->EncodeConfig( $sKey ) . '=true' ; + else if ( $sValue === false ) + $sParams .= $this->EncodeConfig( $sKey ) . '=false' ; + else + $sParams .= $this->EncodeConfig( $sKey ) . '=' . $this->EncodeConfig( $sValue ) ; + } + + return $sParams ; + } + + function EncodeConfig( $valueToEncode ) + { + $chars = array( + '&' => '%26', + '=' => '%3D', + '"' => '%22' ) ; + + return strtr( $valueToEncode, $chars ) ; + } +} + +?> diff --git a/fckeditor/fckeditor_php5.php b/fckeditor/fckeditor_php5.php new file mode 100755 index 0000000..6106315 --- /dev/null +++ b/fckeditor/fckeditor_php5.php @@ -0,0 +1,164 @@ +) + function __construct( $instanceName ) + { + $this->InstanceName = $instanceName ; + $this->BasePath = '/fckeditor/' ; + $this->Width = '100%' ; + $this->Height = '200' ; + $this->ToolbarSet = 'Default' ; + $this->Value = '' ; + + $this->Config = array() ; + } + + function Create() + { + echo $this->CreateHtml() ; + } + + function CreateHtml() + { + $HtmlValue = htmlspecialchars( $this->Value ) ; + + $Html = '
    ' ; + + if ( $this->IsCompatible() ) + { + if ( isset( $_GET['fcksource'] ) && $_GET['fcksource'] == "true" ) + $File = 'fckeditor.original.html' ; + else + $File = 'fckeditor.html' ; + + $Link = "{$this->BasePath}editor/{$File}?InstanceName={$this->InstanceName}" ; + + if ( $this->ToolbarSet != '' ) + $Link .= "&Toolbar={$this->ToolbarSet}" ; + + // Render the linked hidden field. + $Html .= "InstanceName}\" name=\"{$this->InstanceName}\" value=\"{$HtmlValue}\" style=\"display:none\" />" ; + + // Render the configurations hidden field. + $Html .= "InstanceName}___Config\" value=\"" . $this->GetConfigFieldString() . "\" style=\"display:none\" />" ; + + // Render the editor IFRAME. + $Html .= "" ; + } + else + { + if ( strpos( $this->Width, '%' ) === false ) + $WidthCSS = $this->Width . 'px' ; + else + $WidthCSS = $this->Width ; + + if ( strpos( $this->Height, '%' ) === false ) + $HeightCSS = $this->Height . 'px' ; + else + $HeightCSS = $this->Height ; + + $Html .= "" ; + } + + $Html .= '
    ' ; + + return $Html ; + } + + function IsCompatible() + { + global $HTTP_USER_AGENT ; + + if ( isset( $HTTP_USER_AGENT ) ) + $sAgent = $HTTP_USER_AGENT ; + else + $sAgent = $_SERVER['HTTP_USER_AGENT'] ; + + if ( strpos($sAgent, 'MSIE') !== false && strpos($sAgent, 'mac') === false && strpos($sAgent, 'Opera') === false ) + { + $iVersion = (float)substr($sAgent, strpos($sAgent, 'MSIE') + 5, 3) ; + return ($iVersion >= 5.5) ; + } + else if ( strpos($sAgent, 'Gecko/') !== false ) + { + $iVersion = (int)substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8) ; + return ($iVersion >= 20030210) ; + } + else + return false ; + } + + function GetConfigFieldString() + { + $sParams = '' ; + $bFirst = true ; + + foreach ( $this->Config as $sKey => $sValue ) + { + if ( $bFirst == false ) + $sParams .= '&' ; + else + $bFirst = false ; + + if ( $sValue === true ) + $sParams .= $this->EncodeConfig( $sKey ) . '=true' ; + else if ( $sValue === false ) + $sParams .= $this->EncodeConfig( $sKey ) . '=false' ; + else + $sParams .= $this->EncodeConfig( $sKey ) . '=' . $this->EncodeConfig( $sValue ) ; + } + + return $sParams ; + } + + function EncodeConfig( $valueToEncode ) + { + $chars = array( + '&' => '%26', + '=' => '%3D', + '"' => '%22' ) ; + + return strtr( $valueToEncode, $chars ) ; + } +} + +?> \ No newline at end of file diff --git a/fckeditor/fckstyles.xml b/fckeditor/fckstyles.xml new file mode 100755 index 0000000..32e1ccf --- /dev/null +++ b/fckeditor/fckstyles.xml @@ -0,0 +1,56 @@ + + + + + + + + + + \ No newline at end of file diff --git a/fckeditor/fcktemplates.xml b/fckeditor/fcktemplates.xml new file mode 100755 index 0000000..d3d1dbc --- /dev/null +++ b/fckeditor/fcktemplates.xml @@ -0,0 +1,106 @@ + + + + + + + diff --git a/fckeditor/htaccess.txt b/fckeditor/htaccess.txt new file mode 100755 index 0000000..0ba7023 --- /dev/null +++ b/fckeditor/htaccess.txt @@ -0,0 +1,44 @@ +# +# FCKeditor - The text editor for Internet - http://www.fckeditor.net +# Copyright (C) 2003-2007 Frederico Caldeira Knabben +# +# == BEGIN LICENSE == +# +# Licensed under the terms of any of the following licenses at your +# choice: +# +# - GNU General Public License Version 2 or later (the "GPL") +# http://www.gnu.org/licenses/gpl.html +# +# - GNU Lesser General Public License Version 2.1 or later (the "LGPL") +# http://www.gnu.org/licenses/lgpl.html +# +# - Mozilla Public License Version 1.1 or later (the "MPL") +# http://www.mozilla.org/MPL/MPL-1.1.html +# +# == END LICENSE == +# +# ----------------------------------------------------------------------------- +# +# On some specific Linux installations you could face problems with Firefox. +# It could give you errors when loading the editor saying that some illegal +# characters were found (three strange chars in the beginning of the file). +# This could happen if you map the .js or .css files to PHP, for example. +# +# Those characters are the Byte Order Mask (BOM) of the Unicode encoded files. +# All FCKeditor files are Unicode encoded. +# +# Just rename this file to ".htaccess" and leave it in the editor directory. +# There are no security issues on doing it. It just sets the ".js" and ".css" +# files to their correct content types. +# + +AddType application/x-javascript .js +AddType text/css .css + +# +# If PHP is mapped to handle XML files, you could have some issues. The +# following will disable it. +# + +AddType text/xml .xml diff --git a/fckeditor/license.txt b/fckeditor/license.txt new file mode 100755 index 0000000..776d133 --- /dev/null +++ b/fckeditor/license.txt @@ -0,0 +1,1247 @@ +FCKeditor - The text editor for Internet - http://www.fckeditor.net +Copyright (C) 2003-2007 Frederico Caldeira Knabben + +Licensed under the terms of any of the following licenses at your +choice: + + - GNU General Public License Version 2 or later (the "GPL") + http://www.gnu.org/licenses/gpl.html + (See Appendix A) + + - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + http://www.gnu.org/licenses/lgpl.html + (See Appendix B) + + - Mozilla Public License Version 1.1 or later (the "MPL") + http://www.mozilla.org/MPL/MPL-1.1.html + (See Appendix C) + +You are not required to, but if you want to explicitly declare the +license you have chosen to be bound to when using, reproducing, +modifying and distributing this software, just include a text file +titled "legal.txt" in your version of this software, indicating your +license choice. In any case, your choice will not restrict any +recipient of your version of this software to use, reproduce, modify +and distribute this software under any of the above licenses. + +Appendix A: The GPL License +=========================== + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + +Appendix B: The LGPL License +============================ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + +Appendix C: The MPL License +=========================== + + MOZILLA PUBLIC LICENSE + Version 1.1 + + --------------- + +1. Definitions. + + 1.0.1. "Commercial Use" means distribution or otherwise making the + Covered Code available to a third party. + + 1.1. "Contributor" means each entity that creates or contributes to + the creation of Modifications. + + 1.2. "Contributor Version" means the combination of the Original + Code, prior Modifications used by a Contributor, and the Modifications + made by that particular Contributor. + + 1.3. "Covered Code" means the Original Code or Modifications or the + combination of the Original Code and Modifications, in each case + including portions thereof. + + 1.4. "Electronic Distribution Mechanism" means a mechanism generally + accepted in the software development community for the electronic + transfer of data. + + 1.5. "Executable" means Covered Code in any form other than Source + Code. + + 1.6. "Initial Developer" means the individual or entity identified + as the Initial Developer in the Source Code notice required by Exhibit + A. + + 1.7. "Larger Work" means a work which combines Covered Code or + portions thereof with code not governed by the terms of this License. + + 1.8. "License" means this document. + + 1.8.1. "Licensable" means having the right to grant, to the maximum + extent possible, whether at the time of the initial grant or + subsequently acquired, any and all of the rights conveyed herein. + + 1.9. "Modifications" means any addition to or deletion from the + substance or structure of either the Original Code or any previous + Modifications. When Covered Code is released as a series of files, a + Modification is: + A. Any addition to or deletion from the contents of a file + containing Original Code or previous Modifications. + + B. Any new file that contains any part of the Original Code or + previous Modifications. + + 1.10. "Original Code" means Source Code of computer software code + which is described in the Source Code notice required by Exhibit A as + Original Code, and which, at the time of its release under this + License is not already Covered Code governed by this License. + + 1.10.1. "Patent Claims" means any patent claim(s), now owned or + hereafter acquired, including without limitation, method, process, + and apparatus claims, in any patent Licensable by grantor. + + 1.11. "Source Code" means the preferred form of the Covered Code for + making modifications to it, including all modules it contains, plus + any associated interface definition files, scripts used to control + compilation and installation of an Executable, or source code + differential comparisons against either the Original Code or another + well known, available Covered Code of the Contributor's choice. The + Source Code can be in a compressed or archival form, provided the + appropriate decompression or de-archiving software is widely available + for no charge. + + 1.12. "You" (or "Your") means an individual or a legal entity + exercising rights under, and complying with all of the terms of, this + License or a future version of this License issued under Section 6.1. + For legal entities, "You" includes any entity which controls, is + controlled by, or is under common control with You. For purposes of + this definition, "control" means (a) the power, direct or indirect, + to cause the direction or management of such entity, whether by + contract or otherwise, or (b) ownership of more than fifty percent + (50%) of the outstanding shares or beneficial ownership of such + entity. + +2. Source Code License. + + 2.1. The Initial Developer Grant. + The Initial Developer hereby grants You a world-wide, royalty-free, + non-exclusive license, subject to third party intellectual property + claims: + (a) under intellectual property rights (other than patent or + trademark) Licensable by Initial Developer to use, reproduce, + modify, display, perform, sublicense and distribute the Original + Code (or portions thereof) with or without Modifications, and/or + as part of a Larger Work; and + + (b) under Patents Claims infringed by the making, using or + selling of Original Code, to make, have made, use, practice, + sell, and offer for sale, and/or otherwise dispose of the + Original Code (or portions thereof). + + (c) the licenses granted in this Section 2.1(a) and (b) are + effective on the date Initial Developer first distributes + Original Code under the terms of this License. + + (d) Notwithstanding Section 2.1(b) above, no patent license is + granted: 1) for code that You delete from the Original Code; 2) + separate from the Original Code; or 3) for infringements caused + by: i) the modification of the Original Code or ii) the + combination of the Original Code with other software or devices. + + 2.2. Contributor Grant. + Subject to third party intellectual property claims, each Contributor + hereby grants You a world-wide, royalty-free, non-exclusive license + + (a) under intellectual property rights (other than patent or + trademark) Licensable by Contributor, to use, reproduce, modify, + display, perform, sublicense and distribute the Modifications + created by such Contributor (or portions thereof) either on an + unmodified basis, with other Modifications, as Covered Code + and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, using, or + selling of Modifications made by that Contributor either alone + and/or in combination with its Contributor Version (or portions + of such combination), to make, use, sell, offer for sale, have + made, and/or otherwise dispose of: 1) Modifications made by that + Contributor (or portions thereof); and 2) the combination of + Modifications made by that Contributor with its Contributor + Version (or portions of such combination). + + (c) the licenses granted in Sections 2.2(a) and 2.2(b) are + effective on the date Contributor first makes Commercial Use of + the Covered Code. + + (d) Notwithstanding Section 2.2(b) above, no patent license is + granted: 1) for any code that Contributor has deleted from the + Contributor Version; 2) separate from the Contributor Version; + 3) for infringements caused by: i) third party modifications of + Contributor Version or ii) the combination of Modifications made + by that Contributor with other software (except as part of the + Contributor Version) or other devices; or 4) under Patent Claims + infringed by Covered Code in the absence of Modifications made by + that Contributor. + +3. Distribution Obligations. + + 3.1. Application of License. + The Modifications which You create or to which You contribute are + governed by the terms of this License, including without limitation + Section 2.2. The Source Code version of Covered Code may be + distributed only under the terms of this License or a future version + of this License released under Section 6.1, and You must include a + copy of this License with every copy of the Source Code You + distribute. You may not offer or impose any terms on any Source Code + version that alters or restricts the applicable version of this + License or the recipients' rights hereunder. However, You may include + an additional document offering the additional rights described in + Section 3.5. + + 3.2. Availability of Source Code. + Any Modification which You create or to which You contribute must be + made available in Source Code form under the terms of this License + either on the same media as an Executable version or via an accepted + Electronic Distribution Mechanism to anyone to whom you made an + Executable version available; and if made available via Electronic + Distribution Mechanism, must remain available for at least twelve (12) + months after the date it initially became available, or at least six + (6) months after a subsequent version of that particular Modification + has been made available to such recipients. You are responsible for + ensuring that the Source Code version remains available even if the + Electronic Distribution Mechanism is maintained by a third party. + + 3.3. Description of Modifications. + You must cause all Covered Code to which You contribute to contain a + file documenting the changes You made to create that Covered Code and + the date of any change. You must include a prominent statement that + the Modification is derived, directly or indirectly, from Original + Code provided by the Initial Developer and including the name of the + Initial Developer in (a) the Source Code, and (b) in any notice in an + Executable version or related documentation in which You describe the + origin or ownership of the Covered Code. + + 3.4. Intellectual Property Matters + (a) Third Party Claims. + If Contributor has knowledge that a license under a third party's + intellectual property rights is required to exercise the rights + granted by such Contributor under Sections 2.1 or 2.2, + Contributor must include a text file with the Source Code + distribution titled "LEGAL" which describes the claim and the + party making the claim in sufficient detail that a recipient will + know whom to contact. If Contributor obtains such knowledge after + the Modification is made available as described in Section 3.2, + Contributor shall promptly modify the LEGAL file in all copies + Contributor makes available thereafter and shall take other steps + (such as notifying appropriate mailing lists or newsgroups) + reasonably calculated to inform those who received the Covered + Code that new knowledge has been obtained. + + (b) Contributor APIs. + If Contributor's Modifications include an application programming + interface and Contributor has knowledge of patent licenses which + are reasonably necessary to implement that API, Contributor must + also include this information in the LEGAL file. + + (c) Representations. + Contributor represents that, except as disclosed pursuant to + Section 3.4(a) above, Contributor believes that Contributor's + Modifications are Contributor's original creation(s) and/or + Contributor has sufficient rights to grant the rights conveyed by + this License. + + 3.5. Required Notices. + You must duplicate the notice in Exhibit A in each file of the Source + Code. If it is not possible to put such notice in a particular Source + Code file due to its structure, then You must include such notice in a + location (such as a relevant directory) where a user would be likely + to look for such a notice. If You created one or more Modification(s) + You may add your name as a Contributor to the notice described in + Exhibit A. You must also duplicate this License in any documentation + for the Source Code where You describe recipients' rights or ownership + rights relating to Covered Code. You may choose to offer, and to + charge a fee for, warranty, support, indemnity or liability + obligations to one or more recipients of Covered Code. However, You + may do so only on Your own behalf, and not on behalf of the Initial + Developer or any Contributor. You must make it absolutely clear than + any such warranty, support, indemnity or liability obligation is + offered by You alone, and You hereby agree to indemnify the Initial + Developer and every Contributor for any liability incurred by the + Initial Developer or such Contributor as a result of warranty, + support, indemnity or liability terms You offer. + + 3.6. Distribution of Executable Versions. + You may distribute Covered Code in Executable form only if the + requirements of Section 3.1-3.5 have been met for that Covered Code, + and if You include a notice stating that the Source Code version of + the Covered Code is available under the terms of this License, + including a description of how and where You have fulfilled the + obligations of Section 3.2. The notice must be conspicuously included + in any notice in an Executable version, related documentation or + collateral in which You describe recipients' rights relating to the + Covered Code. You may distribute the Executable version of Covered + Code or ownership rights under a license of Your choice, which may + contain terms different from this License, provided that You are in + compliance with the terms of this License and that the license for the + Executable version does not attempt to limit or alter the recipient's + rights in the Source Code version from the rights set forth in this + License. If You distribute the Executable version under a different + license You must make it absolutely clear that any terms which differ + from this License are offered by You alone, not by the Initial + Developer or any Contributor. You hereby agree to indemnify the + Initial Developer and every Contributor for any liability incurred by + the Initial Developer or such Contributor as a result of any such + terms You offer. + + 3.7. Larger Works. + You may create a Larger Work by combining Covered Code with other code + not governed by the terms of this License and distribute the Larger + Work as a single product. In such a case, You must make sure the + requirements of this License are fulfilled for the Covered Code. + +4. Inability to Comply Due to Statute or Regulation. + + If it is impossible for You to comply with any of the terms of this + License with respect to some or all of the Covered Code due to + statute, judicial order, or regulation then You must: (a) comply with + the terms of this License to the maximum extent possible; and (b) + describe the limitations and the code they affect. Such description + must be included in the LEGAL file described in Section 3.4 and must + be included with all distributions of the Source Code. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + +5. Application of this License. + + This License applies to code to which the Initial Developer has + attached the notice in Exhibit A and to related Covered Code. + +6. Versions of the License. + + 6.1. New Versions. + Netscape Communications Corporation ("Netscape") may publish revised + and/or new versions of the License from time to time. Each version + will be given a distinguishing version number. + + 6.2. Effect of New Versions. + Once Covered Code has been published under a particular version of the + License, You may always continue to use it under the terms of that + version. You may also choose to use such Covered Code under the terms + of any subsequent version of the License published by Netscape. No one + other than Netscape has the right to modify the terms applicable to + Covered Code created under this License. + + 6.3. Derivative Works. + If You create or use a modified version of this License (which you may + only do in order to apply it to code which is not already Covered Code + governed by this License), You must (a) rename Your license so that + the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape", + "MPL", "NPL" or any confusingly similar phrase do not appear in your + license (except to note that your license differs from this License) + and (b) otherwise make it clear that Your version of the license + contains terms which differ from the Mozilla Public License and + Netscape Public License. (Filling in the name of the Initial + Developer, Original Code or Contributor in the notice described in + Exhibit A shall not of themselves be deemed to be modifications of + this License.) + +7. DISCLAIMER OF WARRANTY. + + COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, + WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF + DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. + THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE + IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, + YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE + COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER + OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF + ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. + +8. TERMINATION. + + 8.1. This License and the rights granted hereunder will terminate + automatically if You fail to comply with terms herein and fail to cure + such breach within 30 days of becoming aware of the breach. All + sublicenses to the Covered Code which are properly granted shall + survive any termination of this License. Provisions which, by their + nature, must remain in effect beyond the termination of this License + shall survive. + + 8.2. If You initiate litigation by asserting a patent infringement + claim (excluding declatory judgment actions) against Initial Developer + or a Contributor (the Initial Developer or Contributor against whom + You file such action is referred to as "Participant") alleging that: + + (a) such Participant's Contributor Version directly or indirectly + infringes any patent, then any and all rights granted by such + Participant to You under Sections 2.1 and/or 2.2 of this License + shall, upon 60 days notice from Participant terminate prospectively, + unless if within 60 days after receipt of notice You either: (i) + agree in writing to pay Participant a mutually agreeable reasonable + royalty for Your past and future use of Modifications made by such + Participant, or (ii) withdraw Your litigation claim with respect to + the Contributor Version against such Participant. If within 60 days + of notice, a reasonable royalty and payment arrangement are not + mutually agreed upon in writing by the parties or the litigation claim + is not withdrawn, the rights granted by Participant to You under + Sections 2.1 and/or 2.2 automatically terminate at the expiration of + the 60 day notice period specified above. + + (b) any software, hardware, or device, other than such Participant's + Contributor Version, directly or indirectly infringes any patent, then + any rights granted to You by such Participant under Sections 2.1(b) + and 2.2(b) are revoked effective as of the date You first made, used, + sold, distributed, or had made, Modifications made by that + Participant. + + 8.3. If You assert a patent infringement claim against Participant + alleging that such Participant's Contributor Version directly or + indirectly infringes any patent where such claim is resolved (such as + by license or settlement) prior to the initiation of patent + infringement litigation, then the reasonable value of the licenses + granted by such Participant under Sections 2.1 or 2.2 shall be taken + into account in determining the amount or value of any payment or + license. + + 8.4. In the event of termination under Sections 8.1 or 8.2 above, + all end user license agreements (excluding distributors and resellers) + which have been validly granted by You or any distributor hereunder + prior to termination shall survive termination. + +9. LIMITATION OF LIABILITY. + + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT + (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL + DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, + OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR + ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY + CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, + WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER + COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN + INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF + LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY + RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW + PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE + EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO + THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. + +10. U.S. GOVERNMENT END USERS. + + The Covered Code is a "commercial item," as that term is defined in + 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer + software" and "commercial computer software documentation," as such + terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 + C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), + all U.S. Government End Users acquire Covered Code with only those + rights set forth herein. + +11. MISCELLANEOUS. + + This License represents the complete agreement concerning subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. This License shall be governed by + California law provisions (except to the extent applicable law, if + any, provides otherwise), excluding its conflict-of-law provisions. + With respect to disputes in which at least one party is a citizen of, + or an entity chartered or registered to do business in the United + States of America, any litigation relating to this License shall be + subject to the jurisdiction of the Federal Courts of the Northern + District of California, with venue lying in Santa Clara County, + California, with the losing party responsible for costs, including + without limitation, court costs and reasonable attorneys' fees and + expenses. The application of the United Nations Convention on + Contracts for the International Sale of Goods is expressly excluded. + Any law or regulation which provides that the language of a contract + shall be construed against the drafter shall not apply to this + License. + +12. RESPONSIBILITY FOR CLAIMS. + + As between Initial Developer and the Contributors, each party is + responsible for claims and damages arising, directly or indirectly, + out of its utilization of rights under this License and You agree to + work with Initial Developer and Contributors to distribute such + responsibility on an equitable basis. Nothing herein is intended or + shall be deemed to constitute any admission of liability. + +13. MULTIPLE-LICENSED CODE. + + Initial Developer may designate portions of the Covered Code as + "Multiple-Licensed". "Multiple-Licensed" means that the Initial + Developer permits you to utilize portions of the Covered Code under + Your choice of the NPL or the alternative licenses, if any, specified + by the Initial Developer in the file described in Exhibit A. + +EXHIBIT A -Mozilla Public License. + + ``The contents of this file are subject to the Mozilla Public License + Version 1.1 (the "License"); you may not use this file except in + compliance with the License. You may obtain a copy of the License at + http://www.mozilla.org/MPL/ + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the + License for the specific language governing rights and limitations + under the License. + + The Original Code is ______________________________________. + + The Initial Developer of the Original Code is ________________________. + Portions created by ______________________ are Copyright (C) ______ + _______________________. All Rights Reserved. + + Contributor(s): ______________________________________. + + Alternatively, the contents of this file may be used under the terms + of the _____ license (the "[___] License"), in which case the + provisions of [______] License are applicable instead of those + above. If you wish to allow use of your version of this file only + under the terms of the [____] License and not to allow others to use + your version of this file under the MPL, indicate your decision by + deleting the provisions above and replace them with the notice and + other provisions required by the [___] License. If you do not delete + the provisions above, a recipient may use your version of this file + under either the MPL or the [___] License." + + [NOTE: The text of this Exhibit A may differ slightly from the text of + the notices in the Source Code files of the Original Code. You should + use the text of this Exhibit A rather than the text found in the + Original Code Source Code for Your Modifications.] + diff --git a/images/application_edit.png b/images/application_edit.png new file mode 100644 index 0000000..fb2efb8 Binary files /dev/null and b/images/application_edit.png differ diff --git a/images/cross.png b/images/cross.png new file mode 100644 index 0000000..1514d51 Binary files /dev/null and b/images/cross.png differ diff --git a/images/delete.png b/images/delete.png new file mode 100644 index 0000000..08f2493 Binary files /dev/null and b/images/delete.png differ diff --git a/images/error.gif b/images/error.gif new file mode 100644 index 0000000..48543cd Binary files /dev/null and b/images/error.gif differ diff --git a/images/file-ext/avi.gif b/images/file-ext/avi.gif new file mode 100644 index 0000000..9754248 Binary files /dev/null and b/images/file-ext/avi.gif differ diff --git a/images/file-ext/cad.gif b/images/file-ext/cad.gif new file mode 100644 index 0000000..3947208 Binary files /dev/null and b/images/file-ext/cad.gif differ diff --git a/images/file-ext/doc.gif b/images/file-ext/doc.gif new file mode 100644 index 0000000..7e053f5 Binary files /dev/null and b/images/file-ext/doc.gif differ diff --git a/images/file-ext/download.gif b/images/file-ext/download.gif new file mode 100644 index 0000000..d27f89e Binary files /dev/null and b/images/file-ext/download.gif differ diff --git a/images/file-ext/gif.gif b/images/file-ext/gif.gif new file mode 100644 index 0000000..2f1cd83 Binary files /dev/null and b/images/file-ext/gif.gif differ diff --git a/images/file-ext/html.gif b/images/file-ext/html.gif new file mode 100644 index 0000000..e92ab0c Binary files /dev/null and b/images/file-ext/html.gif differ diff --git a/images/file-ext/jpg.gif b/images/file-ext/jpg.gif new file mode 100644 index 0000000..2f1cd83 Binary files /dev/null and b/images/file-ext/jpg.gif differ diff --git a/images/file-ext/mov.gif b/images/file-ext/mov.gif new file mode 100644 index 0000000..9754248 Binary files /dev/null and b/images/file-ext/mov.gif differ diff --git a/images/file-ext/mp3.gif b/images/file-ext/mp3.gif new file mode 100644 index 0000000..6a41246 Binary files /dev/null and b/images/file-ext/mp3.gif differ diff --git a/images/file-ext/pdf.png b/images/file-ext/pdf.png new file mode 100644 index 0000000..e64037e Binary files /dev/null and b/images/file-ext/pdf.png differ diff --git a/images/file-ext/ppt.gif b/images/file-ext/ppt.gif new file mode 100644 index 0000000..4f0c034 Binary files /dev/null and b/images/file-ext/ppt.gif differ diff --git a/images/file-ext/rm.gif b/images/file-ext/rm.gif new file mode 100644 index 0000000..9754248 Binary files /dev/null and b/images/file-ext/rm.gif differ diff --git a/images/file-ext/txt.png b/images/file-ext/txt.png new file mode 100644 index 0000000..22e37ee Binary files /dev/null and b/images/file-ext/txt.png differ diff --git a/images/file-ext/wmv.gif b/images/file-ext/wmv.gif new file mode 100644 index 0000000..9754248 Binary files /dev/null and b/images/file-ext/wmv.gif differ diff --git a/images/file-ext/xls.gif b/images/file-ext/xls.gif new file mode 100644 index 0000000..9f5d57b Binary files /dev/null and b/images/file-ext/xls.gif differ diff --git a/images/file-ext/zip.png b/images/file-ext/zip.png new file mode 100644 index 0000000..6b75d4d Binary files /dev/null and b/images/file-ext/zip.png differ diff --git a/images/find.png b/images/find.png new file mode 100644 index 0000000..1547479 Binary files /dev/null and b/images/find.png differ diff --git a/images/flag_green.png b/images/flag_green.png new file mode 100644 index 0000000..e4bc611 Binary files /dev/null and b/images/flag_green.png differ diff --git a/images/grnball.gif b/images/grnball.gif new file mode 100755 index 0000000..5f7740b Binary files /dev/null and b/images/grnball.gif differ diff --git a/images/help.gif b/images/help.gif new file mode 100755 index 0000000..4915678 Binary files /dev/null and b/images/help.gif differ diff --git a/images/html.gif b/images/html.gif new file mode 100755 index 0000000..21e8e85 Binary files /dev/null and b/images/html.gif differ diff --git a/images/img.gif b/images/img.gif new file mode 100755 index 0000000..cd2c4a5 Binary files /dev/null and b/images/img.gif differ diff --git a/images/left.gif b/images/left.gif new file mode 100644 index 0000000..29d0ba1 Binary files /dev/null and b/images/left.gif differ diff --git a/images/loadingAnimation.gif b/images/loadingAnimation.gif new file mode 100644 index 0000000..92c5c30 Binary files /dev/null and b/images/loadingAnimation.gif differ diff --git a/images/logo.gif b/images/logo.gif new file mode 100755 index 0000000..cb56683 Binary files /dev/null and b/images/logo.gif differ diff --git a/images/mobilemgreen.jpg b/images/mobilemgreen.jpg new file mode 100644 index 0000000..a5fc6ce Binary files /dev/null and b/images/mobilemgreen.jpg differ diff --git a/images/mobilemred.jpg b/images/mobilemred.jpg new file mode 100644 index 0000000..217826d Binary files /dev/null and b/images/mobilemred.jpg differ diff --git a/images/note_edit.png b/images/note_edit.png new file mode 100644 index 0000000..291bfc7 Binary files /dev/null and b/images/note_edit.png differ diff --git a/images/page_edit.png b/images/page_edit.png new file mode 100644 index 0000000..046811e Binary files /dev/null and b/images/page_edit.png differ diff --git a/images/redball.gif b/images/redball.gif new file mode 100755 index 0000000..7005133 Binary files /dev/null and b/images/redball.gif differ diff --git a/images/right.gif b/images/right.gif new file mode 100644 index 0000000..d66a1ca Binary files /dev/null and b/images/right.gif differ diff --git a/images/shadowb.gif b/images/shadowb.gif new file mode 100644 index 0000000..72c4706 Binary files /dev/null and b/images/shadowb.gif differ diff --git a/images/shadowr.gif b/images/shadowr.gif new file mode 100644 index 0000000..f7e19d1 Binary files /dev/null and b/images/shadowr.gif differ diff --git a/images/size.sh b/images/size.sh new file mode 100755 index 0000000..2471ec3 --- /dev/null +++ b/images/size.sh @@ -0,0 +1,13 @@ +#! /bin/bash +convert='/usr/bin/convert' +composite='/usr/bin/composite' + +for file in original/* +do + temp=`basename $file` + $convert -scale '287>' $file resized/$temp + $convert -scale '210>' $file midsized/$temp + $convert -scale '120>' $file thumb/$temp + + echo $temp +done diff --git a/images/tick.png b/images/tick.png new file mode 100644 index 0000000..a9925a0 Binary files /dev/null and b/images/tick.png differ diff --git a/images/top2.jpg b/images/top2.jpg new file mode 100755 index 0000000..350fbe1 Binary files /dev/null and b/images/top2.jpg differ diff --git a/images/user_add.png b/images/user_add.png new file mode 100644 index 0000000..deae99b Binary files /dev/null and b/images/user_add.png differ diff --git a/images/user_edit.png b/images/user_edit.png new file mode 100644 index 0000000..c1974cd Binary files /dev/null and b/images/user_edit.png differ diff --git a/index.php b/index.php new file mode 100644 index 0000000..64282e2 --- /dev/null +++ b/index.php @@ -0,0 +1,40 @@ +getShortUrlId($_GET['glmPage'])) { + $catid = HOME_ID; + } +} else { + $catid = is_numeric($_GET['catid']) ? $_GET['catid'] : HOME_ID; +} +if ($catid != HOME_ID) { + require_once 'Text/CAPTCHA.php'; + require_once 'Text/CAPTCHA/Driver/Image.php'; +} +HTTP_Session2::useCookies(false); +HTTP_Session2::start(); +//session_start(); +require_once 'setup_functions.phtml'; + +// check that the setup file has been set for new customer +if (!strpos(BASE_URL, 'demo.gaslightmedia.com') && !CUSTOMER_SETUP_COMPLETE) { + die('Site is not setup. Please set all defines in setup.phtml'); +} + +$toolbox = new GLM_TEMPLATE($catid); + +// Initiate HTML_Template_Flexy. +$template = new HTML_Template_Flexy($flexyOptions); +// Page object used for merging with the flexy template object. +// now using the page class from toolkit +$gPage = new Toolkit_Page($toolbox); +$gPage->toolboxContent = $toolbox->get_page(); +//$gPage->toolboxContent .= '
    '.print_r($_GET, true).'
    '; + +// Compile the template.html from the templates directory. +$template->compile('template.html'); +// Merge compiled template with the $gPage object. +$template->outputObject($gPage); +?> diff --git a/libjs/cluetip/images/arrowdown.gif b/libjs/cluetip/images/arrowdown.gif new file mode 100755 index 0000000..bf5ba10 Binary files /dev/null and b/libjs/cluetip/images/arrowdown.gif differ diff --git a/libjs/cluetip/images/arrowleft.gif b/libjs/cluetip/images/arrowleft.gif new file mode 100755 index 0000000..26f1910 Binary files /dev/null and b/libjs/cluetip/images/arrowleft.gif differ diff --git a/libjs/cluetip/images/arrowright.gif b/libjs/cluetip/images/arrowright.gif new file mode 100755 index 0000000..df4291b Binary files /dev/null and b/libjs/cluetip/images/arrowright.gif differ diff --git a/libjs/cluetip/images/arrowup.gif b/libjs/cluetip/images/arrowup.gif new file mode 100755 index 0000000..5e59eec Binary files /dev/null and b/libjs/cluetip/images/arrowup.gif differ diff --git a/libjs/cluetip/images/bl.gif b/libjs/cluetip/images/bl.gif new file mode 100755 index 0000000..5bab228 Binary files /dev/null and b/libjs/cluetip/images/bl.gif differ diff --git a/libjs/cluetip/images/bl.png b/libjs/cluetip/images/bl.png new file mode 100755 index 0000000..39960c0 Binary files /dev/null and b/libjs/cluetip/images/bl.png differ diff --git a/libjs/cluetip/images/br.gif b/libjs/cluetip/images/br.gif new file mode 100755 index 0000000..a67d398 Binary files /dev/null and b/libjs/cluetip/images/br.gif differ diff --git a/libjs/cluetip/images/br.png b/libjs/cluetip/images/br.png new file mode 100755 index 0000000..b43a4f4 Binary files /dev/null and b/libjs/cluetip/images/br.png differ diff --git a/libjs/cluetip/images/darrowdown.gif b/libjs/cluetip/images/darrowdown.gif new file mode 100755 index 0000000..4d0ca91 Binary files /dev/null and b/libjs/cluetip/images/darrowdown.gif differ diff --git a/libjs/cluetip/images/darrowleft.gif b/libjs/cluetip/images/darrowleft.gif new file mode 100755 index 0000000..8cd3000 Binary files /dev/null and b/libjs/cluetip/images/darrowleft.gif differ diff --git a/libjs/cluetip/images/darrowright.gif b/libjs/cluetip/images/darrowright.gif new file mode 100755 index 0000000..d0b1cd5 Binary files /dev/null and b/libjs/cluetip/images/darrowright.gif differ diff --git a/libjs/cluetip/images/darrowup.gif b/libjs/cluetip/images/darrowup.gif new file mode 100755 index 0000000..6d85a99 Binary files /dev/null and b/libjs/cluetip/images/darrowup.gif differ diff --git a/libjs/cluetip/images/itunes.png b/libjs/cluetip/images/itunes.png new file mode 100755 index 0000000..6101957 Binary files /dev/null and b/libjs/cluetip/images/itunes.png differ diff --git a/libjs/cluetip/images/rarrowdown.gif b/libjs/cluetip/images/rarrowdown.gif new file mode 100755 index 0000000..f8296c7 Binary files /dev/null and b/libjs/cluetip/images/rarrowdown.gif differ diff --git a/libjs/cluetip/images/rarrowleft.gif b/libjs/cluetip/images/rarrowleft.gif new file mode 100755 index 0000000..4926b83 Binary files /dev/null and b/libjs/cluetip/images/rarrowleft.gif differ diff --git a/libjs/cluetip/images/rarrowright.gif b/libjs/cluetip/images/rarrowright.gif new file mode 100755 index 0000000..08ed75f Binary files /dev/null and b/libjs/cluetip/images/rarrowright.gif differ diff --git a/libjs/cluetip/images/rarrowup.gif b/libjs/cluetip/images/rarrowup.gif new file mode 100755 index 0000000..22c93c2 Binary files /dev/null and b/libjs/cluetip/images/rarrowup.gif differ diff --git a/libjs/cluetip/images/tl.gif b/libjs/cluetip/images/tl.gif new file mode 100755 index 0000000..9a2dd2e Binary files /dev/null and b/libjs/cluetip/images/tl.gif differ diff --git a/libjs/cluetip/images/tl.png b/libjs/cluetip/images/tl.png new file mode 100755 index 0000000..7c08f19 Binary files /dev/null and b/libjs/cluetip/images/tl.png differ diff --git a/libjs/cluetip/images/tr.gif b/libjs/cluetip/images/tr.gif new file mode 100755 index 0000000..faa2e74 Binary files /dev/null and b/libjs/cluetip/images/tr.gif differ diff --git a/libjs/cluetip/images/tr.png b/libjs/cluetip/images/tr.png new file mode 100755 index 0000000..d6293ea Binary files /dev/null and b/libjs/cluetip/images/tr.png differ diff --git a/libjs/cluetip/images/wait.gif b/libjs/cluetip/images/wait.gif new file mode 100755 index 0000000..8186b0c Binary files /dev/null and b/libjs/cluetip/images/wait.gif differ diff --git a/libjs/cluetip/jquery.cluetip.css b/libjs/cluetip/jquery.cluetip.css new file mode 100755 index 0000000..213282a --- /dev/null +++ b/libjs/cluetip/jquery.cluetip.css @@ -0,0 +1,235 @@ +/* global */ +#cluetip-close img { + border: 0; +} +#cluetip-title { + overflow: hidden; +} +#cluetip-title #cluetip-close { + float: right; + position: relative; +} +#cluetip-waitimage { + width: 43px; + height: 11px; + position: absolute; + background-image: url(wait.gif); +} +.cluetip-arrows { + display: none; + position: absolute; + top: 0; + left: -11px; + height: 22px; + width: 11px; + background-repeat: no-repeat; + background-position: 0 0; +} +#cluetip-extra { + display: none; +} +/*************************************** + =cluetipClass: 'default' +-------------------------------------- */ + +.cluetip-default { + background-color: #d9d9c2; + background-color: #006BB5; + background-color: #BFDCFF; +} +.cluetip-default #cluetip-outer { + position: relative; + margin: 0; + background-color: #ADC7E8; + background-color: #ADC7E8; + background-color: #D1DFEF; + text-align: left; +} +.cluetip-default h3#cluetip-title { + margin: 0 0 5px; + padding: 8px 10px 4px; + font-size: 1.1em; + font-weight: normal; + background-color: #006BB5; + color: #fff; +} +.cluetip-default #cluetip-title a { + color: #d9d9c2; + font-size: 0.95em; +} +.cluetip-default #cluetip-inner { + padding: 10px; +} +.cluetip-default div#cluetip-close { + text-align: right; + margin: 0 5px 5px; + color: #900; +} + +/* default arrows */ + +.clue-right-default .cluetip-arrows { + background-image: url(images/darrowleft.gif); +} +.clue-left-default .cluetip-arrows { + background-image: url(images/darrowright.gif); + left: 100%; + margin-right: -11px; +} +.clue-top-default .cluetip-arrows { + background-image: url(images/darrowdown.gif); + top: 100%; + left: 50%; + margin-left: -11px; + height: 11px; + width: 22px; +} +.clue-bottom-default .cluetip-arrows { + background-image: url(images/darrowup.gif); + top: -11px; + left: 50%; + margin-left: -11px; + height: 11px; + width: 22px; +} + +/*************************************** + =cluetipClass: 'jtip' +-------------------------------------- */ +.cluetip-jtip { + background-color: transparent; +} +.cluetip-jtip #cluetip-outer { + border: 2px solid #ccc; + position: relative; + background-color: #fff; +} + +.cluetip-jtip h3#cluetip-title { + margin: 0 0 5px; + padding: 2px 5px; + font-size: 16px; + font-weight: normal; + background-color: #ccc; + color: #333; +} + +.cluetip-jtip #cluetip-inner { + padding: 0 5px 5px; + display: inline-block; +} +.cluetip-jtip div#cluetip-close { + text-align: right; + margin: 0 5px 5px; + color: #900; +} + +/* jtip arrows */ + +.clue-right-jtip .cluetip-arrows { + background-image: url(images/arrowleft.gif); +} +.clue-left-jtip .cluetip-arrows { + background-image: url(images/arrowright.gif); + left: 100%; + margin-right: -11px; +} +.clue-top-jtip .cluetip-arrows { + background-image: url(images/arrowdown.gif); + top: 100%; + left: 50%; + margin-left: -11px; + height: 11px; + width: 22px; +} +.clue-bottom-jtip .cluetip-arrows { + background-image: url(images/arrowup.gif); + top: -11px; + left: 50%; + margin-left: -11px; + height: 11px; + width: 22px; +} + +/*************************************** + =cluetipClass: 'rounded' +-------------------------------------- */ + +.cluetip-rounded { + background: transparent url(images/bl.gif) no-repeat 0 100%; + margin-top: 10px; + margin-left: 12px; +} + +.cluetip-rounded #cluetip-outer { + background: transparent url(images/tl.gif) no-repeat 0 0; + margin-top: -12px; +} + +.cluetip-rounded #cluetip-title { + background-color: transparent; + padding: 12px 12px 0; + margin: 0 -12px 0 0; + position: relative; +} +.cluetip-rounded #cluetip-extra { + position: absolute; + display: block; + background: transparent url(images/tr.gif) no-repeat 100% 0; + top: 0; + right: 0; + width: 12px; + height: 30px; + margin: -12px -12px 0 0; +} +.cluetip-rounded #cluetip-inner { + background: url(images/br.gif) no-repeat 100% 100%; + padding: 5px 12px 12px; + margin: -18px -12px 0 0; + position: relative; +} + +.cluetip-rounded div#cluetip-close { + text-align: right; + margin: 0 5px 5px; + color: #009; + background: transparent; +} +.cluetip-rounded div#cluetip-close a { + color: #777; +} + +/* rounded arrows */ + +.clue-right-rounded .cluetip-arrows { + background-image: url(images/rarrowleft.gif); +} +.clue-left-rounded .cluetip-arrows { + background-image: url(images/rarrowright.gif); + left: 100%; + margin-left: 12px; +} +.clue-top-rounded .cluetip-arrows { + background-image: url(images/rarrowdown.gif); + top: 100%; + left: 50%; + margin-left: -11px; + height: 11px; + width: 22px; +} +.clue-bottom-rounded .cluetip-arrows { + background-image: url(images/rarrowup.gif); + top: -23px; + left: 50%; + margin-left: -11px; + height: 11px; + width: 22px; +} + + + +/* stupid IE6 HasLayout hack */ +.cluetip-rounded #cluetip-title, +.cluetip-rounded #cluetip-inner { + zoom: 1; +} \ No newline at end of file diff --git a/libjs/cluetip/jquery.cluetip.js b/libjs/cluetip/jquery.cluetip.js new file mode 100755 index 0000000..6be3258 --- /dev/null +++ b/libjs/cluetip/jquery.cluetip.js @@ -0,0 +1,519 @@ +/* + * jQuery clueTip plugin + * Version 0.9.9 (04/24/2009) + * @requires jQuery v1.1.4+ + * @requires Dimensions plugin IF USED WITH jQuery VERSIONS PRIOR TO 1.2.5) + * + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + */ + +/* + * + * Full list of options/settings can be found at the bottom of this file and at http://plugins.learningjquery.com/cluetip/ + * + * Examples can be found at http://plugins.learningjquery.com/cluetip/demo/ + * +*/ + +;(function($) { + + var $cluetip, $cluetipInner, $cluetipOuter, $cluetipTitle, $cluetipArrows, $dropShadow, imgCount; + $.fn.cluetip = function(js, options) { + if (typeof js == 'object') { + options = js; + js = null; + } + return this.each(function(index) { + var $this = $(this); + + // support metadata plugin (v1.0 and 2.0) + var opts = $.extend(true, {}, $.fn.cluetip.defaults, options || {}, $.metadata ? $this.metadata() : $.meta ? $this.data() : {}); + + // start out with no contents (for ajax activation) + var cluetipContents = false; + var cluezIndex = parseInt(opts.cluezIndex, 10)-1; + var isActive = false, closeOnDelay = 0; + + // create the cluetip divs + if (!$('#cluetip').length) { + $cluetipInner = $('
    '); + $cluetipTitle = $('

    '); + $cluetipOuter = $('
    ').append($cluetipInner).prepend($cluetipTitle); + $cluetip = $('
    ').css({zIndex: opts.cluezIndex}) + .append($cluetipOuter).append('
    ')[insertionType](insertionElement).hide(); + $('
    ').css({position: 'absolute', zIndex: cluezIndex-1}) + .insertBefore('#cluetip').hide(); + $cluetip.css({position: 'absolute', zIndex: cluezIndex}); + $cluetipOuter.css({position: 'relative', zIndex: cluezIndex+1}); + $cluetipArrows = $('
    ').css({zIndex: cluezIndex+1}).appendTo('#cluetip'); + } + var dropShadowSteps = (opts.dropShadow) ? +opts.dropShadowSteps : 0; + if (!$dropShadow) { + $dropShadow = $([]); + for (var i=0; i < dropShadowSteps; i++) { + $dropShadow = $dropShadow.add($('
    ').css({zIndex: cluezIndex-i-1, opacity:.1, top: 1+i, left: 1+i})); + }; + $dropShadow.css({position: 'absolute', backgroundColor: '#000'}) + .prependTo($cluetip); + } + var tipAttribute = $this.attr(opts.attribute), ctClass = opts.cluetipClass; + if (!tipAttribute && !opts.splitTitle && !js) return true; + // if hideLocal is set to true, on DOM ready hide the local content that will be displayed in the clueTip + if (opts.local && opts.localPrefix) {tipAttribute = opts.localPrefix + tipAttribute;} + if (opts.local && opts.hideLocal) { $(tipAttribute + ':first').hide(); } + var tOffset = parseInt(opts.topOffset, 10), lOffset = parseInt(opts.leftOffset, 10); + // vertical measurement variables + var tipHeight, wHeight; + var defHeight = isNaN(parseInt(opts.height, 10)) ? 'auto' : (/\D/g).test(opts.height) ? opts.height : opts.height + 'px'; + var sTop, linkTop, posY, tipY, mouseY, baseline; + // horizontal measurement variables + var tipInnerWidth = isNaN(parseInt(opts.width, 10)) ? 275 : parseInt(opts.width, 10); + var tipWidth = tipInnerWidth + (parseInt($cluetip.css('paddingLeft'),10)||0) + (parseInt($cluetip.css('paddingRight'),10)||0) + dropShadowSteps; + var linkWidth = this.offsetWidth; + var linkLeft, posX, tipX, mouseX, winWidth; + + // parse the title + var tipParts; + var tipTitle = (opts.attribute != 'title') ? $this.attr(opts.titleAttribute) : ''; + if (opts.splitTitle) { + if(tipTitle == undefined) {tipTitle = '';} + tipParts = tipTitle.split(opts.splitTitle); + tipTitle = tipParts.shift(); + } + if (opts.escapeTitle) { + tipTitle = tipTitle.replace(/&/g,'&').replace(/>/g,'>').replace(/ linkLeft && linkLeft > tipWidth) + || linkLeft + linkWidth + tipWidth + lOffset > winWidth + ? linkLeft - tipWidth - lOffset + : linkWidth + linkLeft + lOffset; + if ($this[0].tagName.toLowerCase() == 'area' || opts.positionBy == 'mouse' || linkWidth + tipWidth > winWidth) { // position by mouse + if (mouseX + 20 + tipWidth > winWidth) { + $cluetip.addClass(' cluetip-' + ctClass); + posX = (mouseX - tipWidth - lOffset) >= 0 ? mouseX - tipWidth - lOffset - parseInt($cluetip.css('marginLeft'),10) + parseInt($cluetipInner.css('marginRight'),10) : mouseX - (tipWidth/2); + } else { + posX = mouseX + lOffset; + } + } + var pY = posX < 0 ? event.pageY + tOffset : event.pageY; + $cluetip.css({left: (posX > 0 && opts.positionBy != 'bottomTop') ? posX : (mouseX + (tipWidth/2) > winWidth) ? winWidth/2 - tipWidth/2 : Math.max(mouseX - (tipWidth/2),0)}); + } + wHeight = $(window).height(); + +/*************************************** +* load a string from cluetip method's first argument +***************************************/ + if (js) { + if (typeof js == 'function') { + js = js($this[0]); + } + $cluetipInner.html(js); + cluetipShow(pY); + } +/*************************************** +* load the title attribute only (or user-selected attribute). +* clueTip title is the string before the first delimiter +* subsequent delimiters place clueTip body text on separate lines +***************************************/ + + else if (tipParts) { + var tpl = tipParts.length; + $cluetipInner.empty(); + for (var i=0; i < tpl; i++){ + if (i == 0) { + $cluetipInner.html(tipParts[i]); + } else { + $cluetipInner.append('
    ' + tipParts[i] + '
    '); + } + }; + cluetipShow(pY); + } +/*************************************** +* load external file via ajax +***************************************/ + + else if (!opts.local && tipAttribute.indexOf('#') != 0) { + if (/\.(jpe?g|tiff?|gif|png)$/i.test(tipAttribute)) { + $cluetipInner.html('' + tipTitle + ''); + cluetipShow(pY); + } else if (cluetipContents && opts.ajaxCache) { + $cluetipInner.html(cluetipContents); + cluetipShow(pY); + } else { + var ajaxSettings = opts.ajaxSettings; + ajaxSettings.cache = false; // force requested page not to be cached by browser + ajaxSettings.url = tipAttribute; + ajaxSettings.beforeSend = function() { + $cluetipOuter.children().empty(); + if (opts.waitImage) { + $('#cluetip-waitimage') + .css({top: mouseY+20, left: mouseX+20}) + .show(); + } + }; + ajaxSettings.error = function() { + if (isActive) { + $cluetipInner.html('sorry, the contents could not be loaded'); + } + }; + ajaxSettings.success = function(data) { + cluetipContents = opts.ajaxProcess(data); + if (isActive) { + $cluetipInner.html(cluetipContents); + } + }; + ajaxSettings.complete = function() { + imgCount = $('#cluetip-inner img').length; + if (imgCount && !$.browser.opera) { + $('#cluetip-inner img').load(function() { + imgCount--; + if (imgCount<1) { + $('#cluetip-waitimage').hide(); + if (isActive) cluetipShow(pY); + } + }); + } else { + $('#cluetip-waitimage').hide(); + if (isActive) cluetipShow(pY); + } + }; + $.ajax(ajaxSettings); + } + +/*************************************** +* load an element from the same page +***************************************/ + } else if (opts.local) { + + var $localContent = $(tipAttribute + (/#\w+$/.test(tipAttribute) ? '' : ':eq(' + index + ')')).clone(true).show(); + $cluetipInner.html($localContent); + cluetipShow(pY); + } + }; + +// get dimensions and options for cluetip and prepare it to be shown + var cluetipShow = function(bpY) { + $cluetip.addClass('cluetip-' + ctClass); + + if (opts.truncate) { + var $truncloaded = $cluetipInner.text().slice(0,opts.truncate) + '...'; + $cluetipInner.html($truncloaded); + } + function doNothing() {}; //empty function + tipTitle ? $cluetipTitle.show().html(tipTitle) : (opts.showTitle) ? $cluetipTitle.show().html(' ') : $cluetipTitle.hide(); + if (opts.sticky) { + var $closeLink = $(''); + (opts.closePosition == 'bottom') ? $closeLink.appendTo($cluetipInner) : (opts.closePosition == 'title') ? $closeLink.prependTo($cluetipTitle) : $closeLink.prependTo($cluetipInner); + $closeLink.click(function() { + cluetipClose(); + return false; + }); + if (opts.mouseOutClose) { + if ($.fn.hoverIntent && opts.hoverIntent) { + $cluetip.hoverIntent({ + over: doNothing, + timeout: opts.hoverIntent.timeout, + out: function() { $closeLink.trigger('click'); } + }); + } else { + $cluetip.hover(doNothing, + function() {$closeLink.trigger('click'); }); + } + } else { + $cluetip.unbind('mouseout'); + } + } +// now that content is loaded, finish the positioning + var direction = ''; + $cluetipOuter.css({overflow: defHeight == 'auto' ? 'visible' : 'auto', height: defHeight}); + tipHeight = defHeight == 'auto' ? Math.max($cluetip.outerHeight(),$cluetip.height()) : parseInt(defHeight,10); + tipY = posY; + baseline = sTop + wHeight; + if (opts.positionBy == 'fixed') { + tipY = posY - opts.dropShadowSteps + tOffset; + } else if ( (posX < mouseX && Math.max(posX, 0) + tipWidth > mouseX) || opts.positionBy == 'bottomTop') { + if (posY + tipHeight + tOffset > baseline && mouseY - sTop > tipHeight + tOffset) { + tipY = mouseY - tipHeight - tOffset; + direction = 'top'; + } else { + tipY = mouseY + tOffset; + direction = 'bottom'; + } + } else if ( posY + tipHeight + tOffset > baseline ) { + tipY = (tipHeight >= wHeight) ? sTop : baseline - tipHeight - tOffset; + } else if ($this.css('display') == 'block' || $this[0].tagName.toLowerCase() == 'area' || opts.positionBy == "mouse") { + tipY = bpY - tOffset; + } else { + tipY = posY - opts.dropShadowSteps; + } + if (direction == '') { + posX < linkLeft ? direction = 'left' : direction = 'right'; + } + $cluetip.css({top: tipY + 'px'}).removeClass().addClass('clue-' + direction + '-' + ctClass).addClass(' cluetip-' + ctClass); + if (opts.arrows) { // set up arrow positioning to align with element + var bgY = (posY - tipY - opts.dropShadowSteps); + $cluetipArrows.css({top: (/(left|right)/.test(direction) && posX >=0 && bgY > 0) ? bgY + 'px' : /(left|right)/.test(direction) ? 0 : ''}).show(); + } else { + $cluetipArrows.hide(); + } + +// (first hide, then) ***SHOW THE CLUETIP*** + $dropShadow.hide(); + $cluetip.hide()[opts.fx.open](opts.fx.open != 'show' && opts.fx.openSpeed); + if (opts.dropShadow) $dropShadow.css({height: tipHeight, width: tipInnerWidth}).show(); + if ($.fn.bgiframe) { $cluetip.bgiframe(); } + // delayed close (not fully tested) + if (opts.delayedClose > 0) { + closeOnDelay = setTimeout(cluetipClose, opts.delayedClose); + } + // trigger the optional onShow function + opts.onShow($cluetip, $cluetipInner); + + }; + +/*************************************** + =INACTIVATION +-------------------------------------- */ + var inactivate = function(event) { + isActive = false; + $('#cluetip-waitimage').hide(); + if (!opts.sticky || (/click|toggle/).test(opts.activation) ) { + cluetipClose(); +clearTimeout(closeOnDelay); + }; + if (opts.hoverClass) { + $this.removeClass(opts.hoverClass); + } + }; +// close cluetip and reset some things + var cluetipClose = function() { + $cluetipOuter + .parent().hide().removeClass(); + opts.onHide($cluetip, $cluetipInner); + $this.removeClass('cluetip-clicked'); + if (tipTitle) { + $this.attr(opts.titleAttribute, tipTitle); + } + $this.css('cursor',''); + if (opts.arrows) $cluetipArrows.css({top: ''}); + }; + +/*************************************** + =BIND EVENTS +-------------------------------------- */ + // activate by click + if ( (/click|toggle/).test(opts.activation) ) { + $this.click(function(event) { + if ($cluetip.is(':hidden') || !$this.is('.cluetip-clicked')) { + activate(event); + $('.cluetip-clicked').removeClass('cluetip-clicked'); + $this.addClass('cluetip-clicked'); + } else { + inactivate(event); + } + this.blur(); + return false; + }); + // activate by focus; inactivate by blur + } else if (opts.activation == 'focus') { + $this.focus(function(event) { + activate(event); + }); + $this.blur(function(event) { + inactivate(event); + }); + // activate by hover + // clicking is returned false if cluetip url is same as href url + } else { + $this.click(function() { + if ($this.attr('href') && $this.attr('href') == tipAttribute && !opts.clickThrough) { + return false; + } + }); + //set up mouse tracking + var mouseTracks = function(evt) { + if (opts.tracking == true) { + var trackX = posX - evt.pageX; + var trackY = tipY ? tipY - evt.pageY : posY - evt.pageY; + $this.mousemove(function(evt) { + $cluetip.css({left: evt.pageX + trackX, top: evt.pageY + trackY }); + }); + } + }; + if ($.fn.hoverIntent && opts.hoverIntent) { + $this.mouseover(function() {$this.attr('title',''); }) + .hoverIntent({ + sensitivity: opts.hoverIntent.sensitivity, + interval: opts.hoverIntent.interval, + over: function(event) { + activate(event); + mouseTracks(event); + }, + timeout: opts.hoverIntent.timeout, + out: function(event) {inactivate(event); $this.unbind('mousemove');} + }); + } else { + $this.hover(function(event) { + activate(event); + mouseTracks(event); + }, function(event) { + inactivate(event); + $this.unbind('mousemove'); + }); + } + } + }); + }; + +/* + * options for clueTip + * + * each one can be explicitly overridden by changing its value. + * for example: $.fn.cluetip.defaults.width = 200; + * would change the default width for all clueTips to 200. + * + * each one can also be overridden by passing an options map to the cluetip method. + * for example: $('a.example').cluetip({width: 200}); + * would change the default width to 200 for clueTips invoked by a link with class of "example" + * + */ + + $.fn.cluetip.defaults = { // set up default options + width: 275, // The width of the clueTip + height: 'auto', // The height of the clueTip + cluezIndex: 97, // Sets the z-index style property of the clueTip + positionBy: 'auto', // Sets the type of positioning: 'auto', 'mouse','bottomTop', 'fixed' + topOffset: 15, // Number of px to offset clueTip from top of invoking element + leftOffset: 15, // Number of px to offset clueTip from left of invoking element + local: false, // Whether to use content from the same page for the clueTip's body + localPrefix: null, // string to be prepended to the tip attribute if local is true + hideLocal: true, // If local option is set to true, this determines whether local content + // to be shown in clueTip should be hidden at its original location + attribute: 'rel', // the attribute to be used for fetching the clueTip's body content + titleAttribute: 'title', // the attribute to be used for fetching the clueTip's title + splitTitle: '', // A character used to split the title attribute into the clueTip title and divs + // within the clueTip body. more info below [6] + escapeTitle: false, // whether to html escape the title attribute + showTitle: true, // show title bar of the clueTip, even if title attribute not set + cluetipClass: 'default',// class added to outermost clueTip div in the form of 'cluetip-' + clueTipClass. + hoverClass: '', // class applied to the invoking element onmouseover and removed onmouseout + waitImage: true, // whether to show a "loading" img, which is set in jquery.cluetip.css + cursor: 'help', + arrows: false, // if true, displays arrow on appropriate side of clueTip + dropShadow: true, // set to false if you don't want the drop-shadow effect on the clueTip + dropShadowSteps: 6, // adjusts the size of the drop shadow + sticky: false, // keep visible until manually closed + mouseOutClose: false, // close when clueTip is moused out + activation: 'hover', // set to 'click' to force user to click to show clueTip + // set to 'focus' to show on focus of a form element and hide on blur + clickThrough: false, // if true, and activation is not 'click', then clicking on link will take user to the link's href, + // even if href and tipAttribute are equal + tracking: false, // if true, clueTip will track mouse movement (experimental) + delayedClose: 0, // close clueTip on a timed delay (experimental) + closePosition: 'top', // location of close text for sticky cluetips; can be 'top' or 'bottom' or 'title' + closeText: 'Close', // text (or HTML) to to be clicked to close sticky clueTips + truncate: 0, // number of characters to truncate clueTip's contents. if 0, no truncation occurs + + // effect and speed for opening clueTips + fx: { + open: 'show', // can be 'show' or 'slideDown' or 'fadeIn' + openSpeed: '' + }, + + // settings for when hoverIntent plugin is used + hoverIntent: { + sensitivity: 3, + interval: 50, + timeout: 0 + }, + + // function to run just before clueTip is shown. + onActivate: function(e) {return true;}, + + // function to run just after clueTip is shown. + onShow: function(ct, c){}, + // function to run just after clueTip is hidden. + onHide: function(ct, c){}, + // whether to cache results of ajax request to avoid unnecessary hits to server + ajaxCache: true, + + // process data retrieved via xhr before it's displayed + ajaxProcess: function(data) { + data = data.replace(//g, '').replace(/<(link|title)(.|\s)*?\/(link|title)>/g,''); + return data; + }, + + // can pass in standard $.ajax() parameters, not including error, complete, success, and url + ajaxSettings: { + dataType: 'html' + }, + debug: false + }; + + +/* + * Global defaults for clueTips. Apply to all calls to the clueTip plugin. + * + * @example $.cluetip.setup({ + * insertionType: 'prependTo', + * insertionElement: '#container' + * }); + * + * @property + * @name $.cluetip.setup + * @type Map + * @cat Plugins/tooltip + * @option String insertionType: Default is 'appendTo'. Determines the method to be used for inserting the clueTip into the DOM. Permitted values are 'appendTo', 'prependTo', 'insertBefore', and 'insertAfter' + * @option String insertionElement: Default is 'body'. Determines which element in the DOM the plugin will reference when inserting the clueTip. + * + */ + + var insertionType = 'appendTo', insertionElement = 'body'; + $.cluetip = {}; + $.cluetip.setup = function(options) { + if (options && options.insertionType && (options.insertionType).match(/appendTo|prependTo|insertBefore|insertAfter/)) { + insertionType = options.insertionType; + } + if (options && options.insertionElement) { + insertionElement = options.insertionElement; + } + }; + +})(jQuery); diff --git a/libjs/cluetip/lib/jquery.bgiframe.min.js b/libjs/cluetip/lib/jquery.bgiframe.min.js new file mode 100755 index 0000000..028b27d --- /dev/null +++ b/libjs/cluetip/lib/jquery.bgiframe.min.js @@ -0,0 +1,10 @@ +/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net) + * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) + * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. + * + * $LastChangedDate: 2007-07-21 19:45:56 -0400 (Sat, 21 Jul 2007) $ + * $Rev: 2447 $ + * + * Version 2.1.1 + */ +(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html=''); + this.iefix = $(this.update.id+'_iefix'); + } + if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50); + }, + + fixIEOverlapping: function() { + Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)}); + this.iefix.style.zIndex = 1; + this.update.style.zIndex = 2; + Element.show(this.iefix); + }, + + hide: function() { + this.stopIndicator(); + if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update); + if(this.iefix) Element.hide(this.iefix); + }, + + startIndicator: function() { + if(this.options.indicator) Element.show(this.options.indicator); + }, + + stopIndicator: function() { + if(this.options.indicator) Element.hide(this.options.indicator); + }, + + onKeyPress: function(event) { + if(this.active) + switch(event.keyCode) { + case Event.KEY_TAB: + case Event.KEY_RETURN: + this.selectEntry(); + Event.stop(event); + case Event.KEY_ESC: + this.hide(); + this.active = false; + Event.stop(event); + return; + case Event.KEY_LEFT: + case Event.KEY_RIGHT: + return; + case Event.KEY_UP: + this.markPrevious(); + this.render(); + if(Prototype.Browser.WebKit) Event.stop(event); + return; + case Event.KEY_DOWN: + this.markNext(); + this.render(); + if(Prototype.Browser.WebKit) Event.stop(event); + return; + } + else + if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || + (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return; + + this.changed = true; + this.hasFocus = true; + + if(this.observer) clearTimeout(this.observer); + this.observer = + setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000); + }, + + activate: function() { + this.changed = false; + this.hasFocus = true; + this.getUpdatedChoices(); + }, + + onHover: function(event) { + var element = Event.findElement(event, 'LI'); + if(this.index != element.autocompleteIndex) + { + this.index = element.autocompleteIndex; + this.render(); + } + Event.stop(event); + }, + + onClick: function(event) { + var element = Event.findElement(event, 'LI'); + this.index = element.autocompleteIndex; + this.selectEntry(); + this.hide(); + }, + + onBlur: function(event) { + // needed to make click events working + setTimeout(this.hide.bind(this), 250); + this.hasFocus = false; + this.active = false; + }, + + render: function() { + if(this.entryCount > 0) { + for (var i = 0; i < this.entryCount; i++) + this.index==i ? + Element.addClassName(this.getEntry(i),"selected") : + Element.removeClassName(this.getEntry(i),"selected"); + if(this.hasFocus) { + this.show(); + this.active = true; + } + } else { + this.active = false; + this.hide(); + } + }, + + markPrevious: function() { + if(this.index > 0) this.index-- + else this.index = this.entryCount-1; + this.getEntry(this.index).scrollIntoView(true); + }, + + markNext: function() { + if(this.index < this.entryCount-1) this.index++ + else this.index = 0; + this.getEntry(this.index).scrollIntoView(false); + }, + + getEntry: function(index) { + return this.update.firstChild.childNodes[index]; + }, + + getCurrentEntry: function() { + return this.getEntry(this.index); + }, + + selectEntry: function() { + this.active = false; + this.updateElement(this.getCurrentEntry()); + }, + + updateElement: function(selectedElement) { + if (this.options.updateElement) { + this.options.updateElement(selectedElement); + return; + } + var value = ''; + if (this.options.select) { + var nodes = $(selectedElement).select('.' + this.options.select) || []; + if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select); + } else + value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal'); + + var bounds = this.getTokenBounds(); + if (bounds[0] != -1) { + var newValue = this.element.value.substr(0, bounds[0]); + var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/); + if (whitespace) + newValue += whitespace[0]; + this.element.value = newValue + value + this.element.value.substr(bounds[1]); + } else { + this.element.value = value; + } + this.oldElementValue = this.element.value; + this.element.focus(); + + if (this.options.afterUpdateElement) + this.options.afterUpdateElement(this.element, selectedElement); + }, + + updateChoices: function(choices) { + if(!this.changed && this.hasFocus) { + this.update.innerHTML = choices; + Element.cleanWhitespace(this.update); + Element.cleanWhitespace(this.update.down()); + + if(this.update.firstChild && this.update.down().childNodes) { + this.entryCount = + this.update.down().childNodes.length; + for (var i = 0; i < this.entryCount; i++) { + var entry = this.getEntry(i); + entry.autocompleteIndex = i; + this.addObservers(entry); + } + } else { + this.entryCount = 0; + } + + this.stopIndicator(); + this.index = 0; + + if(this.entryCount==1 && this.options.autoSelect) { + this.selectEntry(); + this.hide(); + } else { + this.render(); + } + } + }, + + addObservers: function(element) { + Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this)); + Event.observe(element, "click", this.onClick.bindAsEventListener(this)); + }, + + onObserverEvent: function() { + this.changed = false; + this.tokenBounds = null; + if(this.getToken().length>=this.options.minChars) { + this.getUpdatedChoices(); + } else { + this.active = false; + this.hide(); + } + this.oldElementValue = this.element.value; + }, + + getToken: function() { + var bounds = this.getTokenBounds(); + return this.element.value.substring(bounds[0], bounds[1]).strip(); + }, + + getTokenBounds: function() { + if (null != this.tokenBounds) return this.tokenBounds; + var value = this.element.value; + if (value.strip().empty()) return [-1, 0]; + var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue); + var offset = (diff == this.oldElementValue.length ? 1 : 0); + var prevTokenPos = -1, nextTokenPos = value.length; + var tp; + for (var index = 0, l = this.options.tokens.length; index < l; ++index) { + tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1); + if (tp > prevTokenPos) prevTokenPos = tp; + tp = value.indexOf(this.options.tokens[index], diff + offset); + if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp; + } + return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]); + } +}); + +Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) { + var boundary = Math.min(newS.length, oldS.length); + for (var index = 0; index < boundary; ++index) + if (newS[index] != oldS[index]) + return index; + return boundary; +}; + +Ajax.Autocompleter = Class.create(Autocompleter.Base, { + initialize: function(element, update, url, options) { + this.baseInitialize(element, update, options); + this.options.asynchronous = true; + this.options.onComplete = this.onComplete.bind(this); + this.options.defaultParams = this.options.parameters || null; + this.url = url; + }, + + getUpdatedChoices: function() { + this.startIndicator(); + + var entry = encodeURIComponent(this.options.paramName) + '=' + + encodeURIComponent(this.getToken()); + + this.options.parameters = this.options.callback ? + this.options.callback(this.element, entry) : entry; + + if(this.options.defaultParams) + this.options.parameters += '&' + this.options.defaultParams; + + new Ajax.Request(this.url, this.options); + }, + + onComplete: function(request) { + this.updateChoices(request.responseText); + } +}); + +// The local array autocompleter. Used when you'd prefer to +// inject an array of autocompletion options into the page, rather +// than sending out Ajax queries, which can be quite slow sometimes. +// +// The constructor takes four parameters. The first two are, as usual, +// the id of the monitored textbox, and id of the autocompletion menu. +// The third is the array you want to autocomplete from, and the fourth +// is the options block. +// +// Extra local autocompletion options: +// - choices - How many autocompletion choices to offer +// +// - partialSearch - If false, the autocompleter will match entered +// text only at the beginning of strings in the +// autocomplete array. Defaults to true, which will +// match text at the beginning of any *word* in the +// strings in the autocomplete array. If you want to +// search anywhere in the string, additionally set +// the option fullSearch to true (default: off). +// +// - fullSsearch - Search anywhere in autocomplete array strings. +// +// - partialChars - How many characters to enter before triggering +// a partial match (unlike minChars, which defines +// how many characters are required to do any match +// at all). Defaults to 2. +// +// - ignoreCase - Whether to ignore case when autocompleting. +// Defaults to true. +// +// It's possible to pass in a custom function as the 'selector' +// option, if you prefer to write your own autocompletion logic. +// In that case, the other options above will not apply unless +// you support them. + +Autocompleter.Local = Class.create(Autocompleter.Base, { + initialize: function(element, update, array, options) { + this.baseInitialize(element, update, options); + this.options.array = array; + }, + + getUpdatedChoices: function() { + this.updateChoices(this.options.selector(this)); + }, + + setOptions: function(options) { + this.options = Object.extend({ + choices: 10, + partialSearch: true, + partialChars: 2, + ignoreCase: true, + fullSearch: false, + selector: function(instance) { + var ret = []; // Beginning matches + var partial = []; // Inside matches + var entry = instance.getToken(); + var count = 0; + + for (var i = 0; i < instance.options.array.length && + ret.length < instance.options.choices ; i++) { + + var elem = instance.options.array[i]; + var foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase()) : + elem.indexOf(entry); + + while (foundPos != -1) { + if (foundPos == 0 && elem.length != entry.length) { + ret.push("
  • " + elem.substr(0, entry.length) + "" + + elem.substr(entry.length) + "
  • "); + break; + } else if (entry.length >= instance.options.partialChars && + instance.options.partialSearch && foundPos != -1) { + if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) { + partial.push("
  • " + elem.substr(0, foundPos) + "" + + elem.substr(foundPos, entry.length) + "" + elem.substr( + foundPos + entry.length) + "
  • "); + break; + } + } + + foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : + elem.indexOf(entry, foundPos + 1); + + } + } + if (partial.length) + ret = ret.concat(partial.slice(0, instance.options.choices - ret.length)) + return "
      " + ret.join('') + "
    "; + } + }, options || { }); + } +}); + +// AJAX in-place editor and collection editor +// Full rewrite by Christophe Porteneuve (April 2007). + +// Use this if you notice weird scrolling problems on some browsers, +// the DOM might be a bit confused when this gets called so do this +// waits 1 ms (with setTimeout) until it does the activation +Field.scrollFreeActivate = function(field) { + setTimeout(function() { + Field.activate(field); + }, 1); +} + +Ajax.InPlaceEditor = Class.create({ + initialize: function(element, url, options) { + this.url = url; + this.element = element = $(element); + this.prepareOptions(); + this._controls = { }; + arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!! + Object.extend(this.options, options || { }); + if (!this.options.formId && this.element.id) { + this.options.formId = this.element.id + '-inplaceeditor'; + if ($(this.options.formId)) + this.options.formId = ''; + } + if (this.options.externalControl) + this.options.externalControl = $(this.options.externalControl); + if (!this.options.externalControl) + this.options.externalControlOnly = false; + this._originalBackground = this.element.getStyle('background-color') || 'transparent'; + this.element.title = this.options.clickToEditText; + this._boundCancelHandler = this.handleFormCancellation.bind(this); + this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this); + this._boundFailureHandler = this.handleAJAXFailure.bind(this); + this._boundSubmitHandler = this.handleFormSubmission.bind(this); + this._boundWrapperHandler = this.wrapUp.bind(this); + this.registerListeners(); + }, + checkForEscapeOrReturn: function(e) { + if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return; + if (Event.KEY_ESC == e.keyCode) + this.handleFormCancellation(e); + else if (Event.KEY_RETURN == e.keyCode) + this.handleFormSubmission(e); + }, + createControl: function(mode, handler, extraClasses) { + var control = this.options[mode + 'Control']; + var text = this.options[mode + 'Text']; + if ('button' == control) { + var btn = document.createElement('input'); + btn.type = 'submit'; + btn.value = text; + btn.className = 'editor_' + mode + '_button'; + if ('cancel' == mode) + btn.onclick = this._boundCancelHandler; + this._form.appendChild(btn); + this._controls[mode] = btn; + } else if ('link' == control) { + var link = document.createElement('a'); + link.href = '#'; + link.appendChild(document.createTextNode(text)); + link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler; + link.className = 'editor_' + mode + '_link'; + if (extraClasses) + link.className += ' ' + extraClasses; + this._form.appendChild(link); + this._controls[mode] = link; + } + }, + createEditField: function() { + var text = (this.options.loadTextURL ? this.options.loadingText : this.getText()); + var fld; + if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) { + fld = document.createElement('input'); + fld.type = 'text'; + var size = this.options.size || this.options.cols || 0; + if (0 < size) fld.size = size; + } else { + fld = document.createElement('textarea'); + fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows); + fld.cols = this.options.cols || 40; + } + fld.name = this.options.paramName; + fld.value = text; // No HTML breaks conversion anymore + fld.className = 'editor_field'; + if (this.options.submitOnBlur) + fld.onblur = this._boundSubmitHandler; + this._controls.editor = fld; + if (this.options.loadTextURL) + this.loadExternalText(); + this._form.appendChild(this._controls.editor); + }, + createForm: function() { + var ipe = this; + function addText(mode, condition) { + var text = ipe.options['text' + mode + 'Controls']; + if (!text || condition === false) return; + ipe._form.appendChild(document.createTextNode(text)); + }; + this._form = $(document.createElement('form')); + this._form.id = this.options.formId; + this._form.addClassName(this.options.formClassName); + this._form.onsubmit = this._boundSubmitHandler; + this.createEditField(); + if ('textarea' == this._controls.editor.tagName.toLowerCase()) + this._form.appendChild(document.createElement('br')); + if (this.options.onFormCustomization) + this.options.onFormCustomization(this, this._form); + addText('Before', this.options.okControl || this.options.cancelControl); + this.createControl('ok', this._boundSubmitHandler); + addText('Between', this.options.okControl && this.options.cancelControl); + this.createControl('cancel', this._boundCancelHandler, 'editor_cancel'); + addText('After', this.options.okControl || this.options.cancelControl); + }, + destroy: function() { + if (this._oldInnerHTML) + this.element.innerHTML = this._oldInnerHTML; + this.leaveEditMode(); + this.unregisterListeners(); + }, + enterEditMode: function(e) { + if (this._saving || this._editing) return; + this._editing = true; + this.triggerCallback('onEnterEditMode'); + if (this.options.externalControl) + this.options.externalControl.hide(); + this.element.hide(); + this.createForm(); + this.element.parentNode.insertBefore(this._form, this.element); + if (!this.options.loadTextURL) + this.postProcessEditField(); + if (e) Event.stop(e); + }, + enterHover: function(e) { + if (this.options.hoverClassName) + this.element.addClassName(this.options.hoverClassName); + if (this._saving) return; + this.triggerCallback('onEnterHover'); + }, + getText: function() { + return this.element.innerHTML; + }, + handleAJAXFailure: function(transport) { + this.triggerCallback('onFailure', transport); + if (this._oldInnerHTML) { + this.element.innerHTML = this._oldInnerHTML; + this._oldInnerHTML = null; + } + }, + handleFormCancellation: function(e) { + this.wrapUp(); + if (e) Event.stop(e); + }, + handleFormSubmission: function(e) { + var form = this._form; + var value = $F(this._controls.editor); + this.prepareSubmission(); + var params = this.options.callback(form, value) || ''; + if (Object.isString(params)) + params = params.toQueryParams(); + params.editorId = this.element.id; + if (this.options.htmlResponse) { + var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions); + Object.extend(options, { + parameters: params, + onComplete: this._boundWrapperHandler, + onFailure: this._boundFailureHandler + }); + new Ajax.Updater({ success: this.element }, this.url, options); + } else { + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: params, + onComplete: this._boundWrapperHandler, + onFailure: this._boundFailureHandler + }); + new Ajax.Request(this.url, options); + } + if (e) Event.stop(e); + }, + leaveEditMode: function() { + this.element.removeClassName(this.options.savingClassName); + this.removeForm(); + this.leaveHover(); + this.element.style.backgroundColor = this._originalBackground; + this.element.show(); + if (this.options.externalControl) + this.options.externalControl.show(); + this._saving = false; + this._editing = false; + this._oldInnerHTML = null; + this.triggerCallback('onLeaveEditMode'); + }, + leaveHover: function(e) { + if (this.options.hoverClassName) + this.element.removeClassName(this.options.hoverClassName); + if (this._saving) return; + this.triggerCallback('onLeaveHover'); + }, + loadExternalText: function() { + this._form.addClassName(this.options.loadingClassName); + this._controls.editor.disabled = true; + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: 'editorId=' + encodeURIComponent(this.element.id), + onComplete: Prototype.emptyFunction, + onSuccess: function(transport) { + this._form.removeClassName(this.options.loadingClassName); + var text = transport.responseText; + if (this.options.stripLoadedTextTags) + text = text.stripTags(); + this._controls.editor.value = text; + this._controls.editor.disabled = false; + this.postProcessEditField(); + }.bind(this), + onFailure: this._boundFailureHandler + }); + new Ajax.Request(this.options.loadTextURL, options); + }, + postProcessEditField: function() { + var fpc = this.options.fieldPostCreation; + if (fpc) + $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate'](); + }, + prepareOptions: function() { + this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions); + Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks); + [this._extraDefaultOptions].flatten().compact().each(function(defs) { + Object.extend(this.options, defs); + }.bind(this)); + }, + prepareSubmission: function() { + this._saving = true; + this.removeForm(); + this.leaveHover(); + this.showSaving(); + }, + registerListeners: function() { + this._listeners = { }; + var listener; + $H(Ajax.InPlaceEditor.Listeners).each(function(pair) { + listener = this[pair.value].bind(this); + this._listeners[pair.key] = listener; + if (!this.options.externalControlOnly) + this.element.observe(pair.key, listener); + if (this.options.externalControl) + this.options.externalControl.observe(pair.key, listener); + }.bind(this)); + }, + removeForm: function() { + if (!this._form) return; + this._form.remove(); + this._form = null; + this._controls = { }; + }, + showSaving: function() { + this._oldInnerHTML = this.element.innerHTML; + this.element.innerHTML = this.options.savingText; + this.element.addClassName(this.options.savingClassName); + this.element.style.backgroundColor = this._originalBackground; + this.element.show(); + }, + triggerCallback: function(cbName, arg) { + if ('function' == typeof this.options[cbName]) { + this.options[cbName](this, arg); + } + }, + unregisterListeners: function() { + $H(this._listeners).each(function(pair) { + if (!this.options.externalControlOnly) + this.element.stopObserving(pair.key, pair.value); + if (this.options.externalControl) + this.options.externalControl.stopObserving(pair.key, pair.value); + }.bind(this)); + }, + wrapUp: function(transport) { + this.leaveEditMode(); + // Can't use triggerCallback due to backward compatibility: requires + // binding + direct element + this._boundComplete(transport, this.element); + } +}); + +Object.extend(Ajax.InPlaceEditor.prototype, { + dispose: Ajax.InPlaceEditor.prototype.destroy +}); + +Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, { + initialize: function($super, element, url, options) { + this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions; + $super(element, url, options); + }, + + createEditField: function() { + var list = document.createElement('select'); + list.name = this.options.paramName; + list.size = 1; + this._controls.editor = list; + this._collection = this.options.collection || []; + if (this.options.loadCollectionURL) + this.loadCollection(); + else + this.checkForExternalText(); + this._form.appendChild(this._controls.editor); + }, + + loadCollection: function() { + this._form.addClassName(this.options.loadingClassName); + this.showLoadingText(this.options.loadingCollectionText); + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: 'editorId=' + encodeURIComponent(this.element.id), + onComplete: Prototype.emptyFunction, + onSuccess: function(transport) { + var js = transport.responseText.strip(); + if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check + throw 'Server returned an invalid collection representation.'; + this._collection = eval(js); + this.checkForExternalText(); + }.bind(this), + onFailure: this.onFailure + }); + new Ajax.Request(this.options.loadCollectionURL, options); + }, + + showLoadingText: function(text) { + this._controls.editor.disabled = true; + var tempOption = this._controls.editor.firstChild; + if (!tempOption) { + tempOption = document.createElement('option'); + tempOption.value = ''; + this._controls.editor.appendChild(tempOption); + tempOption.selected = true; + } + tempOption.update((text || '').stripScripts().stripTags()); + }, + + checkForExternalText: function() { + this._text = this.getText(); + if (this.options.loadTextURL) + this.loadExternalText(); + else + this.buildOptionList(); + }, + + loadExternalText: function() { + this.showLoadingText(this.options.loadingText); + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: 'editorId=' + encodeURIComponent(this.element.id), + onComplete: Prototype.emptyFunction, + onSuccess: function(transport) { + this._text = transport.responseText.strip(); + this.buildOptionList(); + }.bind(this), + onFailure: this.onFailure + }); + new Ajax.Request(this.options.loadTextURL, options); + }, + + buildOptionList: function() { + this._form.removeClassName(this.options.loadingClassName); + this._collection = this._collection.map(function(entry) { + return 2 === entry.length ? entry : [entry, entry].flatten(); + }); + var marker = ('value' in this.options) ? this.options.value : this._text; + var textFound = this._collection.any(function(entry) { + return entry[0] == marker; + }.bind(this)); + this._controls.editor.update(''); + var option; + this._collection.each(function(entry, index) { + option = document.createElement('option'); + option.value = entry[0]; + option.selected = textFound ? entry[0] == marker : 0 == index; + option.appendChild(document.createTextNode(entry[1])); + this._controls.editor.appendChild(option); + }.bind(this)); + this._controls.editor.disabled = false; + Field.scrollFreeActivate(this._controls.editor); + } +}); + +//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! **** +//**** This only exists for a while, in order to let **** +//**** users adapt to the new API. Read up on the new **** +//**** API and convert your code to it ASAP! **** + +Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) { + if (!options) return; + function fallback(name, expr) { + if (name in options || expr === undefined) return; + options[name] = expr; + }; + fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' : + options.cancelLink == options.cancelButton == false ? false : undefined))); + fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' : + options.okLink == options.okButton == false ? false : undefined))); + fallback('highlightColor', options.highlightcolor); + fallback('highlightEndColor', options.highlightendcolor); +}; + +Object.extend(Ajax.InPlaceEditor, { + DefaultOptions: { + ajaxOptions: { }, + autoRows: 3, // Use when multi-line w/ rows == 1 + cancelControl: 'link', // 'link'|'button'|false + cancelText: 'cancel', + clickToEditText: 'Click to edit', + externalControl: null, // id|elt + externalControlOnly: false, + fieldPostCreation: 'activate', // 'activate'|'focus'|false + formClassName: 'inplaceeditor-form', + formId: null, // id|elt + highlightColor: '#ffff99', + highlightEndColor: '#ffffff', + hoverClassName: '', + htmlResponse: true, + loadingClassName: 'inplaceeditor-loading', + loadingText: 'Loading...', + okControl: 'button', // 'link'|'button'|false + okText: 'ok', + paramName: 'value', + rows: 1, // If 1 and multi-line, uses autoRows + savingClassName: 'inplaceeditor-saving', + savingText: 'Saving...', + size: 0, + stripLoadedTextTags: false, + submitOnBlur: false, + textAfterControls: '', + textBeforeControls: '', + textBetweenControls: '' + }, + DefaultCallbacks: { + callback: function(form) { + return Form.serialize(form); + }, + onComplete: function(transport, element) { + // For backward compatibility, this one is bound to the IPE, and passes + // the element directly. It was too often customized, so we don't break it. + new Effect.Highlight(element, { + startcolor: this.options.highlightColor, keepBackgroundImage: true }); + }, + onEnterEditMode: null, + onEnterHover: function(ipe) { + ipe.element.style.backgroundColor = ipe.options.highlightColor; + if (ipe._effect) + ipe._effect.cancel(); + }, + onFailure: function(transport, ipe) { + alert('Error communication with the server: ' + transport.responseText.stripTags()); + }, + onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls. + onLeaveEditMode: null, + onLeaveHover: function(ipe) { + ipe._effect = new Effect.Highlight(ipe.element, { + startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor, + restorecolor: ipe._originalBackground, keepBackgroundImage: true + }); + } + }, + Listeners: { + click: 'enterEditMode', + keydown: 'checkForEscapeOrReturn', + mouseover: 'enterHover', + mouseout: 'leaveHover' + } +}); + +Ajax.InPlaceCollectionEditor.DefaultOptions = { + loadingCollectionText: 'Loading options...' +}; + +// Delayed observer, like Form.Element.Observer, +// but waits for delay after last key input +// Ideal for live-search fields + +Form.Element.DelayedObserver = Class.create({ + initialize: function(element, delay, callback) { + this.delay = delay || 0.5; + this.element = $(element); + this.callback = callback; + this.timer = null; + this.lastValue = $F(this.element); + Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this)); + }, + delayedListener: function(event) { + if(this.lastValue == $F(this.element)) return; + if(this.timer) clearTimeout(this.timer); + this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000); + this.lastValue = $F(this.element); + }, + onTimerEvent: function() { + this.timer = null; + this.callback(this.element, $F(this.element)); + } +}); diff --git a/libjs/dragdrop.js b/libjs/dragdrop.js new file mode 100755 index 0000000..14ebc6f --- /dev/null +++ b/libjs/dragdrop.js @@ -0,0 +1,974 @@ +// script.aculo.us dragdrop.js v1.8.0, Tue Nov 06 15:01:40 +0300 2007 + +// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz) +// +// script.aculo.us is freely distributable under the terms of an MIT-style license. +// For details, see the script.aculo.us web site: http://script.aculo.us/ + +if(Object.isUndefined(Effect)) + throw("dragdrop.js requires including script.aculo.us' effects.js library"); + +var Droppables = { + drops: [], + + remove: function(element) { + this.drops = this.drops.reject(function(d) { return d.element==$(element) }); + }, + + add: function(element) { + element = $(element); + var options = Object.extend({ + greedy: true, + hoverclass: null, + tree: false + }, arguments[1] || { }); + + // cache containers + if(options.containment) { + options._containers = []; + var containment = options.containment; + if(Object.isArray(containment)) { + containment.each( function(c) { options._containers.push($(c)) }); + } else { + options._containers.push($(containment)); + } + } + + if(options.accept) options.accept = [options.accept].flatten(); + + Element.makePositioned(element); // fix IE + options.element = element; + + this.drops.push(options); + }, + + findDeepestChild: function(drops) { + deepest = drops[0]; + + for (i = 1; i < drops.length; ++i) + if (Element.isParent(drops[i].element, deepest.element)) + deepest = drops[i]; + + return deepest; + }, + + isContained: function(element, drop) { + var containmentNode; + if(drop.tree) { + containmentNode = element.treeNode; + } else { + containmentNode = element.parentNode; + } + return drop._containers.detect(function(c) { return containmentNode == c }); + }, + + isAffected: function(point, element, drop) { + return ( + (drop.element!=element) && + ((!drop._containers) || + this.isContained(element, drop)) && + ((!drop.accept) || + (Element.classNames(element).detect( + function(v) { return drop.accept.include(v) } ) )) && + Position.within(drop.element, point[0], point[1]) ); + }, + + deactivate: function(drop) { + if(drop.hoverclass) + Element.removeClassName(drop.element, drop.hoverclass); + this.last_active = null; + }, + + activate: function(drop) { + if(drop.hoverclass) + Element.addClassName(drop.element, drop.hoverclass); + this.last_active = drop; + }, + + show: function(point, element) { + if(!this.drops.length) return; + var drop, affected = []; + + this.drops.each( function(drop) { + if(Droppables.isAffected(point, element, drop)) + affected.push(drop); + }); + + if(affected.length>0) + drop = Droppables.findDeepestChild(affected); + + if(this.last_active && this.last_active != drop) this.deactivate(this.last_active); + if (drop) { + Position.within(drop.element, point[0], point[1]); + if(drop.onHover) + drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element)); + + if (drop != this.last_active) Droppables.activate(drop); + } + }, + + fire: function(event, element) { + if(!this.last_active) return; + Position.prepare(); + + if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active)) + if (this.last_active.onDrop) { + this.last_active.onDrop(element, this.last_active.element, event); + return true; + } + }, + + reset: function() { + if(this.last_active) + this.deactivate(this.last_active); + } +} + +var Draggables = { + drags: [], + observers: [], + + register: function(draggable) { + if(this.drags.length == 0) { + this.eventMouseUp = this.endDrag.bindAsEventListener(this); + this.eventMouseMove = this.updateDrag.bindAsEventListener(this); + this.eventKeypress = this.keyPress.bindAsEventListener(this); + + Event.observe(document, "mouseup", this.eventMouseUp); + Event.observe(document, "mousemove", this.eventMouseMove); + Event.observe(document, "keypress", this.eventKeypress); + } + this.drags.push(draggable); + }, + + unregister: function(draggable) { + this.drags = this.drags.reject(function(d) { return d==draggable }); + if(this.drags.length == 0) { + Event.stopObserving(document, "mouseup", this.eventMouseUp); + Event.stopObserving(document, "mousemove", this.eventMouseMove); + Event.stopObserving(document, "keypress", this.eventKeypress); + } + }, + + activate: function(draggable) { + if(draggable.options.delay) { + this._timeout = setTimeout(function() { + Draggables._timeout = null; + window.focus(); + Draggables.activeDraggable = draggable; + }.bind(this), draggable.options.delay); + } else { + window.focus(); // allows keypress events if window isn't currently focused, fails for Safari + this.activeDraggable = draggable; + } + }, + + deactivate: function() { + this.activeDraggable = null; + }, + + updateDrag: function(event) { + if(!this.activeDraggable) return; + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + // Mozilla-based browsers fire successive mousemove events with + // the same coordinates, prevent needless redrawing (moz bug?) + if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return; + this._lastPointer = pointer; + + this.activeDraggable.updateDrag(event, pointer); + }, + + endDrag: function(event) { + if(this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; + } + if(!this.activeDraggable) return; + this._lastPointer = null; + this.activeDraggable.endDrag(event); + this.activeDraggable = null; + }, + + keyPress: function(event) { + if(this.activeDraggable) + this.activeDraggable.keyPress(event); + }, + + addObserver: function(observer) { + this.observers.push(observer); + this._cacheObserverCallbacks(); + }, + + removeObserver: function(element) { // element instead of observer fixes mem leaks + this.observers = this.observers.reject( function(o) { return o.element==element }); + this._cacheObserverCallbacks(); + }, + + notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag' + if(this[eventName+'Count'] > 0) + this.observers.each( function(o) { + if(o[eventName]) o[eventName](eventName, draggable, event); + }); + if(draggable.options[eventName]) draggable.options[eventName](draggable, event); + }, + + _cacheObserverCallbacks: function() { + ['onStart','onEnd','onDrag'].each( function(eventName) { + Draggables[eventName+'Count'] = Draggables.observers.select( + function(o) { return o[eventName]; } + ).length; + }); + } +} + +/*--------------------------------------------------------------------------*/ + +var Draggable = Class.create({ + initialize: function(element) { + var defaults = { + handle: false, + reverteffect: function(element, top_offset, left_offset) { + var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02; + new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur, + queue: {scope:'_draggable', position:'end'} + }); + }, + endeffect: function(element) { + var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0; + new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, + queue: {scope:'_draggable', position:'end'}, + afterFinish: function(){ + Draggable._dragging[element] = false + } + }); + }, + zindex: 1000, + revert: false, + quiet: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] } + delay: 0 + }; + + if(!arguments[1] || Object.isUndefined(arguments[1].endeffect)) + Object.extend(defaults, { + starteffect: function(element) { + element._opacity = Element.getOpacity(element); + Draggable._dragging[element] = true; + new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); + } + }); + + var options = Object.extend(defaults, arguments[1] || { }); + + this.element = $(element); + + if(options.handle && Object.isString(options.handle)) + this.handle = this.element.down('.'+options.handle, 0); + + if(!this.handle) this.handle = $(options.handle); + if(!this.handle) this.handle = this.element; + + if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) { + options.scroll = $(options.scroll); + this._isScrollChild = Element.childOf(this.element, options.scroll); + } + + Element.makePositioned(this.element); // fix IE + + this.options = options; + this.dragging = false; + + this.eventMouseDown = this.initDrag.bindAsEventListener(this); + Event.observe(this.handle, "mousedown", this.eventMouseDown); + + Draggables.register(this); + }, + + destroy: function() { + Event.stopObserving(this.handle, "mousedown", this.eventMouseDown); + Draggables.unregister(this); + }, + + currentDelta: function() { + return([ + parseInt(Element.getStyle(this.element,'left') || '0'), + parseInt(Element.getStyle(this.element,'top') || '0')]); + }, + + initDrag: function(event) { + if(!Object.isUndefined(Draggable._dragging[this.element]) && + Draggable._dragging[this.element]) return; + if(Event.isLeftClick(event)) { + // abort on form elements, fixes a Firefox issue + var src = Event.element(event); + if((tag_name = src.tagName.toUpperCase()) && ( + tag_name=='INPUT' || + tag_name=='SELECT' || + tag_name=='OPTION' || + tag_name=='BUTTON' || + tag_name=='TEXTAREA')) return; + + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + var pos = Position.cumulativeOffset(this.element); + this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) }); + + Draggables.activate(this); + Event.stop(event); + } + }, + + startDrag: function(event) { + this.dragging = true; + if(!this.delta) + this.delta = this.currentDelta(); + + if(this.options.zindex) { + this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0); + this.element.style.zIndex = this.options.zindex; + } + + if(this.options.ghosting) { + this._clone = this.element.cloneNode(true); + this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute'); + if (!this.element._originallyAbsolute) + Position.absolutize(this.element); + this.element.parentNode.insertBefore(this._clone, this.element); + } + + if(this.options.scroll) { + if (this.options.scroll == window) { + var where = this._getWindowScroll(this.options.scroll); + this.originalScrollLeft = where.left; + this.originalScrollTop = where.top; + } else { + this.originalScrollLeft = this.options.scroll.scrollLeft; + this.originalScrollTop = this.options.scroll.scrollTop; + } + } + + Draggables.notify('onStart', this, event); + + if(this.options.starteffect) this.options.starteffect(this.element); + }, + + updateDrag: function(event, pointer) { + if(!this.dragging) this.startDrag(event); + + if(!this.options.quiet){ + Position.prepare(); + Droppables.show(pointer, this.element); + } + + Draggables.notify('onDrag', this, event); + + this.draw(pointer); + if(this.options.change) this.options.change(this); + + if(this.options.scroll) { + this.stopScrolling(); + + var p; + if (this.options.scroll == window) { + with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; } + } else { + p = Position.page(this.options.scroll); + p[0] += this.options.scroll.scrollLeft + Position.deltaX; + p[1] += this.options.scroll.scrollTop + Position.deltaY; + p.push(p[0]+this.options.scroll.offsetWidth); + p.push(p[1]+this.options.scroll.offsetHeight); + } + var speed = [0,0]; + if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity); + if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity); + if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity); + if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity); + this.startScrolling(speed); + } + + // fix AppleWebKit rendering + if(Prototype.Browser.WebKit) window.scrollBy(0,0); + + Event.stop(event); + }, + + finishDrag: function(event, success) { + this.dragging = false; + + if(this.options.quiet){ + Position.prepare(); + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + Droppables.show(pointer, this.element); + } + + if(this.options.ghosting) { + if (!this.element._originallyAbsolute) + Position.relativize(this.element); + delete this.element._originallyAbsolute; + Element.remove(this._clone); + this._clone = null; + } + + var dropped = false; + if(success) { + dropped = Droppables.fire(event, this.element); + if (!dropped) dropped = false; + } + if(dropped && this.options.onDropped) this.options.onDropped(this.element); + Draggables.notify('onEnd', this, event); + + var revert = this.options.revert; + if(revert && Object.isFunction(revert)) revert = revert(this.element); + + var d = this.currentDelta(); + if(revert && this.options.reverteffect) { + if (dropped == 0 || revert != 'failure') + this.options.reverteffect(this.element, + d[1]-this.delta[1], d[0]-this.delta[0]); + } else { + this.delta = d; + } + + if(this.options.zindex) + this.element.style.zIndex = this.originalZ; + + if(this.options.endeffect) + this.options.endeffect(this.element); + + Draggables.deactivate(this); + Droppables.reset(); + }, + + keyPress: function(event) { + if(event.keyCode!=Event.KEY_ESC) return; + this.finishDrag(event, false); + Event.stop(event); + }, + + endDrag: function(event) { + if(!this.dragging) return; + this.stopScrolling(); + this.finishDrag(event, true); + Event.stop(event); + }, + + draw: function(point) { + var pos = Position.cumulativeOffset(this.element); + if(this.options.ghosting) { + var r = Position.realOffset(this.element); + pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY; + } + + var d = this.currentDelta(); + pos[0] -= d[0]; pos[1] -= d[1]; + + if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) { + pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft; + pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop; + } + + var p = [0,1].map(function(i){ + return (point[i]-pos[i]-this.offset[i]) + }.bind(this)); + + if(this.options.snap) { + if(Object.isFunction(this.options.snap)) { + p = this.options.snap(p[0],p[1],this); + } else { + if(Object.isArray(this.options.snap)) { + p = p.map( function(v, i) { + return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this)) + } else { + p = p.map( function(v) { + return (v/this.options.snap).round()*this.options.snap }.bind(this)) + } + }} + + var style = this.element.style; + if((!this.options.constraint) || (this.options.constraint=='horizontal')) + style.left = p[0] + "px"; + if((!this.options.constraint) || (this.options.constraint=='vertical')) + style.top = p[1] + "px"; + + if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering + }, + + stopScrolling: function() { + if(this.scrollInterval) { + clearInterval(this.scrollInterval); + this.scrollInterval = null; + Draggables._lastScrollPointer = null; + } + }, + + startScrolling: function(speed) { + if(!(speed[0] || speed[1])) return; + this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed]; + this.lastScrolled = new Date(); + this.scrollInterval = setInterval(this.scroll.bind(this), 10); + }, + + scroll: function() { + var current = new Date(); + var delta = current - this.lastScrolled; + this.lastScrolled = current; + if(this.options.scroll == window) { + with (this._getWindowScroll(this.options.scroll)) { + if (this.scrollSpeed[0] || this.scrollSpeed[1]) { + var d = delta / 1000; + this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] ); + } + } + } else { + this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000; + this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000; + } + + Position.prepare(); + Droppables.show(Draggables._lastPointer, this.element); + Draggables.notify('onDrag', this); + if (this._isScrollChild) { + Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer); + Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000; + Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000; + if (Draggables._lastScrollPointer[0] < 0) + Draggables._lastScrollPointer[0] = 0; + if (Draggables._lastScrollPointer[1] < 0) + Draggables._lastScrollPointer[1] = 0; + this.draw(Draggables._lastScrollPointer); + } + + if(this.options.change) this.options.change(this); + }, + + _getWindowScroll: function(w) { + var T, L, W, H; + with (w.document) { + if (w.document.documentElement && documentElement.scrollTop) { + T = documentElement.scrollTop; + L = documentElement.scrollLeft; + } else if (w.document.body) { + T = body.scrollTop; + L = body.scrollLeft; + } + if (w.innerWidth) { + W = w.innerWidth; + H = w.innerHeight; + } else if (w.document.documentElement && documentElement.clientWidth) { + W = documentElement.clientWidth; + H = documentElement.clientHeight; + } else { + W = body.offsetWidth; + H = body.offsetHeight + } + } + return { top: T, left: L, width: W, height: H }; + } +}); + +Draggable._dragging = { }; + +/*--------------------------------------------------------------------------*/ + +var SortableObserver = Class.create({ + initialize: function(element, observer) { + this.element = $(element); + this.observer = observer; + this.lastValue = Sortable.serialize(this.element); + }, + + onStart: function() { + this.lastValue = Sortable.serialize(this.element); + }, + + onEnd: function() { + Sortable.unmark(); + if(this.lastValue != Sortable.serialize(this.element)) + this.observer(this.element) + } +}); + +var Sortable = { + SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/, + + sortables: { }, + + _findRootElement: function(element) { + while (element.tagName.toUpperCase() != "BODY") { + if(element.id && Sortable.sortables[element.id]) return element; + element = element.parentNode; + } + }, + + options: function(element) { + element = Sortable._findRootElement($(element)); + if(!element) return; + return Sortable.sortables[element.id]; + }, + + destroy: function(element){ + var s = Sortable.options(element); + + if(s) { + Draggables.removeObserver(s.element); + s.droppables.each(function(d){ Droppables.remove(d) }); + s.draggables.invoke('destroy'); + + delete Sortable.sortables[s.element.id]; + } + }, + + create: function(element) { + element = $(element); + var options = Object.extend({ + element: element, + tag: 'li', // assumes li children, override with tag: 'tagname' + dropOnEmpty: false, + tree: false, + treeTag: 'ul', + overlap: 'vertical', // one of 'vertical', 'horizontal' + constraint: 'vertical', // one of 'vertical', 'horizontal', false + containment: element, // also takes array of elements (or id's); or false + handle: false, // or a CSS class + only: false, + delay: 0, + hoverclass: null, + ghosting: false, + quiet: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + format: this.SERIALIZE_RULE, + + // these take arrays of elements or ids and can be + // used for better initialization performance + elements: false, + handles: false, + + onChange: Prototype.emptyFunction, + onUpdate: Prototype.emptyFunction + }, arguments[1] || { }); + + // clear any old sortable with same element + this.destroy(element); + + // build options for the draggables + var options_for_draggable = { + revert: true, + quiet: options.quiet, + scroll: options.scroll, + scrollSpeed: options.scrollSpeed, + scrollSensitivity: options.scrollSensitivity, + delay: options.delay, + ghosting: options.ghosting, + constraint: options.constraint, + handle: options.handle }; + + if(options.starteffect) + options_for_draggable.starteffect = options.starteffect; + + if(options.reverteffect) + options_for_draggable.reverteffect = options.reverteffect; + else + if(options.ghosting) options_for_draggable.reverteffect = function(element) { + element.style.top = 0; + element.style.left = 0; + }; + + if(options.endeffect) + options_for_draggable.endeffect = options.endeffect; + + if(options.zindex) + options_for_draggable.zindex = options.zindex; + + // build options for the droppables + var options_for_droppable = { + overlap: options.overlap, + containment: options.containment, + tree: options.tree, + hoverclass: options.hoverclass, + onHover: Sortable.onHover + } + + var options_for_tree = { + onHover: Sortable.onEmptyHover, + overlap: options.overlap, + containment: options.containment, + hoverclass: options.hoverclass + } + + // fix for gecko engine + Element.cleanWhitespace(element); + + options.draggables = []; + options.droppables = []; + + // drop on empty handling + if(options.dropOnEmpty || options.tree) { + Droppables.add(element, options_for_tree); + options.droppables.push(element); + } + + (options.elements || this.findElements(element, options) || []).each( function(e,i) { + var handle = options.handles ? $(options.handles[i]) : + (options.handle ? $(e).select('.' + options.handle)[0] : e); + options.draggables.push( + new Draggable(e, Object.extend(options_for_draggable, { handle: handle }))); + Droppables.add(e, options_for_droppable); + if(options.tree) e.treeNode = element; + options.droppables.push(e); + }); + + if(options.tree) { + (Sortable.findTreeElements(element, options) || []).each( function(e) { + Droppables.add(e, options_for_tree); + e.treeNode = element; + options.droppables.push(e); + }); + } + + // keep reference + this.sortables[element.id] = options; + + // for onupdate + Draggables.addObserver(new SortableObserver(element, options.onUpdate)); + + }, + + // return all suitable-for-sortable elements in a guaranteed order + findElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.tag); + }, + + findTreeElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.treeTag); + }, + + onHover: function(element, dropon, overlap) { + if(Element.isParent(dropon, element)) return; + + if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) { + return; + } else if(overlap>0.5) { + Sortable.mark(dropon, 'before'); + if(dropon.previousSibling != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, dropon); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } else { + Sortable.mark(dropon, 'after'); + var nextElement = dropon.nextSibling || null; + if(nextElement != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, nextElement); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } + }, + + onEmptyHover: function(element, dropon, overlap) { + var oldParentNode = element.parentNode; + var droponOptions = Sortable.options(dropon); + + if(!Element.isParent(dropon, element)) { + var index; + + var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only}); + var child = null; + + if(children) { + var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap); + + for (index = 0; index < children.length; index += 1) { + if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) { + offset -= Element.offsetSize (children[index], droponOptions.overlap); + } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) { + child = index + 1 < children.length ? children[index + 1] : null; + break; + } else { + child = children[index]; + break; + } + } + } + + dropon.insertBefore(element, child); + + Sortable.options(oldParentNode).onChange(element); + droponOptions.onChange(element); + } + }, + + unmark: function() { + if(Sortable._marker) Sortable._marker.hide(); + }, + + mark: function(dropon, position) { + // mark on ghosting only + var sortable = Sortable.options(dropon.parentNode); + if(sortable && !sortable.ghosting) return; + + if(!Sortable._marker) { + Sortable._marker = + ($('dropmarker') || Element.extend(document.createElement('DIV'))). + hide().addClassName('dropmarker').setStyle({position:'absolute'}); + document.getElementsByTagName("body").item(0).appendChild(Sortable._marker); + } + var offsets = Position.cumulativeOffset(dropon); + Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'}); + + if(position=='after') + if(sortable.overlap == 'horizontal') + Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'}); + else + Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'}); + + Sortable._marker.show(); + }, + + _tree: function(element, options, parent) { + var children = Sortable.findElements(element, options) || []; + + for (var i = 0; i < children.length; ++i) { + var match = children[i].id.match(options.format); + + if (!match) continue; + + var child = { + id: encodeURIComponent(match ? match[1] : null), + element: element, + parent: parent, + children: [], + position: parent.children.length, + container: $(children[i]).down(options.treeTag) + } + + /* Get the element containing the children and recurse over it */ + if (child.container) + this._tree(child.container, options, child) + + parent.children.push (child); + } + + return parent; + }, + + tree: function(element) { + element = $(element); + var sortableOptions = this.options(element); + var options = Object.extend({ + tag: sortableOptions.tag, + treeTag: sortableOptions.treeTag, + only: sortableOptions.only, + name: element.id, + format: sortableOptions.format + }, arguments[1] || { }); + + var root = { + id: null, + parent: null, + children: [], + container: element, + position: 0 + } + + return Sortable._tree(element, options, root); + }, + + /* Construct a [i] index for a particular node */ + _constructIndex: function(node) { + var index = ''; + do { + if (node.id) index = '[' + node.position + ']' + index; + } while ((node = node.parent) != null); + return index; + }, + + sequence: function(element) { + element = $(element); + var options = Object.extend(this.options(element), arguments[1] || { }); + + return $(this.findElements(element, options) || []).map( function(item) { + return item.id.match(options.format) ? item.id.match(options.format)[1] : ''; + }); + }, + + setSequence: function(element, new_sequence) { + element = $(element); + var options = Object.extend(this.options(element), arguments[2] || { }); + + var nodeMap = { }; + this.findElements(element, options).each( function(n) { + if (n.id.match(options.format)) + nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode]; + n.parentNode.removeChild(n); + }); + + new_sequence.each(function(ident) { + var n = nodeMap[ident]; + if (n) { + n[1].appendChild(n[0]); + delete nodeMap[ident]; + } + }); + }, + + serialize: function(element) { + element = $(element); + var options = Object.extend(Sortable.options(element), arguments[1] || { }); + var name = encodeURIComponent( + (arguments[1] && arguments[1].name) ? arguments[1].name : element.id); + + if (options.tree) { + return Sortable.tree(element, arguments[1]).children.map( function (item) { + return [name + Sortable._constructIndex(item) + "[id]=" + + encodeURIComponent(item.id)].concat(item.children.map(arguments.callee)); + }).flatten().join('&'); + } else { + return Sortable.sequence(element, arguments[1]).map( function(item) { + return name + "[]=" + encodeURIComponent(item); + }).join('&'); + } + } +} + +// Returns true if child is contained within element +Element.isParent = function(child, element) { + if (!child.parentNode || child == element) return false; + if (child.parentNode == element) return true; + return Element.isParent(child.parentNode, element); +} + +Element.findChildren = function(element, only, recursive, tagName) { + if(!element.hasChildNodes()) return null; + tagName = tagName.toUpperCase(); + if(only) only = [only].flatten(); + var elements = []; + $A(element.childNodes).each( function(e) { + if(e.tagName && e.tagName.toUpperCase()==tagName && + (!only || (Element.classNames(e).detect(function(v) { return only.include(v) })))) + elements.push(e); + if(recursive) { + var grandchildren = Element.findChildren(e, only, recursive, tagName); + if(grandchildren) elements.push(grandchildren); + } + }); + + return (elements.length>0 ? elements.flatten() : []); +} + +Element.offsetSize = function (element, type) { + return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')]; +} diff --git a/libjs/effects.js b/libjs/effects.js new file mode 100644 index 0000000..27c2901 --- /dev/null +++ b/libjs/effects.js @@ -0,0 +1,1122 @@ +// script.aculo.us effects.js v1.8.0, Tue Nov 06 15:01:40 +0300 2007 + +// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// Contributors: +// Justin Palmer (http://encytemedia.com/) +// Mark Pilgrim (http://diveintomark.org/) +// Martin Bialasinki +// +// script.aculo.us is freely distributable under the terms of an MIT-style license. +// For details, see the script.aculo.us web site: http://script.aculo.us/ + +// converts rgb() and #xxx to #xxxxxx format, +// returns self (or first argument) if not convertable +String.prototype.parseColor = function() { + var color = '#'; + if (this.slice(0,4) == 'rgb(') { + var cols = this.slice(4,this.length-1).split(','); + var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); + } else { + if (this.slice(0,1) == '#') { + if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); + if (this.length==7) color = this.toLowerCase(); + } + } + return (color.length==7 ? color : (arguments[0] || this)); +}; + +/*--------------------------------------------------------------------------*/ + +Element.collectTextNodes = function(element) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + (node.hasChildNodes() ? Element.collectTextNodes(node) : '')); + }).flatten().join(''); +}; + +Element.collectTextNodesIgnoreClass = function(element, className) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? + Element.collectTextNodesIgnoreClass(node, className) : '')); + }).flatten().join(''); +}; + +Element.setContentZoom = function(element, percent) { + element = $(element); + element.setStyle({fontSize: (percent/100) + 'em'}); + if (Prototype.Browser.WebKit) window.scrollBy(0,0); + return element; +}; + +Element.getInlineOpacity = function(element){ + return $(element).style.opacity || ''; +}; + +Element.forceRerendering = function(element) { + try { + element = $(element); + var n = document.createTextNode(' '); + element.appendChild(n); + element.removeChild(n); + } catch(e) { } +}; + +/*--------------------------------------------------------------------------*/ + +var Effect = { + _elementDoesNotExistError: { + name: 'ElementDoesNotExistError', + message: 'The specified DOM element does not exist, but is required for this effect to operate' + }, + Transitions: { + linear: Prototype.K, + sinoidal: function(pos) { + return (-Math.cos(pos*Math.PI)/2) + 0.5; + }, + reverse: function(pos) { + return 1-pos; + }, + flicker: function(pos) { + var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4; + return pos > 1 ? 1 : pos; + }, + wobble: function(pos) { + return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5; + }, + pulse: function(pos, pulses) { + pulses = pulses || 5; + return ( + ((pos % (1/pulses)) * pulses).round() == 0 ? + ((pos * pulses * 2) - (pos * pulses * 2).floor()) : + 1 - ((pos * pulses * 2) - (pos * pulses * 2).floor()) + ); + }, + spring: function(pos) { + return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); + }, + none: function(pos) { + return 0; + }, + full: function(pos) { + return 1; + } + }, + DefaultOptions: { + duration: 1.0, // seconds + fps: 100, // 100= assume 66fps max. + sync: false, // true for combining + from: 0.0, + to: 1.0, + delay: 0.0, + queue: 'parallel' + }, + tagifyText: function(element) { + var tagifyStyle = 'position:relative'; + if (Prototype.Browser.IE) tagifyStyle += ';zoom:1'; + + element = $(element); + $A(element.childNodes).each( function(child) { + if (child.nodeType==3) { + child.nodeValue.toArray().each( function(character) { + element.insertBefore( + new Element('span', {style: tagifyStyle}).update( + character == ' ' ? String.fromCharCode(160) : character), + child); + }); + Element.remove(child); + } + }); + }, + multiple: function(element, effect) { + var elements; + if (((typeof element == 'object') || + Object.isFunction(element)) && + (element.length)) + elements = element; + else + elements = $(element).childNodes; + + var options = Object.extend({ + speed: 0.1, + delay: 0.0 + }, arguments[2] || { }); + var masterDelay = options.delay; + + $A(elements).each( function(element, index) { + new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay })); + }); + }, + PAIRS: { + 'slide': ['SlideDown','SlideUp'], + 'blind': ['BlindDown','BlindUp'], + 'appear': ['Appear','Fade'] + }, + toggle: function(element, effect) { + element = $(element); + effect = (effect || 'appear').toLowerCase(); + var options = Object.extend({ + queue: { position:'end', scope:(element.id || 'global'), limit: 1 } + }, arguments[2] || { }); + Effect[element.visible() ? + Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options); + } +}; + +Effect.DefaultOptions.transition = Effect.Transitions.sinoidal; + +/* ------------- core effects ------------- */ + +Effect.ScopedQueue = Class.create(Enumerable, { + initialize: function() { + this.effects = []; + this.interval = null; + }, + _each: function(iterator) { + this.effects._each(iterator); + }, + add: function(effect) { + var timestamp = new Date().getTime(); + + var position = Object.isString(effect.options.queue) ? + effect.options.queue : effect.options.queue.position; + + switch(position) { + case 'front': + // move unstarted effects after this effect + this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) { + e.startOn += effect.finishOn; + e.finishOn += effect.finishOn; + }); + break; + case 'with-last': + timestamp = this.effects.pluck('startOn').max() || timestamp; + break; + case 'end': + // start effect after last queued effect has finished + timestamp = this.effects.pluck('finishOn').max() || timestamp; + break; + } + + effect.startOn += timestamp; + effect.finishOn += timestamp; + + if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) + this.effects.push(effect); + + if (!this.interval) + this.interval = setInterval(this.loop.bind(this), 15); + }, + remove: function(effect) { + this.effects = this.effects.reject(function(e) { return e==effect }); + if (this.effects.length == 0) { + clearInterval(this.interval); + this.interval = null; + } + }, + loop: function() { + var timePos = new Date().getTime(); + for(var i=0, len=this.effects.length;i= this.startOn) { + if (timePos >= this.finishOn) { + this.render(1.0); + this.cancel(); + this.event('beforeFinish'); + if (this.finish) this.finish(); + this.event('afterFinish'); + return; + } + var pos = (timePos - this.startOn) / this.totalTime, + frame = (pos * this.totalFrames).round(); + if (frame > this.currentFrame) { + this.render(pos); + this.currentFrame = frame; + } + } + }, + cancel: function() { + if (!this.options.sync) + Effect.Queues.get(Object.isString(this.options.queue) ? + 'global' : this.options.queue.scope).remove(this); + this.state = 'finished'; + }, + event: function(eventName) { + if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this); + if (this.options[eventName]) this.options[eventName](this); + }, + inspect: function() { + var data = $H(); + for(property in this) + if (!Object.isFunction(this[property])) data.set(property, this[property]); + return '#'; + } +}); + +Effect.Parallel = Class.create(Effect.Base, { + initialize: function(effects) { + this.effects = effects || []; + this.start(arguments[1]); + }, + update: function(position) { + this.effects.invoke('render', position); + }, + finish: function(position) { + this.effects.each( function(effect) { + effect.render(1.0); + effect.cancel(); + effect.event('beforeFinish'); + if (effect.finish) effect.finish(position); + effect.event('afterFinish'); + }); + } +}); + +Effect.Tween = Class.create(Effect.Base, { + initialize: function(object, from, to) { + object = Object.isString(object) ? $(object) : object; + var args = $A(arguments), method = args.last(), + options = args.length == 5 ? args[3] : null; + this.method = Object.isFunction(method) ? method.bind(object) : + Object.isFunction(object[method]) ? object[method].bind(object) : + function(value) { object[method] = value }; + this.start(Object.extend({ from: from, to: to }, options || { })); + }, + update: function(position) { + this.method(position); + } +}); + +Effect.Event = Class.create(Effect.Base, { + initialize: function() { + this.start(Object.extend({ duration: 0 }, arguments[0] || { })); + }, + update: Prototype.emptyFunction +}); + +Effect.Opacity = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + // make this work on IE on elements without 'layout' + if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) + this.element.setStyle({zoom: 1}); + var options = Object.extend({ + from: this.element.getOpacity() || 0.0, + to: 1.0 + }, arguments[1] || { }); + this.start(options); + }, + update: function(position) { + this.element.setOpacity(position); + } +}); + +Effect.Move = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + x: 0, + y: 0, + mode: 'relative' + }, arguments[1] || { }); + this.start(options); + }, + setup: function() { + this.element.makePositioned(); + this.originalLeft = parseFloat(this.element.getStyle('left') || '0'); + this.originalTop = parseFloat(this.element.getStyle('top') || '0'); + if (this.options.mode == 'absolute') { + this.options.x = this.options.x - this.originalLeft; + this.options.y = this.options.y - this.originalTop; + } + }, + update: function(position) { + this.element.setStyle({ + left: (this.options.x * position + this.originalLeft).round() + 'px', + top: (this.options.y * position + this.originalTop).round() + 'px' + }); + } +}); + +// for backwards compatibility +Effect.MoveBy = function(element, toTop, toLeft) { + return new Effect.Move(element, + Object.extend({ x: toLeft, y: toTop }, arguments[3] || { })); +}; + +Effect.Scale = Class.create(Effect.Base, { + initialize: function(element, percent) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + scaleX: true, + scaleY: true, + scaleContent: true, + scaleFromCenter: false, + scaleMode: 'box', // 'box' or 'contents' or { } with provided values + scaleFrom: 100.0, + scaleTo: percent + }, arguments[2] || { }); + this.start(options); + }, + setup: function() { + this.restoreAfterFinish = this.options.restoreAfterFinish || false; + this.elementPositioning = this.element.getStyle('position'); + + this.originalStyle = { }; + ['top','left','width','height','fontSize'].each( function(k) { + this.originalStyle[k] = this.element.style[k]; + }.bind(this)); + + this.originalTop = this.element.offsetTop; + this.originalLeft = this.element.offsetLeft; + + var fontSize = this.element.getStyle('font-size') || '100%'; + ['em','px','%','pt'].each( function(fontSizeType) { + if (fontSize.indexOf(fontSizeType)>0) { + this.fontSize = parseFloat(fontSize); + this.fontSizeType = fontSizeType; + } + }.bind(this)); + + this.factor = (this.options.scaleTo - this.options.scaleFrom)/100; + + this.dims = null; + if (this.options.scaleMode=='box') + this.dims = [this.element.offsetHeight, this.element.offsetWidth]; + if (/^content/.test(this.options.scaleMode)) + this.dims = [this.element.scrollHeight, this.element.scrollWidth]; + if (!this.dims) + this.dims = [this.options.scaleMode.originalHeight, + this.options.scaleMode.originalWidth]; + }, + update: function(position) { + var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); + if (this.options.scaleContent && this.fontSize) + this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType }); + this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale); + }, + finish: function(position) { + if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle); + }, + setDimensions: function(height, width) { + var d = { }; + if (this.options.scaleX) d.width = width.round() + 'px'; + if (this.options.scaleY) d.height = height.round() + 'px'; + if (this.options.scaleFromCenter) { + var topd = (height - this.dims[0])/2; + var leftd = (width - this.dims[1])/2; + if (this.elementPositioning == 'absolute') { + if (this.options.scaleY) d.top = this.originalTop-topd + 'px'; + if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; + } else { + if (this.options.scaleY) d.top = -topd + 'px'; + if (this.options.scaleX) d.left = -leftd + 'px'; + } + } + this.element.setStyle(d); + } +}); + +Effect.Highlight = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { }); + this.start(options); + }, + setup: function() { + // Prevent executing on elements not in the layout flow + if (this.element.getStyle('display')=='none') { this.cancel(); return; } + // Disable background image during the effect + this.oldStyle = { }; + if (!this.options.keepBackgroundImage) { + this.oldStyle.backgroundImage = this.element.getStyle('background-image'); + this.element.setStyle({backgroundImage: 'none'}); + } + if (!this.options.endcolor) + this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff'); + if (!this.options.restorecolor) + this.options.restorecolor = this.element.getStyle('background-color'); + // init color calculations + this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this)); + this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this)); + }, + update: function(position) { + this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){ + return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) }); + }, + finish: function() { + this.element.setStyle(Object.extend(this.oldStyle, { + backgroundColor: this.options.restorecolor + })); + } +}); + +Effect.ScrollTo = function(element) { + var options = arguments[1] || { }, + scrollOffsets = document.viewport.getScrollOffsets(), + elementOffsets = $(element).cumulativeOffset(), + max = (window.height || document.body.scrollHeight) - document.viewport.getHeight(); + + if (options.offset) elementOffsets[1] += options.offset; + + return new Effect.Tween(null, + scrollOffsets.top, + elementOffsets[1] > max ? max : elementOffsets[1], + options, + function(p){ scrollTo(scrollOffsets.left, p.round()) } + ); +}; + +/* ------------- combination effects ------------- */ + +Effect.Fade = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + var options = Object.extend({ + from: element.getOpacity() || 1.0, + to: 0.0, + afterFinishInternal: function(effect) { + if (effect.options.to!=0) return; + effect.element.hide().setStyle({opacity: oldOpacity}); + } + }, arguments[1] || { }); + return new Effect.Opacity(element,options); +}; + +Effect.Appear = function(element) { + element = $(element); + var options = Object.extend({ + from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0), + to: 1.0, + // force Safari to render floated elements properly + afterFinishInternal: function(effect) { + effect.element.forceRerendering(); + }, + beforeSetup: function(effect) { + effect.element.setOpacity(effect.options.from).show(); + }}, arguments[1] || { }); + return new Effect.Opacity(element,options); +}; + +Effect.Puff = function(element) { + element = $(element); + var oldStyle = { + opacity: element.getInlineOpacity(), + position: element.getStyle('position'), + top: element.style.top, + left: element.style.left, + width: element.style.width, + height: element.style.height + }; + return new Effect.Parallel( + [ new Effect.Scale(element, 200, + { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], + Object.extend({ duration: 1.0, + beforeSetupInternal: function(effect) { + Position.absolutize(effect.effects[0].element) + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().setStyle(oldStyle); } + }, arguments[1] || { }) + ); +}; + +Effect.BlindUp = function(element) { + element = $(element); + element.makeClipping(); + return new Effect.Scale(element, 0, + Object.extend({ scaleContent: false, + scaleX: false, + restoreAfterFinish: true, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping(); + } + }, arguments[1] || { }) + ); +}; + +Effect.BlindDown = function(element) { + element = $(element); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, + scaleFrom: 0, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makeClipping().setStyle({height: '0px'}).show(); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping(); + } + }, arguments[1] || { })); +}; + +Effect.SwitchOff = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + return new Effect.Appear(element, Object.extend({ + duration: 0.4, + from: 0, + transition: Effect.Transitions.flicker, + afterFinishInternal: function(effect) { + new Effect.Scale(effect.element, 1, { + duration: 0.3, scaleFromCenter: true, + scaleX: false, scaleContent: false, restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makePositioned().makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity}); + } + }) + } + }, arguments[1] || { })); +}; + +Effect.DropOut = function(element) { + element = $(element); + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left'), + opacity: element.getInlineOpacity() }; + return new Effect.Parallel( + [ new Effect.Move(element, {x: 0, y: 100, sync: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 }) ], + Object.extend( + { duration: 0.5, + beforeSetup: function(effect) { + effect.effects[0].element.makePositioned(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle); + } + }, arguments[1] || { })); +}; + +Effect.Shake = function(element) { + element = $(element); + var options = Object.extend({ + distance: 20, + duration: 0.5 + }, arguments[1] || {}); + var distance = parseFloat(options.distance); + var split = parseFloat(options.duration) / 10.0; + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left') }; + return new Effect.Move(element, + { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) { + effect.element.undoPositioned().setStyle(oldStyle); + }}) }}) }}) }}) }}) }}); +}; + +Effect.SlideDown = function(element) { + element = $(element).cleanWhitespace(); + // SlideDown need to have the content of the element wrapped in a container element with fixed height! + var oldInnerBottom = element.down().getStyle('bottom'); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, + scaleFrom: window.opera ? 0 : 1, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makePositioned(); + effect.element.down().makePositioned(); + if (window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping().setStyle({height: '0px'}).show(); + }, + afterUpdateInternal: function(effect) { + effect.element.down().setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping().undoPositioned(); + effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); } + }, arguments[1] || { }) + ); +}; + +Effect.SlideUp = function(element) { + element = $(element).cleanWhitespace(); + var oldInnerBottom = element.down().getStyle('bottom'); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, window.opera ? 0 : 1, + Object.extend({ scaleContent: false, + scaleX: false, + scaleMode: 'box', + scaleFrom: 100, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makePositioned(); + effect.element.down().makePositioned(); + if (window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping().show(); + }, + afterUpdateInternal: function(effect) { + effect.element.down().setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().undoPositioned(); + effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); + } + }, arguments[1] || { }) + ); +}; + +// Bug in opera makes the TD containing this element expand for a instance after finish +Effect.Squish = function(element) { + return new Effect.Scale(element, window.opera ? 1 : 0, { + restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping(); + } + }); +}; + +Effect.Grow = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.full + }, arguments[1] || { }); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var initialMoveX, initialMoveY; + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + initialMoveX = initialMoveY = moveX = moveY = 0; + break; + case 'top-right': + initialMoveX = dims.width; + initialMoveY = moveY = 0; + moveX = -dims.width; + break; + case 'bottom-left': + initialMoveX = moveX = 0; + initialMoveY = dims.height; + moveY = -dims.height; + break; + case 'bottom-right': + initialMoveX = dims.width; + initialMoveY = dims.height; + moveX = -dims.width; + moveY = -dims.height; + break; + case 'center': + initialMoveX = dims.width / 2; + initialMoveY = dims.height / 2; + moveX = -dims.width / 2; + moveY = -dims.height / 2; + break; + } + + return new Effect.Move(element, { + x: initialMoveX, + y: initialMoveY, + duration: 0.01, + beforeSetup: function(effect) { + effect.element.hide().makeClipping().makePositioned(); + }, + afterFinishInternal: function(effect) { + new Effect.Parallel( + [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }), + new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }), + new Effect.Scale(effect.element, 100, { + scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, + sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true}) + ], Object.extend({ + beforeSetup: function(effect) { + effect.effects[0].element.setStyle({height: '0px'}).show(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); + } + }, options) + ) + } + }); +}; + +Effect.Shrink = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.none + }, arguments[1] || { }); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + moveX = moveY = 0; + break; + case 'top-right': + moveX = dims.width; + moveY = 0; + break; + case 'bottom-left': + moveX = 0; + moveY = dims.height; + break; + case 'bottom-right': + moveX = dims.width; + moveY = dims.height; + break; + case 'center': + moveX = dims.width / 2; + moveY = dims.height / 2; + break; + } + + return new Effect.Parallel( + [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }), + new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}), + new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }) + ], Object.extend({ + beforeStartInternal: function(effect) { + effect.effects[0].element.makePositioned().makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); } + }, options) + ); +}; + +Effect.Pulsate = function(element) { + element = $(element); + var options = arguments[1] || { }; + var oldOpacity = element.getInlineOpacity(); + var transition = options.transition || Effect.Transitions.sinoidal; + var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) }; + reverser.bind(transition); + return new Effect.Opacity(element, + Object.extend(Object.extend({ duration: 2.0, from: 0, + afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); } + }, options), {transition: reverser})); +}; + +Effect.Fold = function(element) { + element = $(element); + var oldStyle = { + top: element.style.top, + left: element.style.left, + width: element.style.width, + height: element.style.height }; + element.makeClipping(); + return new Effect.Scale(element, 5, Object.extend({ + scaleContent: false, + scaleX: false, + afterFinishInternal: function(effect) { + new Effect.Scale(element, 1, { + scaleContent: false, + scaleY: false, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().setStyle(oldStyle); + } }); + }}, arguments[1] || { })); +}; + +Effect.Morph = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + style: { } + }, arguments[1] || { }); + + if (!Object.isString(options.style)) this.style = $H(options.style); + else { + if (options.style.include(':')) + this.style = options.style.parseStyle(); + else { + this.element.addClassName(options.style); + this.style = $H(this.element.getStyles()); + this.element.removeClassName(options.style); + var css = this.element.getStyles(); + this.style = this.style.reject(function(style) { + return style.value == css[style.key]; + }); + options.afterFinishInternal = function(effect) { + effect.element.addClassName(effect.options.style); + effect.transforms.each(function(transform) { + effect.element.style[transform.style] = ''; + }); + } + } + } + this.start(options); + }, + + setup: function(){ + function parseColor(color){ + if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff'; + color = color.parseColor(); + return $R(0,2).map(function(i){ + return parseInt( color.slice(i*2+1,i*2+3), 16 ) + }); + } + this.transforms = this.style.map(function(pair){ + var property = pair[0], value = pair[1], unit = null; + + if (value.parseColor('#zzzzzz') != '#zzzzzz') { + value = value.parseColor(); + unit = 'color'; + } else if (property == 'opacity') { + value = parseFloat(value); + if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) + this.element.setStyle({zoom: 1}); + } else if (Element.CSS_LENGTH.test(value)) { + var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/); + value = parseFloat(components[1]); + unit = (components.length == 3) ? components[2] : null; + } + + var originalValue = this.element.getStyle(property); + return { + style: property.camelize(), + originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), + targetValue: unit=='color' ? parseColor(value) : value, + unit: unit + }; + }.bind(this)).reject(function(transform){ + return ( + (transform.originalValue == transform.targetValue) || + ( + transform.unit != 'color' && + (isNaN(transform.originalValue) || isNaN(transform.targetValue)) + ) + ) + }); + }, + update: function(position) { + var style = { }, transform, i = this.transforms.length; + while(i--) + style[(transform = this.transforms[i]).style] = + transform.unit=='color' ? '#'+ + (Math.round(transform.originalValue[0]+ + (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() + + (Math.round(transform.originalValue[1]+ + (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() + + (Math.round(transform.originalValue[2]+ + (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() : + (transform.originalValue + + (transform.targetValue - transform.originalValue) * position).toFixed(3) + + (transform.unit === null ? '' : transform.unit); + this.element.setStyle(style, true); + } +}); + +Effect.Transform = Class.create({ + initialize: function(tracks){ + this.tracks = []; + this.options = arguments[1] || { }; + this.addTracks(tracks); + }, + addTracks: function(tracks){ + tracks.each(function(track){ + track = $H(track); + var data = track.values().first(); + this.tracks.push($H({ + ids: track.keys().first(), + effect: Effect.Morph, + options: { style: data } + })); + }.bind(this)); + return this; + }, + play: function(){ + return new Effect.Parallel( + this.tracks.map(function(track){ + var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options'); + var elements = [$(ids) || $$(ids)].flatten(); + return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) }); + }).flatten(), + this.options + ); + } +}); + +Element.CSS_PROPERTIES = $w( + 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + + 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' + + 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' + + 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' + + 'fontSize fontWeight height left letterSpacing lineHeight ' + + 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+ + 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' + + 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' + + 'right textIndent top width wordSpacing zIndex'); + +Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/; + +String.__parseStyleElement = document.createElement('div'); +String.prototype.parseStyle = function(){ + var style, styleRules = $H(); + if (Prototype.Browser.WebKit) + style = new Element('div',{style:this}).style; + else { + String.__parseStyleElement.innerHTML = '
    '; + style = String.__parseStyleElement.childNodes[0].style; + } + + Element.CSS_PROPERTIES.each(function(property){ + if (style[property]) styleRules.set(property, style[property]); + }); + + if (Prototype.Browser.IE && this.include('opacity')) + styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]); + + return styleRules; +}; + +if (document.defaultView && document.defaultView.getComputedStyle) { + Element.getStyles = function(element) { + var css = document.defaultView.getComputedStyle($(element), null); + return Element.CSS_PROPERTIES.inject({ }, function(styles, property) { + styles[property] = css[property]; + return styles; + }); + }; +} else { + Element.getStyles = function(element) { + element = $(element); + var css = element.currentStyle, styles; + styles = Element.CSS_PROPERTIES.inject({ }, function(hash, property) { + hash.set(property, css[property]); + return hash; + }); + if (!styles.opacity) styles.set('opacity', element.getOpacity()); + return styles; + }; +}; + +Effect.Methods = { + morph: function(element, style) { + element = $(element); + new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { })); + return element; + }, + visualEffect: function(element, effect, options) { + element = $(element) + var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1); + new Effect[klass](element, options); + return element; + }, + highlight: function(element, options) { + element = $(element); + new Effect.Highlight(element, options); + return element; + } +}; + +$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+ + 'pulsate shake puff squish switchOff dropOut').each( + function(effect) { + Effect.Methods[effect] = function(element, options){ + element = $(element); + Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options); + return element; + } + } +); + +$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( + function(f) { Effect.Methods[f] = Element[f]; } +); + +Element.addMethods(Effect.Methods); diff --git a/libjs/external.js b/libjs/external.js new file mode 100644 index 0000000..a080c66 --- /dev/null +++ b/libjs/external.js @@ -0,0 +1,27 @@ +function externalLinks() +{ + if(!document.getElementsByTagName) + { + return; + } + var anchors = document.getElementsByTagName("a"); + var msg = ''; + var tHref = ''; + var baseurl = document.baseURI; + msg += baseurl + '\n'; + for(var i=0; i"); +} + +google.setOnLoadCallback(initGoogleSearch); diff --git a/libjs/homeFeaturedNav.js b/libjs/homeFeaturedNav.js new file mode 100755 index 0000000..077e06d --- /dev/null +++ b/libjs/homeFeaturedNav.js @@ -0,0 +1,15 @@ +$(function() { + $('#testscroller').cycle({ + fx: 'scrollDown' + }); +}); + +$(function() { + $('#s4').before('
    ').cycle({ + fx: 'fade', + speed: '4000', + timeout: 12000, + pager: '#featuredNav', + before: function() { if (window.console) console.log(this.src); } + }); +}); diff --git a/libjs/jquery-1.0.1.js.bakw b/libjs/jquery-1.0.1.js.bakw new file mode 100644 index 0000000..f7dc203 --- /dev/null +++ b/libjs/jquery-1.0.1.js.bakw @@ -0,0 +1,1826 @@ +/* + * jQuery - New Wave Javascript + * + * Copyright (c) 2006 John Resig (jquery.com) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * $Date: 2009/09/17 20:08:58 $ + * $Rev: 249 $ + */ + +// Global undefined variable +window.undefined = window.undefined; +function jQuery(a,c) { + + // Shortcut for document ready (because $(document).each() is silly) + if ( a && a.constructor == Function && jQuery.fn.ready ) + return jQuery(document).ready(a); + + // Make sure that a selection was provided + a = a || jQuery.context || document; + + // Watch for when a jQuery object is passed as the selector + if ( a.jquery ) + return $( jQuery.merge( a, [] ) ); + + // Watch for when a jQuery object is passed at the context + if ( c && c.jquery ) + return $( c ).find(a); + + // If the context is global, return a new object + if ( window == this ) + return new jQuery(a,c); + + // Handle HTML strings + var m = /^[^<]*(<.+>)[^>]*$/.exec(a); + if ( m ) a = jQuery.clean( [ m[1] ] ); + + // Watch for when an array is passed in + this.get( a.constructor == Array || a.length && !a.nodeType && a[0] != undefined && a[0].nodeType ? + // Assume that it is an array of DOM Elements + jQuery.merge( a, [] ) : + + // Find the matching elements and save them for later + jQuery.find( a, c ) ); + + // See if an extra function was provided + var fn = arguments[ arguments.length - 1 ]; + + // If so, execute it in context + if ( fn && fn.constructor == Function ) + this.each(fn); +} + +// Map over the $ in case of overwrite +if ( typeof $ != "undefined" ) + jQuery._$ = $; + +// Map the jQuery namespace to the '$' one +var $ = jQuery; + +jQuery.fn = jQuery.prototype = { + jquery: "$Rev: 249 $", + + size: function() { + return this.length; + }, + + get: function( num ) { + // Watch for when an array (of elements) is passed in + if ( num && num.constructor == Array ) { + + // Use a tricky hack to make the jQuery object + // look and feel like an array + this.length = 0; + [].push.apply( this, num ); + + return this; + } else + return num == undefined ? + + // Return a 'clean' array + jQuery.map( this, function(a){ return a } ) : + + // Return just the object + this[num]; + }, + each: function( fn, args ) { + return jQuery.each( this, fn, args ); + }, + + index: function( obj ) { + var pos = -1; + this.each(function(i){ + if ( this == obj ) pos = i; + }); + return pos; + }, + + attr: function( key, value, type ) { + // Check to see if we're setting style values + return key.constructor != String || value != undefined ? + this.each(function(){ + // See if we're setting a hash of styles + if ( value == undefined ) + // Set all the styles + for ( var prop in key ) + jQuery.attr( + type ? this.style : this, + prop, key[prop] + ); + + // See if we're setting a single key/value style + else + jQuery.attr( + type ? this.style : this, + key, value + ); + }) : + + // Look for the case where we're accessing a style value + jQuery[ type || "attr" ]( this[0], key ); + }, + + css: function( key, value ) { + return this.attr( key, value, "curCSS" ); + }, + text: function(e) { + e = e || this; + var t = ""; + for ( var j = 0; j < e.length; j++ ) { + var r = e[j].childNodes; + for ( var i = 0; i < r.length; i++ ) + if ( r[i].nodeType != 8 ) + t += r[i].nodeType != 1 ? + r[i].nodeValue : jQuery.fn.text([ r[i] ]); + } + return t; + }, + wrap: function() { + // The elements to wrap the target around + var a = jQuery.clean(arguments); + + // Wrap each of the matched elements individually + return this.each(function(){ + // Clone the structure that we're using to wrap + var b = a[0].cloneNode(true); + + // Insert it before the element to be wrapped + this.parentNode.insertBefore( b, this ); + + // Find he deepest point in the wrap structure + while ( b.firstChild ) + b = b.firstChild; + + // Move the matched element to within the wrap structure + b.appendChild( this ); + }); + }, + append: function() { + return this.domManip(arguments, true, 1, function(a){ + this.appendChild( a ); + }); + }, + prepend: function() { + return this.domManip(arguments, true, -1, function(a){ + this.insertBefore( a, this.firstChild ); + }); + }, + before: function() { + return this.domManip(arguments, false, 1, function(a){ + this.parentNode.insertBefore( a, this ); + }); + }, + after: function() { + return this.domManip(arguments, false, -1, function(a){ + this.parentNode.insertBefore( a, this.nextSibling ); + }); + }, + end: function() { + return this.get( this.stack.pop() ); + }, + find: function(t) { + return this.pushStack( jQuery.map( this, function(a){ + return jQuery.find(t,a); + }), arguments ); + }, + + clone: function(deep) { + return this.pushStack( jQuery.map( this, function(a){ + return a.cloneNode( deep != undefined ? deep : true ); + }), arguments ); + }, + + filter: function(t) { + return this.pushStack( + t.constructor == Array && + jQuery.map(this,function(a){ + for ( var i = 0; i < t.length; i++ ) + if ( jQuery.filter(t[i],[a]).r.length ) + return a; + }) || + + t.constructor == Boolean && + ( t ? this.get() : [] ) || + + t.constructor == Function && + jQuery.grep( this, t ) || + + jQuery.filter(t,this).r, arguments ); + }, + + not: function(t) { + return this.pushStack( t.constructor == String ? + jQuery.filter(t,this,false).r : + jQuery.grep(this,function(a){ return a != t; }), arguments ); + }, + + add: function(t) { + return this.pushStack( jQuery.merge( this, t.constructor == String ? + jQuery.find(t) : t.constructor == Array ? t : [t] ), arguments ); + }, + is: function(expr) { + return expr ? jQuery.filter(expr,this).r.length > 0 : this.length > 0; + }, + domManip: function(args, table, dir, fn){ + var clone = this.size() > 1; + var a = jQuery.clean(args); + + return this.each(function(){ + var obj = this; + + if ( table && this.nodeName == "TABLE" && a[0].nodeName != "THEAD" ) { + var tbody = this.getElementsByTagName("tbody"); + + if ( !tbody.length ) { + obj = document.createElement("tbody"); + this.appendChild( obj ); + } else + obj = tbody[0]; + } + + for ( var i = ( dir < 0 ? a.length - 1 : 0 ); + i != ( dir < 0 ? dir : a.length ); i += dir ) { + fn.apply( obj, [ clone ? a[i].cloneNode(true) : a[i] ] ); + } + }); + }, + pushStack: function(a,args) { + var fn = args && args[args.length-1]; + + if ( !fn || fn.constructor != Function ) { + if ( !this.stack ) this.stack = []; + this.stack.push( this.get() ); + this.get( a ); + } else { + var old = this.get(); + this.get( a ); + if ( fn.constructor == Function ) + return this.each( fn ); + this.get( old ); + } + + return this; + } +}; + +jQuery.extend = jQuery.fn.extend = function(obj,prop) { + if ( !prop ) { prop = obj; obj = this; } + for ( var i in prop ) obj[i] = prop[i]; + return obj; +}; + +jQuery.extend({ + init: function(){ + jQuery.initDone = true; + + jQuery.each( jQuery.macros.axis, function(i,n){ + jQuery.fn[ i ] = function(a) { + var ret = jQuery.map(this,n); + if ( a && a.constructor == String ) + ret = jQuery.filter(a,ret).r; + return this.pushStack( ret, arguments ); + }; + }); + + jQuery.each( jQuery.macros.to, function(i,n){ + jQuery.fn[ i ] = function(){ + var a = arguments; + return this.each(function(){ + for ( var j = 0; j < a.length; j++ ) + $(a[j])[n]( this ); + }); + }; + }); + + jQuery.each( jQuery.macros.each, function(i,n){ + jQuery.fn[ i ] = function() { + return this.each( n, arguments ); + }; + }); + + jQuery.each( jQuery.macros.filter, function(i,n){ + jQuery.fn[ n ] = function(num,fn) { + return this.filter( ":" + n + "(" + num + ")", fn ); + }; + }); + + jQuery.each( jQuery.macros.attr, function(i,n){ + n = n || i; + jQuery.fn[ i ] = function(h) { + return h == undefined ? + this.length ? this[0][n] : null : + this.attr( n, h ); + }; + }); + + jQuery.each( jQuery.macros.css, function(i,n){ + jQuery.fn[ n ] = function(h) { + return h == undefined ? + ( this.length ? jQuery.css( this[0], n ) : null ) : + this.css( n, h ); + }; + }); + + }, + each: function( obj, fn, args ) { + if ( obj.length == undefined ) + for ( var i in obj ) + fn.apply( obj[i], args || [i, obj[i]] ); + else + for ( var i = 0; i < obj.length; i++ ) + fn.apply( obj[i], args || [i, obj[i]] ); + return obj; + }, + + className: { + add: function(o,c){ + if (jQuery.className.has(o,c)) return; + o.className += ( o.className ? " " : "" ) + c; + }, + remove: function(o,c){ + o.className = !c ? "" : + o.className.replace( + new RegExp("(^|\\s*\\b[^-])"+c+"($|\\b(?=[^-]))", "g"), ""); + }, + has: function(e,a) { + if ( e.className != undefined ) + e = e.className; + return new RegExp("(^|\\s)" + a + "(\\s|$)").test(e); + } + }, + swap: function(e,o,f) { + for ( var i in o ) { + e.style["old"+i] = e.style[i]; + e.style[i] = o[i]; + } + f.apply( e, [] ); + for ( var i in o ) + e.style[i] = e.style["old"+i]; + }, + + css: function(e,p) { + if ( p == "height" || p == "width" ) { + var old = {}, oHeight, oWidth, d = ["Top","Bottom","Right","Left"]; + + for ( var i in d ) { + old["padding" + d[i]] = 0; + old["border" + d[i] + "Width"] = 0; + } + + jQuery.swap( e, old, function() { + if (jQuery.css(e,"display") != "none") { + oHeight = e.offsetHeight; + oWidth = e.offsetWidth; + } else { + e = $(e.cloneNode(true)).css({ + visibility: "hidden", position: "absolute", display: "block" + }).prependTo("body")[0]; + + oHeight = e.clientHeight; + oWidth = e.clientWidth; + + e.parentNode.removeChild(e); + } + }); + + return p == "height" ? oHeight : oWidth; + } else if ( p == "opacity" && jQuery.browser.msie ) + return parseFloat( jQuery.curCSS(e,"filter").replace(/[^0-9.]/,"") ) || 1; + + return jQuery.curCSS( e, p ); + }, + + curCSS: function(elem, prop, force) { + var ret; + + if (!force && elem.style[prop]) { + + ret = elem.style[prop]; + + } else if (elem.currentStyle) { + + var newProp = prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase()}); + ret = elem.currentStyle[prop] || elem.currentStyle[newProp]; + + } else if (document.defaultView && document.defaultView.getComputedStyle) { + + prop = prop.replace(/([A-Z])/g,"-$1").toLowerCase(); + var cur = document.defaultView.getComputedStyle(elem, null); + + if ( cur ) + ret = cur.getPropertyValue(prop); + else if ( prop == 'display' ) + ret = 'none'; + else + jQuery.swap(elem, { display: 'block' }, function() { + ret = document.defaultView.getComputedStyle(this,null).getPropertyValue(prop); + }); + + } + + return ret; + }, + + clean: function(a) { + var r = []; + for ( var i = 0; i < a.length; i++ ) { + if ( a[i].constructor == String ) { + + var table = ""; + + if ( !a[i].indexOf(""; + } else if ( !a[i].indexOf(""; + } else if ( !a[i].indexOf(""; + } + + var div = document.createElement("div"); + div.innerHTML = a[i]; + + if ( table ) { + div = div.firstChild; + if ( table != "thead" ) div = div.firstChild; + if ( table == "td" ) div = div.firstChild; + } + + for ( var j = 0; j < div.childNodes.length; j++ ) + r.push( div.childNodes[j] ); + } else if ( a[i].jquery || a[i].length && !a[i].nodeType ) + for ( var k = 0; k < a[i].length; k++ ) + r.push( a[i][k] ); + else if ( a[i] !== null ) + r.push( a[i].nodeType ? a[i] : document.createTextNode(a[i].toString()) ); + } + return r; + }, + + expr: { + "": "m[2]== '*'||a.nodeName.toUpperCase()==m[2].toUpperCase()", + "#": "a.getAttribute('id')&&a.getAttribute('id')==m[2]", + ":": { + // Position Checks + lt: "im[3]-0", + nth: "m[3]-0==i", + eq: "m[3]-0==i", + first: "i==0", + last: "i==r.length-1", + even: "i%2==0", + odd: "i%2", + + // Child Checks + "nth-child": "jQuery.sibling(a,m[3]).cur", + "first-child": "jQuery.sibling(a,0).cur", + "last-child": "jQuery.sibling(a,0).last", + "only-child": "jQuery.sibling(a).length==1", + + // Parent Checks + parent: "a.childNodes.length", + empty: "!a.childNodes.length", + + // Text Check + contains: "(a.innerText||a.innerHTML).indexOf(m[3])>=0", + + // Visibility + visible: "a.type!='hidden'&&jQuery.css(a,'display')!='none'&&jQuery.css(a,'visibility')!='hidden'", + hidden: "a.type=='hidden'||jQuery.css(a,'display')=='none'||jQuery.css(a,'visibility')=='hidden'", + + // Form elements + enabled: "!a.disabled", + disabled: "a.disabled", + checked: "a.checked", + selected: "a.selected" + }, + ".": "jQuery.className.has(a,m[2])", + "@": { + "=": "z==m[4]", + "!=": "z!=m[4]", + "^=": "!z.indexOf(m[4])", + "$=": "z.substr(z.length - m[4].length,m[4].length)==m[4]", + "*=": "z.indexOf(m[4])>=0", + "": "z" + }, + "[": "jQuery.find(m[2],a).length" + }, + + token: [ + "\\.\\.|/\\.\\.", "a.parentNode", + ">|/", "jQuery.sibling(a.firstChild)", + "\\+", "jQuery.sibling(a).next", + "~", function(a){ + var r = []; + var s = jQuery.sibling(a); + if ( s.n > 0 ) + for ( var i = s.n; i < s.length; i++ ) + r.push( s[i] ); + return r; + } + ], + find: function( t, context ) { + // Make sure that the context is a DOM Element + if ( context && context.nodeType == undefined ) + context = null; + + // Set the correct context (if none is provided) + context = context || jQuery.context || document; + + if ( t.constructor != String ) return [t]; + + if ( !t.indexOf("//") ) { + context = context.documentElement; + t = t.substr(2,t.length); + } else if ( !t.indexOf("/") ) { + context = context.documentElement; + t = t.substr(1,t.length); + // FIX Assume the root element is right :( + if ( t.indexOf("/") >= 1 ) + t = t.substr(t.indexOf("/"),t.length); + } + + var ret = [context]; + var done = []; + var last = null; + + while ( t.length > 0 && last != t ) { + var r = []; + last = t; + + t = jQuery.trim(t).replace( /^\/\//i, "" ); + + var foundToken = false; + + for ( var i = 0; i < jQuery.token.length; i += 2 ) { + if ( foundToken ) continue; + + var re = new RegExp("^(" + jQuery.token[i] + ")"); + var m = re.exec(t); + + if ( m ) { + r = ret = jQuery.map( ret, jQuery.token[i+1] ); + t = jQuery.trim( t.replace( re, "" ) ); + foundToken = true; + } + } + + if ( !foundToken ) { + if ( !t.indexOf(",") || !t.indexOf("|") ) { + if ( ret[0] == context ) ret.shift(); + done = jQuery.merge( done, ret ); + r = ret = [context]; + t = " " + t.substr(1,t.length); + } else { + var re2 = /^([#.]?)([a-z0-9\\*_-]*)/i; + var m = re2.exec(t); + + if ( m[1] == "#" ) { + // Ummm, should make this work in all XML docs + var oid = document.getElementById(m[2]); + r = ret = oid ? [oid] : []; + t = t.replace( re2, "" ); + } else { + if ( !m[2] || m[1] == "." ) m[2] = "*"; + + for ( var i = 0; i < ret.length; i++ ) + r = jQuery.merge( r, + m[2] == "*" ? + jQuery.getAll(ret[i]) : + ret[i].getElementsByTagName(m[2]) + ); + } + } + + } + + if ( t ) { + var val = jQuery.filter(t,r); + ret = r = val.r; + t = jQuery.trim(val.t); + } + } + + if ( ret && ret[0] == context ) ret.shift(); + done = jQuery.merge( done, ret ); + + return done; + }, + + getAll: function(o,r) { + r = r || []; + var s = o.childNodes; + for ( var i = 0; i < s.length; i++ ) + if ( s[i].nodeType == 1 ) { + r.push( s[i] ); + jQuery.getAll( s[i], r ); + } + return r; + }, + + attr: function(elem, name, value){ + var fix = { + "for": "htmlFor", + "class": "className", + "float": "cssFloat", + innerHTML: "innerHTML", + className: "className", + value: "value", + disabled: "disabled" + }; + + if ( fix[name] ) { + if ( value != undefined ) elem[fix[name]] = value; + return elem[fix[name]]; + } else if ( elem.getAttribute ) { + if ( value != undefined ) elem.setAttribute( name, value ); + return elem.getAttribute( name, 2 ); + } else { + name = name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();}); + if ( value != undefined ) elem[name] = value; + return elem[name]; + } + }, + + // The regular expressions that power the parsing engine + parse: [ + // Match: [@value='test'], [@foo] + [ "\\[ *(@)S *([!*$^=]*) *Q\\]", 1 ], + + // Match: [div], [div p] + [ "(\\[)Q\\]", 0 ], + + // Match: :contains('foo') + [ "(:)S\\(Q\\)", 0 ], + + // Match: :even, :last-chlid + [ "([:.#]*)S", 0 ] + ], + + filter: function(t,r,not) { + // Figure out if we're doing regular, or inverse, filtering + var g = not !== false ? jQuery.grep : + function(a,f) {return jQuery.grep(a,f,true);}; + + while ( t && /^[a-z[({<*:.#]/i.test(t) ) { + + var p = jQuery.parse; + + for ( var i = 0; i < p.length; i++ ) { + var re = new RegExp( "^" + p[i][0] + + // Look for a string-like sequence + .replace( 'S', "([a-z*_-][a-z0-9_-]*)" ) + + // Look for something (optionally) enclosed with quotes + .replace( 'Q', " *'?\"?([^'\"]*?)'?\"? *" ), "i" ); + + var m = re.exec( t ); + + if ( m ) { + // Re-organize the match + if ( p[i][1] ) + m = ["", m[1], m[3], m[2], m[4]]; + + // Remove what we just matched + t = t.replace( re, "" ); + + break; + } + } + + // :not() is a special case that can be optomized by + // keeping it out of the expression list + if ( m[1] == ":" && m[2] == "not" ) + r = jQuery.filter(m[3],r,false).r; + + // Otherwise, find the expression to execute + else { + var f = jQuery.expr[m[1]]; + if ( f.constructor != String ) + f = jQuery.expr[m[1]][m[2]]; + + // Build a custom macro to enclose it + eval("f = function(a,i){" + + ( m[1] == "@" ? "z=jQuery.attr(a,m[3]);" : "" ) + + "return " + f + "}"); + + // Execute it against the current filter + r = g( r, f ); + } + } + + // Return an array of filtered elements (r) + // and the modified expression string (t) + return { r: r, t: t }; + }, + trim: function(t){ + return t.replace(/^\s+|\s+$/g, ""); + }, + parents: function( elem ){ + var matched = []; + var cur = elem.parentNode; + while ( cur && cur != document ) { + matched.push( cur ); + cur = cur.parentNode; + } + return matched; + }, + sibling: function(elem, pos, not) { + var elems = []; + + var siblings = elem.parentNode.childNodes; + for ( var i = 0; i < siblings.length; i++ ) { + if ( not === true && siblings[i] == elem ) continue; + + if ( siblings[i].nodeType == 1 ) + elems.push( siblings[i] ); + if ( siblings[i] == elem ) + elems.n = elems.length - 1; + } + + return jQuery.extend( elems, { + last: elems.n == elems.length - 1, + cur: pos == "even" && elems.n % 2 == 0 || pos == "odd" && elems.n % 2 || elems[pos] == elem, + prev: elems[elems.n - 1], + next: elems[elems.n + 1] + }); + }, + merge: function(first, second) { + var result = []; + + // Move b over to the new array (this helps to avoid + // StaticNodeList instances) + for ( var k = 0; k < first.length; k++ ) + result[k] = first[k]; + + // Now check for duplicates between a and b and only + // add the unique items + for ( var i = 0; i < second.length; i++ ) { + var noCollision = true; + + // The collision-checking process + for ( var j = 0; j < first.length; j++ ) + if ( second[i] == first[j] ) + noCollision = false; + + // If the item is unique, add it + if ( noCollision ) + result.push( second[i] ); + } + + return result; + }, + grep: function(elems, fn, inv) { + // If a string is passed in for the function, make a function + // for it (a handy shortcut) + if ( fn.constructor == String ) + fn = new Function("a","i","return " + fn); + + var result = []; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0; i < elems.length; i++ ) + if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) ) + result.push( elems[i] ); + + return result; + }, + map: function(elems, fn) { + // If a string is passed in for the function, make a function + // for it (a handy shortcut) + if ( fn.constructor == String ) + fn = new Function("a","return " + fn); + + var result = []; + + // Go through the array, translating each of the items to their + // new value (or values). + for ( var i = 0; i < elems.length; i++ ) { + var val = fn(elems[i],i); + + if ( val !== null && val != undefined ) { + if ( val.constructor != Array ) val = [val]; + result = jQuery.merge( result, val ); + } + } + + return result; + }, + + /* + * A number of helper functions used for managing events. + * Many of the ideas behind this code orignated from Dean Edwards' addEvent library. + */ + event: { + + // Bind an event to an element + // Original by Dean Edwards + add: function(element, type, handler) { + // For whatever reason, IE has trouble passing the window object + // around, causing it to be cloned in the process + if ( jQuery.browser.msie && element.setInterval != undefined ) + element = window; + + // Make sure that the function being executed has a unique ID + if ( !handler.guid ) + handler.guid = this.guid++; + + // Init the element's event structure + if (!element.events) + element.events = {}; + + // Get the current list of functions bound to this event + var handlers = element.events[type]; + + // If it hasn't been initialized yet + if (!handlers) { + // Init the event handler queue + handlers = element.events[type] = {}; + + // Remember an existing handler, if it's already there + if (element["on" + type]) + handlers[0] = element["on" + type]; + } + + // Add the function to the element's handler list + handlers[handler.guid] = handler; + + // And bind the global event handler to the element + element["on" + type] = this.handle; + + // Remember the function in a global list (for triggering) + if (!this.global[type]) + this.global[type] = []; + this.global[type].push( element ); + }, + + guid: 1, + global: {}, + + // Detach an event or set of events from an element + remove: function(element, type, handler) { + if (element.events) + if (type && element.events[type]) + if ( handler ) + delete element.events[type][handler.guid]; + else + for ( var i in element.events[type] ) + delete element.events[type][i]; + else + for ( var j in element.events ) + this.remove( element, j ); + }, + + trigger: function(type,data,element) { + // Touch up the incoming data + data = data || []; + + // Handle a global trigger + if ( !element ) { + var g = this.global[type]; + if ( g ) + for ( var i = 0; i < g.length; i++ ) + this.trigger( type, data, g[i] ); + + // Handle triggering a single element + } else if ( element["on" + type] ) { + // Pass along a fake event + data.unshift( this.fix({ type: type, target: element }) ); + + // Trigger the event + element["on" + type].apply( element, data ); + } + }, + + handle: function(event) { + if ( typeof jQuery == "undefined" ) return; + + event = event || jQuery.event.fix( window.event ); + + // If no correct event was found, fail + if ( !event ) return; + + var returnValue = true; + + var c = this.events[event.type]; + + for ( var j in c ) { + if ( c[j].apply( this, [event] ) === false ) { + event.preventDefault(); + event.stopPropagation(); + returnValue = false; + } + } + + return returnValue; + }, + + fix: function(event) { + if ( event ) { + event.preventDefault = function() { + this.returnValue = false; + }; + + event.stopPropagation = function() { + this.cancelBubble = true; + }; + } + + return event; + } + + } +}); + +new function() { + var b = navigator.userAgent.toLowerCase(); + + // Figure out what browser is being used + jQuery.browser = { + safari: /webkit/.test(b), + opera: /opera/.test(b), + msie: /msie/.test(b) && !/opera/.test(b), + mozilla: /mozilla/.test(b) && !/compatible/.test(b) + }; + + // Check to see if the W3C box model is being used + jQuery.boxModel = !jQuery.browser.msie || document.compatMode == "CSS1Compat"; +}; + +jQuery.macros = { + to: { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after" + }, + + + css: "width,height,top,left,position,float,overflow,color,background".split(","), + + filter: [ "eq", "lt", "gt", "contains" ], + + attr: { + + val: "value", + + html: "innerHTML", + + id: null, + + title: null, + + name: null, + + href: null, + + src: null, + + rel: null + }, + + axis: { + + parent: "a.parentNode", + + ancestors: jQuery.parents, + + parents: jQuery.parents, + + next: "jQuery.sibling(a).next", + + prev: "jQuery.sibling(a).prev", + + siblings: jQuery.sibling, + + children: "jQuery.sibling(a.firstChild)" + }, + + each: { + + removeAttr: function( key ) { + this.removeAttribute( key ); + }, + show: function(){ + this.style.display = this.oldblock ? this.oldblock : ""; + if ( jQuery.css(this,"display") == "none" ) + this.style.display = "block"; + }, + hide: function(){ + this.oldblock = this.oldblock || jQuery.css(this,"display"); + if ( this.oldblock == "none" ) + this.oldblock = "block"; + this.style.display = "none"; + }, + toggle: function(){ + $(this)[ $(this).is(":hidden") ? "show" : "hide" ].apply( $(this), arguments ); + }, + addClass: function(c){ + jQuery.className.add(this,c); + }, + removeClass: function(c){ + jQuery.className.remove(this,c); + }, + toggleClass: function( c ){ + jQuery.className[ jQuery.className.has(this,c) ? "remove" : "add" ](this,c); + }, + + remove: function(a){ + if ( !a || jQuery.filter( a, [this] ).r ) + this.parentNode.removeChild( this ); + }, + empty: function(){ + while ( this.firstChild ) + this.removeChild( this.firstChild ); + }, + bind: function( type, fn ) { + if ( fn.constructor == String ) + fn = new Function("e", ( !fn.indexOf(".") ? "$(this)" : "return " ) + fn); + jQuery.event.add( this, type, fn ); + }, + + unbind: function( type, fn ) { + jQuery.event.remove( this, type, fn ); + }, + trigger: function( type, data ) { + jQuery.event.trigger( type, data, this ); + } + } +}; + +jQuery.init(); +jQuery.fn.extend({ + + // We're overriding the old toggle function, so + // remember it for later + _toggle: jQuery.fn.toggle, + toggle: function(a,b) { + // If two functions are passed in, we're + // toggling on a click + return a && b && a.constructor == Function && b.constructor == Function ? this.click(function(e){ + // Figure out which function to execute + this.last = this.last == a ? b : a; + + // Make sure that clicks stop + e.preventDefault(); + + // and execute the function + return this.last.apply( this, [e] ) || false; + }) : + + // Otherwise, execute the old toggle function + this._toggle.apply( this, arguments ); + }, + + hover: function(f,g) { + + // A private function for haandling mouse 'hovering' + function handleHover(e) { + // Check if mouse(over|out) are still within the same parent element + var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; + + // Traverse up the tree + while ( p && p != this ) p = p.parentNode; + + // If we actually just moused on to a sub-element, ignore it + if ( p == this ) return false; + + // Execute the right function + return (e.type == "mouseover" ? f : g).apply(this, [e]); + } + + // Bind the function to the two event listeners + return this.mouseover(handleHover).mouseout(handleHover); + }, + ready: function(f) { + // If the DOM is already ready + if ( jQuery.isReady ) + // Execute the function immediately + f.apply( document ); + + // Otherwise, remember the function for later + else { + // Add the function to the wait list + jQuery.readyList.push( f ); + } + + return this; + } +}); + +jQuery.extend({ + /* + * All the code that makes DOM Ready work nicely. + */ + isReady: false, + readyList: [], + + // Handle when the DOM is ready + ready: function() { + // Make sure that the DOM is not already loaded + if ( !jQuery.isReady ) { + // Remember that the DOM is ready + jQuery.isReady = true; + + // If there are functions bound, to execute + if ( jQuery.readyList ) { + // Execute all of them + for ( var i = 0; i < jQuery.readyList.length; i++ ) + jQuery.readyList[i].apply( document ); + + // Reset the list of functions + jQuery.readyList = null; + } + } + } +}); + +new function(){ + + var e = ("blur,focus,load,resize,scroll,unload,click,dblclick," + + "mousedown,mouseup,mousemove,mouseover,mouseout,change,reset,select," + + "submit,keydown,keypress,keyup,error").split(","); + + // Go through all the event names, but make sure that + // it is enclosed properly + for ( var i = 0; i < e.length; i++ ) new function(){ + + var o = e[i]; + + // Handle event binding + jQuery.fn[o] = function(f){ + return f ? this.bind(o, f) : this.trigger(o); + }; + + // Handle event unbinding + jQuery.fn["un"+o] = function(f){ return this.unbind(o, f); }; + + // Finally, handle events that only fire once + jQuery.fn["one"+o] = function(f){ + // Attach the event listener + return this.each(function(){ + + var count = 0; + + // Add the event + jQuery.event.add( this, o, function(e){ + // If this function has already been executed, stop + if ( count++ ) return; + + // And execute the bound function + return f.apply(this, [e]); + }); + }); + }; + + }; + + // If Mozilla is used + if ( jQuery.browser.mozilla || jQuery.browser.opera ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", jQuery.ready, false ); + + // If IE is used, use the excellent hack by Matthias Miller + // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited + } else if ( jQuery.browser.msie ) { + + // Only works if you document.write() it + document.write("<\/script>"); + + // Use the defer script hack + var script = document.getElementById("__ie_init"); + script.onreadystatechange = function() { + if ( this.readyState != "complete" ) return; + this.parentNode.removeChild( this ); + jQuery.ready(); + }; + + // Clear from memory + script = null; + + // If Safari is used + } else if ( jQuery.browser.safari ) { + // Continually check to see if the document.readyState is valid + jQuery.safariTimer = setInterval(function(){ + // loaded and complete are both valid states + if ( document.readyState == "loaded" || + document.readyState == "complete" ) { + + // If either one are found, remove the timer + clearInterval( jQuery.safariTimer ); + jQuery.safariTimer = null; + + // and execute any waiting functions + jQuery.ready(); + } + }, 10); + } + + // A fallback to window.onload, that will always work + jQuery.event.add( window, "load", jQuery.ready ); + +}; +jQuery.fn.extend({ + + // overwrite the old show method + _show: jQuery.fn.show, + + show: function(speed,callback){ + return speed ? this.animate({ + height: "show", width: "show", opacity: "show" + }, speed, callback) : this._show(); + }, + + // Overwrite the old hide method + _hide: jQuery.fn.hide, + + hide: function(speed,callback){ + return speed ? this.animate({ + height: "hide", width: "hide", opacity: "hide" + }, speed, callback) : this._hide(); + }, + + slideDown: function(speed,callback){ + return this.animate({height: "show"}, speed, callback); + }, + + slideUp: function(speed,callback){ + return this.animate({height: "hide"}, speed, callback); + }, + + slideToggle: function(speed,callback){ + return this.each(function(){ + var state = $(this).is(":hidden") ? "show" : "hide"; + $(this).animate({height: state}, speed, callback); + }); + }, + + fadeIn: function(speed,callback){ + return this.animate({opacity: "show"}, speed, callback); + }, + + fadeOut: function(speed,callback){ + return this.animate({opacity: "hide"}, speed, callback); + }, + + fadeTo: function(speed,to,callback){ + return this.animate({opacity: to}, speed, callback); + }, + animate: function(prop,speed,callback) { + return this.queue(function(){ + + this.curAnim = prop; + + for ( var p in prop ) { + var e = new jQuery.fx( this, jQuery.speed(speed,callback), p ); + if ( prop[p].constructor == Number ) + e.custom( e.cur(), prop[p] ); + else + e[ prop[p] ]( prop ); + } + + }); + }, + queue: function(type,fn){ + if ( !fn ) { + fn = type; + type = "fx"; + } + + return this.each(function(){ + if ( !this.queue ) + this.queue = {}; + + if ( !this.queue[type] ) + this.queue[type] = []; + + this.queue[type].push( fn ); + + if ( this.queue[type].length == 1 ) + fn.apply(this); + }); + } + +}); + +jQuery.extend({ + + setAuto: function(e,p) { + if ( e.notAuto ) return; + + if ( p == "height" && e.scrollHeight != parseInt(jQuery.curCSS(e,p)) ) return; + if ( p == "width" && e.scrollWidth != parseInt(jQuery.curCSS(e,p)) ) return; + + // Remember the original height + var a = e.style[p]; + + // Figure out the size of the height right now + var o = jQuery.curCSS(e,p,1); + + if ( p == "height" && e.scrollHeight != o || + p == "width" && e.scrollWidth != o ) return; + + // Set the height to auto + e.style[p] = e.currentStyle ? "" : "auto"; + + // See what the size of "auto" is + var n = jQuery.curCSS(e,p,1); + + // Revert back to the original size + if ( o != n && n != "auto" ) { + e.style[p] = a; + e.notAuto = true; + } + }, + + speed: function(s,o) { + o = o || {}; + + if ( o.constructor == Function ) + o = { complete: o }; + + var ss = { slow: 600, fast: 200 }; + o.duration = (s && s.constructor == Number ? s : ss[s]) || 400; + + // Queueing + o.oldComplete = o.complete; + o.complete = function(){ + jQuery.dequeue(this, "fx"); + if ( o.oldComplete && o.oldComplete.constructor == Function ) + o.oldComplete.apply( this ); + }; + + return o; + }, + + queue: {}, + + dequeue: function(elem,type){ + type = type || "fx"; + + if ( elem.queue && elem.queue[type] ) { + // Remove self + elem.queue[type].shift(); + + // Get next function + var f = elem.queue[type][0]; + + if ( f ) f.apply( elem ); + } + }, + + /* + * I originally wrote fx() as a clone of moo.fx and in the process + * of making it small in size the code became illegible to sane + * people. You've been warned. + */ + + fx: function( elem, options, prop ){ + + var z = this; + + // The users options + z.o = { + duration: options.duration || 400, + complete: options.complete, + step: options.step + }; + + // The element + z.el = elem; + + // The styles + var y = z.el.style; + + // Simple function for setting a style value + z.a = function(){ + if ( options.step ) + options.step.apply( elem, [ z.now ] ); + + if ( prop == "opacity" ) { + if (jQuery.browser.mozilla && z.now == 1) z.now = 0.9999; + if (window.ActiveXObject) + y.filter = "alpha(opacity=" + z.now*100 + ")"; + else + y.opacity = z.now; + + // My hate for IE will never die + } else if ( parseInt(z.now) ) + y[prop] = parseInt(z.now) + "px"; + + y.display = "block"; + }; + + // Figure out the maximum number to run to + z.max = function(){ + return parseFloat( jQuery.css(z.el,prop) ); + }; + + // Get the current size + z.cur = function(){ + var r = parseFloat( jQuery.curCSS(z.el, prop) ); + return r && r > -10000 ? r : z.max(); + }; + + // Start an animation from one number to another + z.custom = function(from,to){ + z.startTime = (new Date()).getTime(); + z.now = from; + z.a(); + + z.timer = setInterval(function(){ + z.step(from, to); + }, 13); + }; + + // Simple 'show' function + z.show = function( p ){ + if ( !z.el.orig ) z.el.orig = {}; + + // Remember where we started, so that we can go back to it later + z.el.orig[prop] = this.cur(); + + z.custom( 0, z.el.orig[prop] ); + + // Stupid IE, look what you made me do + if ( prop != "opacity" ) + y[prop] = "1px"; + }; + + // Simple 'hide' function + z.hide = function(){ + if ( !z.el.orig ) z.el.orig = {}; + + // Remember where we started, so that we can go back to it later + z.el.orig[prop] = this.cur(); + + z.o.hide = true; + + // Begin the animation + z.custom(z.el.orig[prop], 0); + }; + + // IE has trouble with opacity if it does not have layout + if ( jQuery.browser.msie && !z.el.currentStyle.hasLayout ) + y.zoom = "1"; + + // Remember the overflow of the element + if ( !z.el.oldOverlay ) + z.el.oldOverflow = jQuery.css( z.el, "overflow" ); + + // Make sure that nothing sneaks out + y.overflow = "hidden"; + + // Each step of an animation + z.step = function(firstNum, lastNum){ + var t = (new Date()).getTime(); + + if (t > z.o.duration + z.startTime) { + // Stop the timer + clearInterval(z.timer); + z.timer = null; + + z.now = lastNum; + z.a(); + + z.el.curAnim[ prop ] = true; + + var done = true; + for ( var i in z.el.curAnim ) + if ( z.el.curAnim[i] !== true ) + done = false; + + if ( done ) { + // Reset the overflow + y.overflow = z.el.oldOverflow; + + // Hide the element if the "hide" operation was done + if ( z.o.hide ) + y.display = 'none'; + + // Reset the property, if the item has been hidden + if ( z.o.hide ) { + for ( var p in z.el.curAnim ) { + y[ p ] = z.el.orig[p] + ( p == "opacity" ? "" : "px" ); + + // set its height and/or width to auto + if ( p == 'height' || p == 'width' ) + jQuery.setAuto( z.el, p ); + } + } + } + + // If a callback was provided, execute it + if( done && z.o.complete && z.o.complete.constructor == Function ) + // Execute the complete function + z.o.complete.apply( z.el ); + } else { + // Figure out where in the animation we are and set the number + var p = (t - this.startTime) / z.o.duration; + z.now = ((-Math.cos(p*Math.PI)/2) + 0.5) * (lastNum-firstNum) + firstNum; + + // Perform the next step of the animation + z.a(); + } + }; + + } + +}); +// AJAX Plugin +// Docs Here: +// http://jquery.com/docs/ajax/ +jQuery.fn.loadIfModified = function( url, params, callback ) { + this.load( url, params, callback, 1 ); +}; + +jQuery.fn.load = function( url, params, callback, ifModified ) { + if ( url.constructor == Function ) + return this.bind("load", url); + + callback = callback || function(){}; + + // Default to a GET request + var type = "GET"; + + // If the second parameter was provided + if ( params ) { + // If it's a function + if ( params.constructor == Function ) { + // We assume that it's the callback + callback = params; + params = null; + + // Otherwise, build a param string + } else { + params = jQuery.param( params ); + type = "POST"; + } + } + + var self = this; + + // Request the remote document + jQuery.ajax( type, url, params,function(res, status){ + + if ( status == "success" || !ifModified && status == "notmodified" ) { + // Inject the HTML into all the matched elements + self.html(res.responseText).each( callback, [res.responseText, status] ); + + // Execute all the scripts inside of the newly-injected HTML + $("script", self).each(function(){ + if ( this.src ) + $.getScript( this.src ); + else + eval.call( window, this.text || this.textContent || this.innerHTML || "" ); + }); + } else + callback.apply( self, [res.responseText, status] ); + + }, ifModified); + + return this; +}; + +// If IE is used, create a wrapper for the XMLHttpRequest object +if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" ) + XMLHttpRequest = function(){ + return new ActiveXObject( + navigator.userAgent.indexOf("MSIE 5") >= 0 ? + "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP" + ); + }; + +// Attach a bunch of functions for handling common AJAX events +new function(){ + var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(','); + + for ( var i = 0; i < e.length; i++ ) new function(){ + var o = e[i]; + jQuery.fn[o] = function(f){ + return this.bind(o, f); + }; + }; +}; + +jQuery.extend({ + get: function( url, data, callback, type, ifModified ) { + if ( data.constructor == Function ) { + type = callback; + callback = data; + data = null; + } + + if ( data ) url += "?" + jQuery.param(data); + + // Build and start the HTTP Request + jQuery.ajax( "GET", url, null, function(r, status) { + if ( callback ) callback( jQuery.httpData(r,type), status ); + }, ifModified); + }, + + getIfModified: function( url, data, callback, type ) { + jQuery.get(url, data, callback, type, 1); + }, + + getScript: function( url, data, callback ) { + jQuery.get(url, data, callback, "script"); + }, + post: function( url, data, callback, type ) { + // Build and start the HTTP Request + jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) { + if ( callback ) callback( jQuery.httpData(r,type), status ); + }); + }, + + // timeout (ms) + timeout: 0, + + ajaxTimeout: function(timeout) { + jQuery.timeout = timeout; + }, + + // Last-Modified header cache for next request + lastModified: {}, + ajax: function( type, url, data, ret, ifModified ) { + // If only a single argument was passed in, + // assume that it is a object of key/value pairs + if ( !url ) { + ret = type.complete; + var success = type.success; + var error = type.error; + data = type.data; + url = type.url; + type = type.type; + } + + // Watch for a new set of requests + if ( ! jQuery.active++ ) + jQuery.event.trigger( "ajaxStart" ); + + var requestDone = false; + + // Create the request object + var xml = new XMLHttpRequest(); + + // Open the socket + xml.open(type || "GET", url, true); + + // Set the correct header, if data is being sent + if ( data ) + xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + + // Set the If-Modified-Since header, if ifModified mode. + if ( ifModified ) + xml.setRequestHeader("If-Modified-Since", + jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" ); + + // Set header so calling script knows that it's an XMLHttpRequest + xml.setRequestHeader("X-Requested-With", "XMLHttpRequest"); + + // Make sure the browser sends the right content length + if ( xml.overrideMimeType ) + xml.setRequestHeader("Connection", "close"); + + // Wait for a response to come back + var onreadystatechange = function(istimeout){ + // The transfer is complete and the data is available, or the request timed out + if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) { + requestDone = true; + + var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ? + ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error"; + + // Make sure that the request was successful or notmodified + if ( status != "error" ) { + // Cache Last-Modified header, if ifModified mode. + var modRes = xml.getResponseHeader("Last-Modified"); + if ( ifModified && modRes ) jQuery.lastModified[url] = modRes; + + // If a local callback was specified, fire it + if ( success ) success( xml, status ); + + // Fire the global callback + jQuery.event.trigger( "ajaxSuccess" ); + + // Otherwise, the request was not successful + } else { + // If a local callback was specified, fire it + if ( error ) error( xml, status ); + + // Fire the global callback + jQuery.event.trigger( "ajaxError" ); + } + + // The request was completed + jQuery.event.trigger( "ajaxComplete" ); + + // Handle the global AJAX counter + if ( ! --jQuery.active ) + jQuery.event.trigger( "ajaxStop" ); + + // Process result + if ( ret ) ret(xml, status); + + // Stop memory leaks + xml.onreadystatechange = function(){}; + xml = null; + + } + }; + xml.onreadystatechange = onreadystatechange; + + // Timeout checker + if(jQuery.timeout > 0) + setTimeout(function(){ + // Check to see if the request is still happening + if (xml) { + // Cancel the request + xml.abort(); + + if ( !requestDone ) onreadystatechange( "timeout" ); + + // Clear from memory + xml = null; + } + }, jQuery.timeout); + + // Send the data + xml.send(data); + }, + + // Counter for holding the number of active queries + active: 0, + + // Determines if an XMLHttpRequest was successful or not + httpSuccess: function(r) { + try { + return !r.status && location.protocol == "file:" || + ( r.status >= 200 && r.status < 300 ) || r.status == 304 || + jQuery.browser.safari && r.status == undefined; + } catch(e){} + + return false; + }, + + // Determines if an XMLHttpRequest returns NotModified + httpNotModified: function(xml, url) { + try { + var xmlRes = xml.getResponseHeader("Last-Modified"); + + // Firefox always returns 200. check Last-Modified date + return xml.status == 304 || xmlRes == jQuery.lastModified[url] || + jQuery.browser.safari && xml.status == undefined; + } catch(e){} + + return false; + }, + + // Get the data out of an XMLHttpRequest. + // Return parsed XML if content-type header is "xml" and type is "xml" or omitted, + // otherwise return plain text. + httpData: function(r,type) { + var ct = r.getResponseHeader("content-type"); + var data = !type && ct && ct.indexOf("xml") >= 0; + data = type == "xml" || data ? r.responseXML : r.responseText; + + // If the type is "script", eval it + if ( type == "script" ) eval.call( window, data ); + + // Get the JavaScript object, if JSON is used. + if ( type == "json" ) eval( "data = " + data ); + + return data; + }, + + // Serialize an array of form elements or a set of + // key/values into a query string + param: function(a) { + var s = []; + + // If an array was passed in, assume that it is an array + // of form elements + if ( a.constructor == Array ) { + // Serialize the form elements + for ( var i = 0; i < a.length; i++ ) + s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) ); + + // Otherwise, assume that it's an object of key/value pairs + } else { + // Serialize the key/values + for ( var j in a ) + s.push( j + "=" + encodeURIComponent( a[j] ) ); + } + + // Return the resulting serialization + return s.join("&"); + } + +}); diff --git a/libjs/jquery-1.3.2.min.js b/libjs/jquery-1.3.2.min.js new file mode 100755 index 0000000..b1ae21d --- /dev/null +++ b/libjs/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/libjs/jquery.autoScroller.js b/libjs/jquery.autoScroller.js new file mode 100644 index 0000000..5589604 --- /dev/null +++ b/libjs/jquery.autoScroller.js @@ -0,0 +1,43 @@ +function autoScroller(contentDiv, speed) +{ + contentDiv = "#"+contentDiv; + var scrollSpeed = (speed==null) ? 5 : parseInt(speed); + + // double make sure the autoScroller-container has the correct css position and overflow property + $(contentDiv).parent().css({position:'relative',overflow:'hidden'}); + + // set contentDiv style + $(contentDiv).css({position:'absolute',top:0}); + // get contentDiv height + contentDivHeight = $(contentDiv).height(); + + // call periodical + $(contentDiv).everyTime(100, function(i){ + if (parseInt($(this).css('top'))>(contentDivHeight*(-1)+8)) + { + // move scroller upwards + offset = parseInt($(this).css('top'))-scrollSpeed+"px"; + $(this).css({'top':offset}); + } + // reset to original position + else + { + // reset to original position + offset = parseInt($(this).parent().height())+8+"px"; + $(this).css({'top':offset}); + } + }); + + // on mouse over event, pause the scroller + $(contentDiv).mouseover(function () + { + speed = scrollSpeed; + scrollSpeed = 0; + }); + + // on mouse out event, start the scroller + $(contentDiv).mouseout(function () + { + scrollSpeed = speed; + }); +} \ No newline at end of file diff --git a/libjs/jquery.cycle.all.min.js b/libjs/jquery.cycle.all.min.js new file mode 100755 index 0000000..f24a74d --- /dev/null +++ b/libjs/jquery.cycle.all.min.js @@ -0,0 +1,27 @@ +/* + * jQuery Cycle Plugin (with Transition Definitions) + * Examples and documentation at: http://jquery.malsup.com/cycle/ + * Copyright (c) 2007-2009 M. Alsup + * Version: 2.72 (09-SEP-2009) + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * Requires: jQuery v1.2.6 or later + * + * Originally based on the work of: + * 1) Matt Oakes + * 2) Torsten Baldes (http://medienfreunde.com/lab/innerfade/) + * 3) Benjamin Sterling (http://www.benjaminsterling.com/experiments/jqShuffle/) + */ +(function($){var ver="2.72";if($.support==undefined){$.support={opacity:!($.browser.msie)};}function debug(s){if($.fn.cycle.debug){log(s);}}function log(){if(window.console&&window.console.log){window.console.log("[cycle] "+Array.prototype.join.call(arguments," "));}}$.fn.cycle=function(options,arg2){var o={s:this.selector,c:this.context};if(this.length===0&&options!="stop"){if(!$.isReady&&o.s){log("DOM not ready, queuing slideshow");$(function(){$(o.s,o.c).cycle(options,arg2);});return this;}log("terminating; zero elements found by selector"+($.isReady?"":" (DOM not ready)"));return this;}return this.each(function(){var opts=handleArguments(this,options,arg2);if(opts===false){return;}if(this.cycleTimeout){clearTimeout(this.cycleTimeout);}this.cycleTimeout=this.cyclePause=0;var $cont=$(this);var $slides=opts.slideExpr?$(opts.slideExpr,this):$cont.children();var els=$slides.get();if(els.length<2){log("terminating; too few slides: "+els.length);return;}var opts2=buildOptions($cont,$slides,els,opts,o);if(opts2===false){return;}var startTime=opts2.continuous?10:getTimeout(opts2.currSlide,opts2.nextSlide,opts2,!opts2.rev);if(startTime){startTime+=(opts2.delay||0);if(startTime<10){startTime=10;}debug("first timeout: "+startTime);this.cycleTimeout=setTimeout(function(){go(els,opts2,0,!opts2.rev);},startTime);}});};function handleArguments(cont,options,arg2){if(cont.cycleStop==undefined){cont.cycleStop=0;}if(options===undefined||options===null){options={};}if(options.constructor==String){switch(options){case"stop":cont.cycleStop++;if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);}cont.cycleTimeout=0;$(cont).removeData("cycle.opts");return false;case"pause":cont.cyclePause=1;return false;case"resume":cont.cyclePause=0;if(arg2===true){options=$(cont).data("cycle.opts");if(!options){log("options not found, can not resume");return false;}if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);cont.cycleTimeout=0;}go(options.elements,options,1,1);}return false;case"prev":case"next":var opts=$(cont).data("cycle.opts");if(!opts){log('options not found, "prev/next" ignored');return false;}$.fn.cycle[options](opts);return false;default:options={fx:options};}return options;}else{if(options.constructor==Number){var num=options;options=$(cont).data("cycle.opts");if(!options){log("options not found, can not advance slide");return false;}if(num<0||num>=options.elements.length){log("invalid slide index: "+num);return false;}options.nextSlide=num;if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);cont.cycleTimeout=0;}if(typeof arg2=="string"){options.oneTimeFx=arg2;}go(options.elements,options,1,num>=options.currSlide);return false;}}return options;}function removeFilter(el,opts){if(!$.support.opacity&&opts.cleartype&&el.style.filter){try{el.style.removeAttribute("filter");}catch(smother){}}}function buildOptions($cont,$slides,els,options,o){var opts=$.extend({},$.fn.cycle.defaults,options||{},$.metadata?$cont.metadata():$.meta?$cont.data():{});if(opts.autostop){opts.countdown=opts.autostopCount||els.length;}var cont=$cont[0];$cont.data("cycle.opts",opts);opts.$cont=$cont;opts.stopCount=cont.cycleStop;opts.elements=els;opts.before=opts.before?[opts.before]:[];opts.after=opts.after?[opts.after]:[];opts.after.unshift(function(){opts.busy=0;});if(!$.support.opacity&&opts.cleartype){opts.after.push(function(){removeFilter(this,opts);});}if(opts.continuous){opts.after.push(function(){go(els,opts,0,!opts.rev);});}saveOriginalOpts(opts);if(!$.support.opacity&&opts.cleartype&&!opts.cleartypeNoBg){clearTypeFix($slides);}if($cont.css("position")=="static"){$cont.css("position","relative");}if(opts.width){$cont.width(opts.width);}if(opts.height&&opts.height!="auto"){$cont.height(opts.height);}if(opts.startingSlide){opts.startingSlide=parseInt(opts.startingSlide);}if(opts.random){opts.randomMap=[];for(var i=0;i=els.length){opts.startingSlide=0;}}opts.currSlide=opts.startingSlide=opts.startingSlide||0;var first=opts.startingSlide;$slides.css({position:"absolute",top:0,left:0}).hide().each(function(i){var z=first?i>=first?els.length-(i-first):first-i:els.length-i;$(this).css("z-index",z);});$(els[first]).css("opacity",1).show();removeFilter(els[first],opts);if(opts.fit&&opts.width){$slides.width(opts.width);}if(opts.fit&&opts.height&&opts.height!="auto"){$slides.height(opts.height);}var reshape=opts.containerResize&&!$cont.innerHeight();if(reshape){var maxw=0,maxh=0;for(var j=0;jmaxw?w:maxw;maxh=h>maxh?h:maxh;}if(maxw>0&&maxh>0){$cont.css({width:maxw+"px",height:maxh+"px"});}}if(opts.pause){$cont.hover(function(){this.cyclePause++;},function(){this.cyclePause--;});}if(supportMultiTransitions(opts)===false){return false;}var requeue=false;options.requeueAttempts=options.requeueAttempts||0;$slides.each(function(){var $el=$(this);this.cycleH=(opts.fit&&opts.height)?opts.height:$el.height();this.cycleW=(opts.fit&&opts.width)?opts.width:$el.width();if($el.is("img")){var loadingIE=($.browser.msie&&this.cycleW==28&&this.cycleH==30&&!this.complete);var loadingFF=($.browser.mozilla&&this.cycleW==34&&this.cycleH==19&&!this.complete);var loadingOp=($.browser.opera&&((this.cycleW==42&&this.cycleH==19)||(this.cycleW==37&&this.cycleH==17))&&!this.complete);var loadingOther=(this.cycleH==0&&this.cycleW==0&&!this.complete);if(loadingIE||loadingFF||loadingOp||loadingOther){if(o.s&&opts.requeueOnImageNotLoaded&&++options.requeueAttempts<100){log(options.requeueAttempts," - img slide not loaded, requeuing slideshow: ",this.src,this.cycleW,this.cycleH);setTimeout(function(){$(o.s,o.c).cycle(options);},opts.requeueTimeout);requeue=true;return false;}else{log("could not determine size of image: "+this.src,this.cycleW,this.cycleH);}}}return true;});if(requeue){return false;}opts.cssBefore=opts.cssBefore||{};opts.animIn=opts.animIn||{};opts.animOut=opts.animOut||{};$slides.not(":eq("+first+")").css(opts.cssBefore);if(opts.cssFirst){$($slides[first]).css(opts.cssFirst);}if(opts.timeout){opts.timeout=parseInt(opts.timeout);if(opts.speed.constructor==String){opts.speed=$.fx.speeds[opts.speed]||parseInt(opts.speed);}if(!opts.sync){opts.speed=opts.speed/2;}while((opts.timeout-opts.speed)<250){opts.timeout+=opts.speed;}}if(opts.easing){opts.easeIn=opts.easeOut=opts.easing;}if(!opts.speedIn){opts.speedIn=opts.speed;}if(!opts.speedOut){opts.speedOut=opts.speed;}opts.slideCount=els.length;opts.currSlide=opts.lastSlide=first;if(opts.random){opts.nextSlide=opts.currSlide;if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{opts.nextSlide=opts.startingSlide>=(els.length-1)?0:opts.startingSlide+1;}if(!opts.multiFx){var init=$.fn.cycle.transitions[opts.fx];if($.isFunction(init)){init($cont,$slides,opts);}else{if(opts.fx!="custom"&&!opts.multiFx){log("unknown transition: "+opts.fx,"; slideshow terminating");return false;}}}var e0=$slides[first];if(opts.before.length){opts.before[0].apply(e0,[e0,e0,opts,true]);}if(opts.after.length>1){opts.after[1].apply(e0,[e0,e0,opts,true]);}if(opts.next){$(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,opts.rev?-1:1);});}if(opts.prev){$(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,opts.rev?1:-1);});}if(opts.pager){buildPager(els,opts);}exposeAddSlide(opts,els);return opts;}function saveOriginalOpts(opts){opts.original={before:[],after:[]};opts.original.cssBefore=$.extend({},opts.cssBefore);opts.original.cssAfter=$.extend({},opts.cssAfter);opts.original.animIn=$.extend({},opts.animIn);opts.original.animOut=$.extend({},opts.animOut);$.each(opts.before,function(){opts.original.before.push(this);});$.each(opts.after,function(){opts.original.after.push(this);});}function supportMultiTransitions(opts){var i,tx,txs=$.fn.cycle.transitions;if(opts.fx.indexOf(",")>0){opts.multiFx=true;opts.fxs=opts.fx.replace(/\s*/g,"").split(",");for(i=0;i=opts.fxs.length){opts.lastFx=0;}fx=opts.fxs[opts.lastFx];opts.currFx=fx;}if(opts.oneTimeFx){fx=opts.oneTimeFx;opts.oneTimeFx=null;}$.fn.cycle.resetState(opts,fx);if(opts.before.length){$.each(opts.before,function(i,o){if(p.cycleStop!=opts.stopCount){return;}o.apply(next,[curr,next,opts,fwd]);});}var after=function(){$.each(opts.after,function(i,o){if(p.cycleStop!=opts.stopCount){return;}o.apply(next,[curr,next,opts,fwd]);});};if(opts.nextSlide!=opts.currSlide){opts.busy=1;if(opts.fxFn){opts.fxFn(curr,next,opts,after,fwd);}else{if($.isFunction($.fn.cycle[opts.fx])){$.fn.cycle[opts.fx](curr,next,opts,after);}else{$.fn.cycle.custom(curr,next,opts,after,manual&&opts.fastOnEvent);}}}opts.lastSlide=opts.currSlide;if(opts.random){opts.currSlide=opts.nextSlide;if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{var roll=(opts.nextSlide+1)==els.length;opts.nextSlide=roll?0:opts.nextSlide+1;opts.currSlide=roll?els.length-1:opts.nextSlide-1;}if(opts.pager){$.fn.cycle.updateActivePagerLink(opts.pager,opts.currSlide);}}var ms=0;if(opts.timeout&&!opts.continuous){ms=getTimeout(curr,next,opts,fwd);}else{if(opts.continuous&&p.cyclePause){ms=10;}}if(ms>0){p.cycleTimeout=setTimeout(function(){go(els,opts,0,!opts.rev);},ms);}}$.fn.cycle.updateActivePagerLink=function(pager,currSlide){$(pager).find("a").removeClass("activeSlide").filter("a:eq("+currSlide+")").addClass("activeSlide");};function getTimeout(curr,next,opts,fwd){if(opts.timeoutFn){var t=opts.timeoutFn(curr,next,opts,fwd);while((t-opts.speed)<250){t+=opts.speed;}debug("calculated timeout: "+t+"; speed: "+opts.speed);if(t!==false){return t;}}return opts.timeout;}$.fn.cycle.next=function(opts){advance(opts,opts.rev?-1:1);};$.fn.cycle.prev=function(opts){advance(opts,opts.rev?1:-1);};function advance(opts,val){var els=opts.elements;var p=opts.$cont[0],timeout=p.cycleTimeout;if(timeout){clearTimeout(timeout);p.cycleTimeout=0;}if(opts.random&&val<0){opts.randomIndex--;if(--opts.randomIndex==-2){opts.randomIndex=els.length-2;}else{if(opts.randomIndex==-1){opts.randomIndex=els.length-1;}}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{if(opts.random){if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{opts.nextSlide=opts.currSlide+val;if(opts.nextSlide<0){if(opts.nowrap){return false;}opts.nextSlide=els.length-1;}else{if(opts.nextSlide>=els.length){if(opts.nowrap){return false;}opts.nextSlide=0;}}}}if($.isFunction(opts.prevNextClick)){opts.prevNextClick(val>0,opts.nextSlide,els[opts.nextSlide]);}go(els,opts,1,val>=0);return false;}function buildPager(els,opts){var $p=$(opts.pager);$.each(els,function(i,o){$.fn.cycle.createPagerAnchor(i,o,$p,els,opts);});$.fn.cycle.updateActivePagerLink(opts.pager,opts.startingSlide);}$.fn.cycle.createPagerAnchor=function(i,el,$p,els,opts){var a;if($.isFunction(opts.pagerAnchorBuilder)){a=opts.pagerAnchorBuilder(i,el);}else{a=''+(i+1)+"";}if(!a){return;}var $a=$(a);if($a.parents("body").length===0){var arr=[];if($p.length>1){$p.each(function(){var $clone=$a.clone(true);$(this).append($clone);arr.push($clone);});$a=$(arr);}else{$a.appendTo($p);}}$a.bind(opts.pagerEvent,function(e){e.preventDefault();opts.nextSlide=i;var p=opts.$cont[0],timeout=p.cycleTimeout;if(timeout){clearTimeout(timeout);p.cycleTimeout=0;}if($.isFunction(opts.pagerClick)){opts.pagerClick(opts.nextSlide,els[opts.nextSlide]);}go(els,opts,1,opts.currSlidel?c-l:opts.slideCount-l;}else{hops=c=0){var rgb=v.match(/\d+/g);return"#"+hex(rgb[0])+hex(rgb[1])+hex(rgb[2]);}if(v&&v!="transparent"){return v;}}return"#ffffff";}$slides.each(function(){$(this).css("background-color",getBg(this));});}$.fn.cycle.commonReset=function(curr,next,opts,w,h,rev){$(opts.elements).not(curr).hide();opts.cssBefore.opacity=1;opts.cssBefore.display="block";if(w!==false&&next.cycleW>0){opts.cssBefore.width=next.cycleW;}if(h!==false&&next.cycleH>0){opts.cssBefore.height=next.cycleH;}opts.cssAfter=opts.cssAfter||{};opts.cssAfter.display="none";$(curr).css("zIndex",opts.slideCount+(rev===true?1:0));$(next).css("zIndex",opts.slideCount+(rev===true?0:1));};$.fn.cycle.custom=function(curr,next,opts,cb,speedOverride){var $l=$(curr),$n=$(next);var speedIn=opts.speedIn,speedOut=opts.speedOut,easeIn=opts.easeIn,easeOut=opts.easeOut;$n.css(opts.cssBefore);if(speedOverride){if(typeof speedOverride=="number"){speedIn=speedOut=speedOverride;}else{speedIn=speedOut=1;}easeIn=easeOut=null;}var fn=function(){$n.animate(opts.animIn,speedIn,easeIn,cb);};$l.animate(opts.animOut,speedOut,easeOut,function(){if(opts.cssAfter){$l.css(opts.cssAfter);}if(!opts.sync){fn();}});if(opts.sync){fn();}};$.fn.cycle.transitions={fade:function($cont,$slides,opts){$slides.not(":eq("+opts.currSlide+")").css("opacity",0);opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts);opts.cssBefore.opacity=0;});opts.animIn={opacity:1};opts.animOut={opacity:0};opts.cssBefore={top:0,left:0};}};$.fn.cycle.ver=function(){return ver;};$.fn.cycle.defaults={fx:"fade",timeout:4000,timeoutFn:null,continuous:0,speed:1000,speedIn:null,speedOut:null,next:null,prev:null,prevNextClick:null,prevNextEvent:"click",pager:null,pagerClick:null,pagerEvent:"click",pagerAnchorBuilder:null,before:null,after:null,end:null,easing:null,easeIn:null,easeOut:null,shuffle:null,animIn:null,animOut:null,cssBefore:null,cssAfter:null,fxFn:null,height:"auto",startingSlide:0,sync:1,random:0,fit:0,containerResize:1,pause:0,pauseOnPagerHover:0,autostop:0,autostopCount:0,delay:0,slideExpr:null,cleartype:!$.support.opacity,cleartypeNoBg:false,nowrap:0,fastOnEvent:0,randomizeEffects:1,rev:0,manualTrump:true,requeueOnImageNotLoaded:true,requeueTimeout:250};})(jQuery); +/* + * jQuery Cycle Plugin Transition Definitions + * This script is a plugin for the jQuery Cycle Plugin + * Examples and documentation at: http://malsup.com/jquery/cycle/ + * Copyright (c) 2007-2008 M. Alsup + * Version: 2.72 + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + */ +(function($){$.fn.cycle.transitions.none=function($cont,$slides,opts){opts.fxFn=function(curr,next,opts,after){$(next).show();$(curr).hide();after();};};$.fn.cycle.transitions.scrollUp=function($cont,$slides,opts){$cont.css("overflow","hidden");opts.before.push($.fn.cycle.commonReset);var h=$cont.height();opts.cssBefore={top:h,left:0};opts.cssFirst={top:0};opts.animIn={top:0};opts.animOut={top:-h};};$.fn.cycle.transitions.scrollDown=function($cont,$slides,opts){$cont.css("overflow","hidden");opts.before.push($.fn.cycle.commonReset);var h=$cont.height();opts.cssFirst={top:0};opts.cssBefore={top:-h,left:0};opts.animIn={top:0};opts.animOut={top:h};};$.fn.cycle.transitions.scrollLeft=function($cont,$slides,opts){$cont.css("overflow","hidden");opts.before.push($.fn.cycle.commonReset);var w=$cont.width();opts.cssFirst={left:0};opts.cssBefore={left:w,top:0};opts.animIn={left:0};opts.animOut={left:0-w};};$.fn.cycle.transitions.scrollRight=function($cont,$slides,opts){$cont.css("overflow","hidden");opts.before.push($.fn.cycle.commonReset);var w=$cont.width();opts.cssFirst={left:0};opts.cssBefore={left:-w,top:0};opts.animIn={left:0};opts.animOut={left:w};};$.fn.cycle.transitions.scrollHorz=function($cont,$slides,opts){$cont.css("overflow","hidden").width();opts.before.push(function(curr,next,opts,fwd){$.fn.cycle.commonReset(curr,next,opts);opts.cssBefore.left=fwd?(next.cycleW-1):(1-next.cycleW);opts.animOut.left=fwd?-curr.cycleW:curr.cycleW;});opts.cssFirst={left:0};opts.cssBefore={top:0};opts.animIn={left:0};opts.animOut={top:0};};$.fn.cycle.transitions.scrollVert=function($cont,$slides,opts){$cont.css("overflow","hidden");opts.before.push(function(curr,next,opts,fwd){$.fn.cycle.commonReset(curr,next,opts);opts.cssBefore.top=fwd?(1-next.cycleH):(next.cycleH-1);opts.animOut.top=fwd?curr.cycleH:-curr.cycleH;});opts.cssFirst={top:0};opts.cssBefore={left:0};opts.animIn={top:0};opts.animOut={left:0};};$.fn.cycle.transitions.slideX=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$(opts.elements).not(curr).hide();$.fn.cycle.commonReset(curr,next,opts,false,true);opts.animIn.width=next.cycleW;});opts.cssBefore={left:0,top:0,width:0};opts.animIn={width:"show"};opts.animOut={width:0};};$.fn.cycle.transitions.slideY=function($cont,$slides,opts){opts.before.push(function(curr,next,opts){$(opts.elements).not(curr).hide();$.fn.cycle.commonReset(curr,next,opts,true,false);opts.animIn.height=next.cycleH;});opts.cssBefore={left:0,top:0,height:0};opts.animIn={height:"show"};opts.animOut={height:0};};$.fn.cycle.transitions.shuffle=function($cont,$slides,opts){var i,w=$cont.css("overflow","visible").width();$slides.css({left:0,top:0});opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts,true,true,true);});if(!opts.speedAdjusted){opts.speed=opts.speed/2;opts.speedAdjusted=true;}opts.random=0;opts.shuffle=opts.shuffle||{left:-w,top:15};opts.els=[];for(i=0;i<$slides.length;i++){opts.els.push($slides[i]);}for(i=0;i)[^>]*$|^#(\w+)$/;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(typeof selector=="string"){var m=quickExpr.exec(selector);if(m&&(m[1]||!context)){if(m[1])selector=jQuery.clean([m[1]],context);else{var tmp=document.getElementById(m[3]);if(tmp)if(tmp.id!=m[3])return jQuery().find(selector);else{this[0]=tmp;this.length=1;return this;}else +selector=[];}}else +return new jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return new jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(selector.constructor==Array&&selector||(selector.jquery||selector.length&&selector!=window&&!selector.nodeType&&selector[0]!=undefined&&selector[0].nodeType)&&jQuery.makeArray(selector)||[selector]);},jquery:"1.2.1",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(a){var ret=jQuery(a);ret.prevObject=this;return ret;},setArray:function(a){this.length=0;Array.prototype.push.apply(this,a);return this;},each:function(fn,args){return jQuery.each(this,fn,args);},index:function(obj){var pos=-1;this.each(function(i){if(this==obj)pos=i;});return pos;},attr:function(key,value,type){var obj=key;if(key.constructor==String)if(value==undefined)return this.length&&jQuery[type||"attr"](this[0],key)||undefined;else{obj={};obj[key]=value;}return this.each(function(index){for(var prop in obj)jQuery.attr(type?this.style:this,prop,jQuery.prop(this,obj[prop],type,index,prop));});},css:function(key,value){return this.attr(key,value,"curCSS");},text:function(e){if(typeof e!="object"&&e!=null)return this.empty().append(document.createTextNode(e));var t="";jQuery.each(e||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)t+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return t;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,1,function(a){this.appendChild(a);});},prepend:function(){return this.domManip(arguments,true,-1,function(a){this.insertBefore(a,this.firstChild);});},before:function(){return this.domManip(arguments,false,1,function(a){this.parentNode.insertBefore(a,this);});},after:function(){return this.domManip(arguments,false,-1,function(a){this.parentNode.insertBefore(a,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(t){var data=jQuery.map(this,function(a){return jQuery.find(t,a);});return this.pushStack(/[^+>] [^+>]/.test(t)||t.indexOf("..")>-1?jQuery.unique(data):data);},clone:function(events){var ret=this.map(function(){return this.outerHTML?jQuery(this.outerHTML)[0]:this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(t){return this.pushStack(jQuery.isFunction(t)&&jQuery.grep(this,function(el,index){return t.apply(el,[index]);})||jQuery.multiFilter(t,this));},not:function(t){return this.pushStack(t.constructor==String&&jQuery.multiFilter(t,this,true)||jQuery.grep(this,function(a){return(t.constructor==Array||t.jquery)?jQuery.inArray(a,t)<0:a!=t;}));},add:function(t){return this.pushStack(jQuery.merge(this.get(),t.constructor==String?jQuery(t).get():t.length!=undefined&&(!t.nodeName||jQuery.nodeName(t,"form"))?t:[t]));},is:function(expr){return expr?jQuery.multiFilter(expr,this).length>0:false;},hasClass:function(expr){return this.is("."+expr);},val:function(val){if(val==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,a=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i=0||jQuery.inArray(this.name,val)>=0);else if(jQuery.nodeName(this,"select")){var tmp=val.constructor==Array?val:[val];jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,tmp)>=0||jQuery.inArray(this.text,tmp)>=0);});if(!tmp.length)this.selectedIndex=-1;}else +this.value=val;});},html:function(val){return val==undefined?(this.length?this[0].innerHTML:null):this.empty().append(val);},replaceWith:function(val){return this.after(val).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(fn){return this.pushStack(jQuery.map(this,function(elem,i){return fn.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},domManip:function(args,table,dir,fn){var clone=this.length>1,a;return this.each(function(){if(!a){a=jQuery.clean(args,this.ownerDocument);if(dir<0)a.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(a[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(document.createElement("tbody"));jQuery.each(a,function(){var elem=clone?this.cloneNode(true):this;if(!evalScript(0,elem))fn.call(obj,elem);});});}};function evalScript(i,elem){var script=jQuery.nodeName(elem,"script");if(script){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else +jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}else if(elem.nodeType==1)jQuery("script",elem).each(evalScript);return script;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},a=1,al=arguments.length,deep=false;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};}if(al==1){target=this;a=0;}var prop;for(;a-1;}},swap:function(e,o,f){for(var i in o){e.style["old"+i]=e.style[i];e.style[i]=o[i];}f.apply(e,[]);for(var i in o)e.style[i]=e.style["old"+i];},css:function(e,p){if(p=="height"||p=="width"){var old={},oHeight,oWidth,d=["Top","Bottom","Right","Left"];jQuery.each(d,function(){old["padding"+this]=0;old["border"+this+"Width"]=0;});jQuery.swap(e,old,function(){if(jQuery(e).is(':visible')){oHeight=e.offsetHeight;oWidth=e.offsetWidth;}else{e=jQuery(e.cloneNode(true)).find(":radio").removeAttr("checked").end().css({visibility:"hidden",position:"absolute",display:"block",right:"0",left:"0"}).appendTo(e.parentNode)[0];var parPos=jQuery.css(e.parentNode,"position")||"static";if(parPos=="static")e.parentNode.style.position="relative";oHeight=e.clientHeight;oWidth=e.clientWidth;if(parPos=="static")e.parentNode.style.position="static";e.parentNode.removeChild(e);}});return p=="height"?oHeight:oWidth;}return jQuery.curCSS(e,p);},curCSS:function(elem,prop,force){var ret,stack=[],swap=[];function color(a){if(!jQuery.browser.safari)return false;var ret=document.defaultView.getComputedStyle(a,null);return!ret||ret.getPropertyValue("color")=="";}if(prop=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(elem.style,"opacity");return ret==""?"1":ret;}if(prop.match(/float/i))prop=styleFloat;if(!force&&elem.style[prop])ret=elem.style[prop];else if(document.defaultView&&document.defaultView.getComputedStyle){if(prop.match(/float/i))prop="float";prop=prop.replace(/([A-Z])/g,"-$1").toLowerCase();var cur=document.defaultView.getComputedStyle(elem,null);if(cur&&!color(elem))ret=cur.getPropertyValue(prop);else{for(var a=elem;a&&color(a);a=a.parentNode)stack.unshift(a);for(a=0;a]*?)\/>/g,function(m,all,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area)$/i)?m:all+">";});var s=jQuery.trim(arg).toLowerCase(),div=doc.createElement("div"),tb=[];var wrap=!s.indexOf("",""]||!s.indexOf("",""]||s.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
    "]||!s.indexOf("",""]||(!s.indexOf("",""]||!s.indexOf("",""]||jQuery.browser.msie&&[1,"div
    ","
    "]||[0,"",""];div.innerHTML=wrap[1]+arg+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){if(!s.indexOf(""&&s.indexOf("=0;--n)if(jQuery.nodeName(tb[n],"tbody")&&!tb[n].childNodes.length)tb[n].parentNode.removeChild(tb[n]);if(/^\s/.test(arg))div.insertBefore(doc.createTextNode(arg.match(/^\s*/)[0]),div.firstChild);}arg=jQuery.makeArray(div.childNodes);}if(0===arg.length&&(!jQuery.nodeName(arg,"form")&&!jQuery.nodeName(arg,"select")))return;if(arg[0]==undefined||jQuery.nodeName(arg,"form")||arg.options)r.push(arg);else +r=jQuery.merge(r,arg);});return r;},attr:function(elem,name,value){var fix=jQuery.isXMLDoc(elem)?{}:jQuery.props;if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(fix[name]){if(value!=undefined)elem[fix[name]]=value;return elem[fix[name]];}else if(jQuery.browser.msie&&name=="style")return jQuery.attr(elem.style,"cssText",value);else if(value==undefined&&jQuery.browser.msie&&jQuery.nodeName(elem,"form")&&(name=="action"||name=="method"))return elem.getAttributeNode(name).nodeValue;else if(elem.tagName){if(value!=undefined){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem.setAttribute(name,value);}if(jQuery.browser.msie&&/href|src/.test(name)&&!jQuery.isXMLDoc(elem))return elem.getAttribute(name,2);return elem.getAttribute(name);}else{if(name=="opacity"&&jQuery.browser.msie){if(value!=undefined){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseFloat(value).toString()=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100).toString():"";}name=name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();});if(value!=undefined)elem[name]=value;return elem[name];}},trim:function(t){return(t||"").replace(/^\s+|\s+$/g,"");},makeArray:function(a){var r=[];if(typeof a!="array")for(var i=0,al=a.length;i\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":"m[2]=='*'||jQuery.nodeName(a,m[2])","#":"a.getAttribute('id')==m[2]",":":{lt:"im[3]-0",nth:"m[3]-0==i",eq:"m[3]-0==i",first:"i==0",last:"i==r.length-1",even:"i%2==0",odd:"i%2","first-child":"a.parentNode.getElementsByTagName('*')[0]==a","last-child":"jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a","only-child":"!jQuery.nth(a.parentNode.lastChild,2,'previousSibling')",parent:"a.firstChild",empty:"!a.firstChild",contains:"(a.textContent||a.innerText||jQuery(a).text()||'').indexOf(m[3])>=0",visible:'"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',hidden:'"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"',enabled:"!a.disabled",disabled:"a.disabled",checked:"a.checked",selected:"a.selected||jQuery.attr(a,'selected')",text:"'text'==a.type",radio:"'radio'==a.type",checkbox:"'checkbox'==a.type",file:"'file'==a.type",password:"'password'==a.type",submit:"'submit'==a.type",image:"'image'==a.type",reset:"'reset'==a.type",button:'"button"==a.type||jQuery.nodeName(a,"button")',input:"/input|select|textarea|button/i.test(a.nodeName)",has:"jQuery.find(m[3],a).length",header:"/h\\d/i.test(a.nodeName)",animated:"jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length"}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&!context.nodeType)context=null;context=context||document;var ret=[context],done=[],last;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false;var re=quickChild;var m=re.exec(t);if(m){var nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName.toUpperCase()))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var nodeName=m[2],merge={};m=m[1];for(var j=0,rl=ret.length;j=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=jQuery.filter(m[3],r,true).r;else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(\d*)n\+?(\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"n+"+m[3]||m[3]),first=(test[1]||1)-0,last=test[2]-0;for(var i=0,rl=r.length;i<\/script>");var script=document.getElementById("__ie_init");if(script)script.onreadystatechange=function(){if(this.readyState!="complete")return;jQuery.ready();};script=null;}else if(jQuery.browser.safari)jQuery.safariTimer=setInterval(function(){if(document.readyState=="loaded"||document.readyState=="complete"){clearInterval(jQuery.safariTimer);jQuery.safariTimer=null;jQuery.ready();}},10);jQuery.event.add(window,"load",jQuery.ready);}jQuery.fn.extend({load:function(url,params,callback){if(jQuery.isFunction(url))return this.bind("load",url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("
    ").append(res.responseText.replace(//g,"")).find(selector):res.responseText);setTimeout(function(){self.each(callback,[res.responseText,status,res]);},13);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=(new Date).getTime();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null},lastModified:{},ajax:function(s){var jsonp,jsre=/=(\?|%3F)/g,status,data;s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(s.type.toLowerCase()=="get"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=s.data.replace(jsre,"="+jsonp);s.url=s.url.replace(jsre,"="+jsonp);s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&s.type.toLowerCase()=="get")s.url+=(s.url.match(/\?/)?"&":"?")+"_="+(new Date()).getTime();if(s.data&&s.type.toLowerCase()=="get"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");if(!s.url.indexOf("http")&&s.dataType=="script"){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(!jsonp&&(s.success||s.complete)){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return;}var requestDone=false;var xml=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();xml.open(s.type,s.url,s.async);if(s.data)xml.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xml.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xml.setRequestHeader("X-Requested-With","XMLHttpRequest");if(s.beforeSend)s.beforeSend(xml);if(s.global)jQuery.event.trigger("ajaxSend",[xml,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xml&&(xml.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xml)&&"error"||s.ifModified&&jQuery.httpNotModified(xml,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xml,s.dataType);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xml.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else +jQuery.handleError(s,xml,status);complete();if(s.async)xml=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xml){xml.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xml.send(s.data);}catch(e){jQuery.handleError(s,xml,null,e);}if(!s.async)onreadystatechange();return xml;function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xml,s]);}function complete(){if(s.complete)s.complete(xml,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xml,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}},handleError:function(s,xml,status,e){if(s.error)s.error(xml,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xml,s,e]);},active:0,httpSuccess:function(r){try{return!r.status&&location.protocol=="file:"||(r.status>=200&&r.status<300)||r.status==304||jQuery.browser.safari&&r.status==undefined;}catch(e){}return false;},httpNotModified:function(xml,url){try{var xmlRes=xml.getResponseHeader("Last-Modified");return xml.status==304||xmlRes==jQuery.lastModified[url]||jQuery.browser.safari&&xml.status==undefined;}catch(e){}return false;},httpData:function(r,type){var ct=r.getResponseHeader("content-type");var xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0;var data=xml?r.responseXML:r.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else +for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else +s.push(encodeURIComponent(j)+"="+encodeURIComponent(a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock?this.oldblock:"";if(jQuery.css(this,"display")=="none")this.style.display="block";}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");if(this.oldblock=="none")this.oldblock="block";this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle(fn,fn2):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var opt=jQuery.speed(speed,easing,callback);return this[opt.queue===false?"each":"queue"](function(){opt=jQuery.extend({},opt);var hidden=jQuery(this).is(":hidden"),self=this;for(var p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return jQuery.isFunction(opt.complete)&&opt.complete.apply(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else +e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.apply(this);}});},stop:function(){var timers=jQuery.timers;return this.each(function(){for(var i=0;i-10000?r:parseFloat(jQuery.css(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=(new Date()).getTime();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(){return self.step();}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timers.length==1){var timer=setInterval(function(){var timers=jQuery.timers;for(var i=0;ithis.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done&&jQuery.isFunction(this.options.complete))this.options.complete.apply(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.fx.step={scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}};jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var absolute=jQuery.css(elem,"position")=="absolute",parent=elem.parentNode,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522;if(elem.getBoundingClientRect){box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));if(msie){var border=jQuery("html").css("borderWidth");border=(border=="medium"||jQuery.boxModel&&parseInt(version)>=7)&&2||border;add(-border,-border);}}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&/^t[d|h]$/i.test(parent.tagName)||!safari2)border(offsetParent);if(safari2&&!absolute&&jQuery.css(offsetParent,"position")=="absolute")absolute=true;offsetParent=offsetParent.offsetParent;}while(parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table-row.*$/i.test(jQuery.css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&jQuery.css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if(safari2&&absolute)add(-doc.body.offsetLeft,-doc.body.offsetTop);}results={top:top,left:left};}return results;function border(elem){add(jQuery.css(elem,"borderLeftWidth"),jQuery.css(elem,"borderTopWidth"));}function add(l,t){left+=parseInt(l)||0;top+=parseInt(t)||0;}};})(); \ No newline at end of file diff --git a/libjs/jquery.json-1.2.min.js b/libjs/jquery.json-1.2.min.js new file mode 100755 index 0000000..52a6bb2 --- /dev/null +++ b/libjs/jquery.json-1.2.min.js @@ -0,0 +1,41 @@ +(function($){function toIntegersAtLease(n) +{return n<10?'0'+n:n;} +Date.prototype.toJSON=function(date) +{return this.getUTCFullYear()+'-'+ +toIntegersAtLease(this.getUTCMonth())+'-'+ +toIntegersAtLease(this.getUTCDate());};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'} +$.quoteString=function(string) +{if(escapeable.test(string)) +{return'"'+string.replace(escapeable,function(a) +{var c=meta[a];if(typeof c==='string'){return c;} +c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"'} +return'"'+string+'"';} +$.toJSON=function(o,compact) +{var type=typeof(o);if(type=="undefined") +return"undefined";else if(type=="number"||type=="boolean") +return o+"";else if(o===null) +return"null";if(type=="string") +{return $.quoteString(o);} +if(type=="object"&&typeof o.toJSON=="function") +return o.toJSON(compact);if(type!="function"&&typeof(o.length)=="number") +{var ret=[];for(var i=0;i times && times !== 0) || fn.call(element, counter) === false) + jQuery.timer.remove(element, label, fn); + this.inProgress = false; + }; + + handler.$timerID = fn.$timerID; + + if (!element.$timers[label][fn.$timerID]) + element.$timers[label][fn.$timerID] = window.setInterval(handler,interval); + + if ( !this.global[label] ) + this.global[label] = []; + this.global[label].push( element ); + + }, + remove: function(element, label, fn) { + var timers = element.$timers, ret; + + if ( timers ) { + + if (!label) { + for ( label in timers ) + this.remove(element, label, fn); + } else if ( timers[label] ) { + if ( fn ) { + if ( fn.$timerID ) { + window.clearInterval(timers[label][fn.$timerID]); + delete timers[label][fn.$timerID]; + } + } else { + for ( var fn in timers[label] ) { + window.clearInterval(timers[label][fn]); + delete timers[label][fn]; + } + } + + for ( ret in timers[label] ) break; + if ( !ret ) { + ret = null; + delete timers[label]; + } + } + + for ( ret in timers ) break; + if ( !ret ) + element.$timers = null; + } + } + } +}); + +if (jQuery.browser.msie) + jQuery(window).one("unload", function() { + var global = jQuery.timer.global; + for ( var label in global ) { + var els = global[label], i = els.length; + while ( --i ) + jQuery.timer.remove(els[i], label); + } + }); + + diff --git a/libjs/member-list-categories.js b/libjs/member-list-categories.js new file mode 100644 index 0000000..5844909 --- /dev/null +++ b/libjs/member-list-categories.js @@ -0,0 +1,29 @@ +var ListCategories = +{ + listId: 'mRow1', + treeId: 'treeDiv1', + list: null, + trunk: null, + options: [], + + init: function() + { + $$('option').each(function(o) { + ListCategories.options.push(o.innerHTML); + }); + + ListCategories.list = $(ListCategories.listId); + ListCategories.trunk = new YAHOO.widget.TreeView(ListCategories.listId) +// ListCategories.buildCategoriesTree(); + ListCategories.list.innerHTML = ''; + ListCategories.list.insert({top: ''}); +// ListCategories.trunk.draw(); +// $(ListCategories.treeId).toggle(); + }, + + buildCategoriesTree: function() + { + } +}; + +Event.observe(window, 'load', ListCategories.init); diff --git a/libjs/member-list.js b/libjs/member-list.js new file mode 100644 index 0000000..05d4697 --- /dev/null +++ b/libjs/member-list.js @@ -0,0 +1,61 @@ +var MemberList = +{ + baseUrl: null, + init: function() + { + $$('.remove').each(function(a) { + a.observe('click', MemberList.remove); + a.observe('mouseover', MemberList.click); + a.observe('mouseout', MemberList.release); + }); + + $$('.searchResult').each(function(r) { + r.observe('mouseover', MemberList.mouseOn); + r.observe('mouseout', MemberList.mouseOff); + r.observe('click', MemberList.goToMember); + }); + + MemberList.baseUrl = location.protocol + '//' + location.hostname + '/'; + + var url = location.pathname; + if (location.hostname == 'devsys2.gaslightmedia.com') { + var urlParts = url.split('/'); + MemberList.baseUrl += urlParts[1] + '/'; + } + }, + + mouseOn: function(event) + { + this.addClassName('searchResultOn'); + }, + + mouseOff: function(event) + { + this.removeClassName('searchResultOn'); + }, + + goToMember: function(event) + { + document.location.href = this.select('h3 a'); + return false; + }, + + remove: function(event) + { + if (!confirm('Are you sure you wish to remove this business?\nThis is not reversible!')) { + event.stop(); + } + }, + + click: function(event) + { + this.down().writeAttribute('src', MemberList.baseUrl + 'assets/remove_clicked.png'); + }, + + release: function(event) + { + this.down().writeAttribute('src', MemberList.baseUrl + 'assets/remove.png'); + } +}; + +Event.observe(window, 'load', MemberList.init); diff --git a/libjs/member-search.js b/libjs/member-search.js new file mode 100644 index 0000000..8219a5b --- /dev/null +++ b/libjs/member-search.js @@ -0,0 +1,38 @@ +var MemberSearch = +{ + forms: null, + showing: false, + + init: function() + { + if (MemberSearch.forms == null) { + MemberSearch.forms = $$('fieldset.form'); + MemberSearch.forms[1].toggle(); + MemberSearch.forms[0].select('tbody')[0].insert({bottom: 'Advanced Search'}); + + $('advanced-search').observe('click', MemberSearch.toggleAdvancedSearch); + } + // Find a member id in the search params, this will let us know we + // are editing a member and then we don't want to focus on the + // the first field. + var idRegExp = /.*(\?|&)id=\d+.*$/g; + if (!idRegExp.test(location.search)) { + $('search_Form').focusFirstElement(); + } + }, + + toggleAdvancedSearch: function(event) + { + if (MemberSearch.showing) { + //new Effect.Fade(MemberSearch.forms[1]); + new Effect.SlideUp(MemberSearch.forms[1]); + MemberSearch.showing = false; + } else { + //new Effect.Appear(MemberSearch.forms[1]); + new Effect.SlideDown(MemberSearch.forms[1]); + MemberSearch.showing = true; + } + } +}; + +document.observe('dom:loaded', MemberSearch.init); diff --git a/libjs/newsletterSignup.js b/libjs/newsletterSignup.js new file mode 100644 index 0000000..5ed248f --- /dev/null +++ b/libjs/newsletterSignup.js @@ -0,0 +1,49 @@ +var SignUp = +{ + originalText: null, + targetBox: null, + verifyBox: null, + + init: function() + { + SignUp.targetBox = $('#email-f'); + SignUp.verifyBox = $('#email-h'); + SignUp.originalText = SignUp.targetBox.val(); + SignUp.targetBox.parent().bind('submit', SignUp.submit); + SignUp.targetBox.bind('focus', SignUp.clear); + SignUp.targetBox.bind('blur', SignUp.reset); + }, + + clear: function(event) + { + // Only clear the search string if the user + // has not previously entered anything. + if (this.value == SignUp.originalText) { + this.value = ''; + } + }, + + reset: function(event) + { + // Only reset the search string if there was + // nothing entered into the search box. + if (!this.value) { + this.value = SignUp.originalText; + } + }, + + submit: function(event) + { + var signUpEmpty = !SignUp.targetBox.val(); + var signUpTextIsOrig = (SignUp.targetBox.val() == SignUp.originalText); + if (signUpEmpty || signUpTextIsOrig) { + event.preventDefault(); + alert('Please enter your email address!'); + SignUp.targetBox.focus(); + } + + SignUp.verifyBox.val(SignUp.targetBox.val()); + } +}; + +$(document).ready(SignUp.init); diff --git a/libjs/prototype.js b/libjs/prototype.js new file mode 100644 index 0000000..5c73462 --- /dev/null +++ b/libjs/prototype.js @@ -0,0 +1,4184 @@ +/* Prototype JavaScript framework, version 1.6.0 + * (c) 2005-2007 Sam Stephenson + * + * Prototype is freely distributable under the terms of an MIT-style license. + * For details, see the Prototype web site: http://www.prototypejs.org/ + * + *--------------------------------------------------------------------------*/ + +var Prototype = { + Version: '1.6.0', + + Browser: { + IE: !!(window.attachEvent && !window.opera), + Opera: !!window.opera, + WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1, + Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1, + MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/) + }, + + BrowserFeatures: { + XPath: !!document.evaluate, + ElementExtensions: !!window.HTMLElement, + SpecificElementExtensions: + document.createElement('div').__proto__ && + document.createElement('div').__proto__ !== + document.createElement('form').__proto__ + }, + + ScriptFragment: ']*>([\\S\\s]*?)<\/script>', + JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/, + + emptyFunction: function() { }, + K: function(x) { return x } +}; + +if (Prototype.Browser.MobileSafari) + Prototype.BrowserFeatures.SpecificElementExtensions = false; + +if (Prototype.Browser.WebKit) + Prototype.BrowserFeatures.XPath = false; + +/* Based on Alex Arnell's inheritance implementation. */ +var Class = { + create: function() { + var parent = null, properties = $A(arguments); + if (Object.isFunction(properties[0])) + parent = properties.shift(); + + function klass() { + this.initialize.apply(this, arguments); + } + + Object.extend(klass, Class.Methods); + klass.superclass = parent; + klass.subclasses = []; + + if (parent) { + var subclass = function() { }; + subclass.prototype = parent.prototype; + klass.prototype = new subclass; + parent.subclasses.push(klass); + } + + for (var i = 0; i < properties.length; i++) + klass.addMethods(properties[i]); + + if (!klass.prototype.initialize) + klass.prototype.initialize = Prototype.emptyFunction; + + klass.prototype.constructor = klass; + + return klass; + } +}; + +Class.Methods = { + addMethods: function(source) { + var ancestor = this.superclass && this.superclass.prototype; + var properties = Object.keys(source); + + if (!Object.keys({ toString: true }).length) + properties.push("toString", "valueOf"); + + for (var i = 0, length = properties.length; i < length; i++) { + var property = properties[i], value = source[property]; + if (ancestor && Object.isFunction(value) && + value.argumentNames().first() == "$super") { + var method = value, value = Object.extend((function(m) { + return function() { return ancestor[m].apply(this, arguments) }; + })(property).wrap(method), { + valueOf: function() { return method }, + toString: function() { return method.toString() } + }); + } + this.prototype[property] = value; + } + + return this; + } +}; + +var Abstract = { }; + +Object.extend = function(destination, source) { + for (var property in source) + destination[property] = source[property]; + return destination; +}; + +Object.extend(Object, { + inspect: function(object) { + try { + if (object === undefined) return 'undefined'; + if (object === null) return 'null'; + return object.inspect ? object.inspect() : object.toString(); + } catch (e) { + if (e instanceof RangeError) return '...'; + throw e; + } + }, + + toJSON: function(object) { + var type = typeof object; + switch (type) { + case 'undefined': + case 'function': + case 'unknown': return; + case 'boolean': return object.toString(); + } + + if (object === null) return 'null'; + if (object.toJSON) return object.toJSON(); + if (Object.isElement(object)) return; + + var results = []; + for (var property in object) { + var value = Object.toJSON(object[property]); + if (value !== undefined) + results.push(property.toJSON() + ': ' + value); + } + + return '{' + results.join(', ') + '}'; + }, + + toQueryString: function(object) { + return $H(object).toQueryString(); + }, + + toHTML: function(object) { + return object && object.toHTML ? object.toHTML() : String.interpret(object); + }, + + keys: function(object) { + var keys = []; + for (var property in object) + keys.push(property); + return keys; + }, + + values: function(object) { + var values = []; + for (var property in object) + values.push(object[property]); + return values; + }, + + clone: function(object) { + return Object.extend({ }, object); + }, + + isElement: function(object) { + return object && object.nodeType == 1; + }, + + isArray: function(object) { + return object && object.constructor === Array; + }, + + isHash: function(object) { + return object instanceof Hash; + }, + + isFunction: function(object) { + return typeof object == "function"; + }, + + isString: function(object) { + return typeof object == "string"; + }, + + isNumber: function(object) { + return typeof object == "number"; + }, + + isUndefined: function(object) { + return typeof object == "undefined"; + } +}); + +Object.extend(Function.prototype, { + argumentNames: function() { + var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip"); + return names.length == 1 && !names[0] ? [] : names; + }, + + bind: function() { + if (arguments.length < 2 && arguments[0] === undefined) return this; + var __method = this, args = $A(arguments), object = args.shift(); + return function() { + return __method.apply(object, args.concat($A(arguments))); + } + }, + + bindAsEventListener: function() { + var __method = this, args = $A(arguments), object = args.shift(); + return function(event) { + return __method.apply(object, [event || window.event].concat(args)); + } + }, + + curry: function() { + if (!arguments.length) return this; + var __method = this, args = $A(arguments); + return function() { + return __method.apply(this, args.concat($A(arguments))); + } + }, + + delay: function() { + var __method = this, args = $A(arguments), timeout = args.shift() * 1000; + return window.setTimeout(function() { + return __method.apply(__method, args); + }, timeout); + }, + + wrap: function(wrapper) { + var __method = this; + return function() { + return wrapper.apply(this, [__method.bind(this)].concat($A(arguments))); + } + }, + + methodize: function() { + if (this._methodized) return this._methodized; + var __method = this; + return this._methodized = function() { + return __method.apply(null, [this].concat($A(arguments))); + }; + } +}); + +Function.prototype.defer = Function.prototype.delay.curry(0.01); + +Date.prototype.toJSON = function() { + return '"' + this.getUTCFullYear() + '-' + + (this.getUTCMonth() + 1).toPaddedString(2) + '-' + + this.getUTCDate().toPaddedString(2) + 'T' + + this.getUTCHours().toPaddedString(2) + ':' + + this.getUTCMinutes().toPaddedString(2) + ':' + + this.getUTCSeconds().toPaddedString(2) + 'Z"'; +}; + +var Try = { + these: function() { + var returnValue; + + for (var i = 0, length = arguments.length; i < length; i++) { + var lambda = arguments[i]; + try { + returnValue = lambda(); + break; + } catch (e) { } + } + + return returnValue; + } +}; + +RegExp.prototype.match = RegExp.prototype.test; + +RegExp.escape = function(str) { + return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); +}; + +/*--------------------------------------------------------------------------*/ + +var PeriodicalExecuter = Class.create({ + initialize: function(callback, frequency) { + this.callback = callback; + this.frequency = frequency; + this.currentlyExecuting = false; + + this.registerCallback(); + }, + + registerCallback: function() { + this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + }, + + execute: function() { + this.callback(this); + }, + + stop: function() { + if (!this.timer) return; + clearInterval(this.timer); + this.timer = null; + }, + + onTimerEvent: function() { + if (!this.currentlyExecuting) { + try { + this.currentlyExecuting = true; + this.execute(); + } finally { + this.currentlyExecuting = false; + } + } + } +}); +Object.extend(String, { + interpret: function(value) { + return value == null ? '' : String(value); + }, + specialChar: { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '\\': '\\\\' + } +}); + +Object.extend(String.prototype, { + gsub: function(pattern, replacement) { + var result = '', source = this, match; + replacement = arguments.callee.prepareReplacement(replacement); + + while (source.length > 0) { + if (match = source.match(pattern)) { + result += source.slice(0, match.index); + result += String.interpret(replacement(match)); + source = source.slice(match.index + match[0].length); + } else { + result += source, source = ''; + } + } + return result; + }, + + sub: function(pattern, replacement, count) { + replacement = this.gsub.prepareReplacement(replacement); + count = count === undefined ? 1 : count; + + return this.gsub(pattern, function(match) { + if (--count < 0) return match[0]; + return replacement(match); + }); + }, + + scan: function(pattern, iterator) { + this.gsub(pattern, iterator); + return String(this); + }, + + truncate: function(length, truncation) { + length = length || 30; + truncation = truncation === undefined ? '...' : truncation; + return this.length > length ? + this.slice(0, length - truncation.length) + truncation : String(this); + }, + + strip: function() { + return this.replace(/^\s+/, '').replace(/\s+$/, ''); + }, + + stripTags: function() { + return this.replace(/<\/?[^>]+>/gi, ''); + }, + + stripScripts: function() { + return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); + }, + + extractScripts: function() { + var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); + var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); + return (this.match(matchAll) || []).map(function(scriptTag) { + return (scriptTag.match(matchOne) || ['', ''])[1]; + }); + }, + + evalScripts: function() { + return this.extractScripts().map(function(script) { return eval(script) }); + }, + + escapeHTML: function() { + var self = arguments.callee; + self.text.data = this; + return self.div.innerHTML; + }, + + unescapeHTML: function() { + var div = new Element('div'); + div.innerHTML = this.stripTags(); + return div.childNodes[0] ? (div.childNodes.length > 1 ? + $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) : + div.childNodes[0].nodeValue) : ''; + }, + + toQueryParams: function(separator) { + var match = this.strip().match(/([^?#]*)(#.*)?$/); + if (!match) return { }; + + return match[1].split(separator || '&').inject({ }, function(hash, pair) { + if ((pair = pair.split('='))[0]) { + var key = decodeURIComponent(pair.shift()); + var value = pair.length > 1 ? pair.join('=') : pair[0]; + if (value != undefined) value = decodeURIComponent(value); + + if (key in hash) { + if (!Object.isArray(hash[key])) hash[key] = [hash[key]]; + hash[key].push(value); + } + else hash[key] = value; + } + return hash; + }); + }, + + toArray: function() { + return this.split(''); + }, + + succ: function() { + return this.slice(0, this.length - 1) + + String.fromCharCode(this.charCodeAt(this.length - 1) + 1); + }, + + times: function(count) { + return count < 1 ? '' : new Array(count + 1).join(this); + }, + + camelize: function() { + var parts = this.split('-'), len = parts.length; + if (len == 1) return parts[0]; + + var camelized = this.charAt(0) == '-' + ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) + : parts[0]; + + for (var i = 1; i < len; i++) + camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); + + return camelized; + }, + + capitalize: function() { + return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); + }, + + underscore: function() { + return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase(); + }, + + dasherize: function() { + return this.gsub(/_/,'-'); + }, + + inspect: function(useDoubleQuotes) { + var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) { + var character = String.specialChar[match[0]]; + return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16); + }); + if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; + return "'" + escapedString.replace(/'/g, '\\\'') + "'"; + }, + + toJSON: function() { + return this.inspect(true); + }, + + unfilterJSON: function(filter) { + return this.sub(filter || Prototype.JSONFilter, '#{1}'); + }, + + isJSON: function() { + var str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''); + return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str); + }, + + evalJSON: function(sanitize) { + var json = this.unfilterJSON(); + try { + if (!sanitize || json.isJSON()) return eval('(' + json + ')'); + } catch (e) { } + throw new SyntaxError('Badly formed JSON string: ' + this.inspect()); + }, + + include: function(pattern) { + return this.indexOf(pattern) > -1; + }, + + startsWith: function(pattern) { + return this.indexOf(pattern) === 0; + }, + + endsWith: function(pattern) { + var d = this.length - pattern.length; + return d >= 0 && this.lastIndexOf(pattern) === d; + }, + + empty: function() { + return this == ''; + }, + + blank: function() { + return /^\s*$/.test(this); + }, + + interpolate: function(object, pattern) { + return new Template(this, pattern).evaluate(object); + } +}); + +if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, { + escapeHTML: function() { + return this.replace(/&/g,'&').replace(//g,'>'); + }, + unescapeHTML: function() { + return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); + } +}); + +String.prototype.gsub.prepareReplacement = function(replacement) { + if (Object.isFunction(replacement)) return replacement; + var template = new Template(replacement); + return function(match) { return template.evaluate(match) }; +}; + +String.prototype.parseQuery = String.prototype.toQueryParams; + +Object.extend(String.prototype.escapeHTML, { + div: document.createElement('div'), + text: document.createTextNode('') +}); + +with (String.prototype.escapeHTML) div.appendChild(text); + +var Template = Class.create({ + initialize: function(template, pattern) { + this.template = template.toString(); + this.pattern = pattern || Template.Pattern; + }, + + evaluate: function(object) { + if (Object.isFunction(object.toTemplateReplacements)) + object = object.toTemplateReplacements(); + + return this.template.gsub(this.pattern, function(match) { + if (object == null) return ''; + + var before = match[1] || ''; + if (before == '\\') return match[2]; + + var ctx = object, expr = match[3]; + var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/, match = pattern.exec(expr); + if (match == null) return before; + + while (match != null) { + var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1]; + ctx = ctx[comp]; + if (null == ctx || '' == match[3]) break; + expr = expr.substring('[' == match[3] ? match[1].length : match[0].length); + match = pattern.exec(expr); + } + + return before + String.interpret(ctx); + }.bind(this)); + } +}); +Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; + +var $break = { }; + +var Enumerable = { + each: function(iterator, context) { + var index = 0; + iterator = iterator.bind(context); + try { + this._each(function(value) { + iterator(value, index++); + }); + } catch (e) { + if (e != $break) throw e; + } + return this; + }, + + eachSlice: function(number, iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var index = -number, slices = [], array = this.toArray(); + while ((index += number) < array.length) + slices.push(array.slice(index, index+number)); + return slices.collect(iterator, context); + }, + + all: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var result = true; + this.each(function(value, index) { + result = result && !!iterator(value, index); + if (!result) throw $break; + }); + return result; + }, + + any: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var result = false; + this.each(function(value, index) { + if (result = !!iterator(value, index)) + throw $break; + }); + return result; + }, + + collect: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var results = []; + this.each(function(value, index) { + results.push(iterator(value, index)); + }); + return results; + }, + + detect: function(iterator, context) { + iterator = iterator.bind(context); + var result; + this.each(function(value, index) { + if (iterator(value, index)) { + result = value; + throw $break; + } + }); + return result; + }, + + findAll: function(iterator, context) { + iterator = iterator.bind(context); + var results = []; + this.each(function(value, index) { + if (iterator(value, index)) + results.push(value); + }); + return results; + }, + + grep: function(filter, iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var results = []; + + if (Object.isString(filter)) + filter = new RegExp(filter); + + this.each(function(value, index) { + if (filter.match(value)) + results.push(iterator(value, index)); + }); + return results; + }, + + include: function(object) { + if (Object.isFunction(this.indexOf)) + if (this.indexOf(object) != -1) return true; + + var found = false; + this.each(function(value) { + if (value == object) { + found = true; + throw $break; + } + }); + return found; + }, + + inGroupsOf: function(number, fillWith) { + fillWith = fillWith === undefined ? null : fillWith; + return this.eachSlice(number, function(slice) { + while(slice.length < number) slice.push(fillWith); + return slice; + }); + }, + + inject: function(memo, iterator, context) { + iterator = iterator.bind(context); + this.each(function(value, index) { + memo = iterator(memo, value, index); + }); + return memo; + }, + + invoke: function(method) { + var args = $A(arguments).slice(1); + return this.map(function(value) { + return value[method].apply(value, args); + }); + }, + + max: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var result; + this.each(function(value, index) { + value = iterator(value, index); + if (result == undefined || value >= result) + result = value; + }); + return result; + }, + + min: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var result; + this.each(function(value, index) { + value = iterator(value, index); + if (result == undefined || value < result) + result = value; + }); + return result; + }, + + partition: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var trues = [], falses = []; + this.each(function(value, index) { + (iterator(value, index) ? + trues : falses).push(value); + }); + return [trues, falses]; + }, + + pluck: function(property) { + var results = []; + this.each(function(value) { + results.push(value[property]); + }); + return results; + }, + + reject: function(iterator, context) { + iterator = iterator.bind(context); + var results = []; + this.each(function(value, index) { + if (!iterator(value, index)) + results.push(value); + }); + return results; + }, + + sortBy: function(iterator, context) { + iterator = iterator.bind(context); + return this.map(function(value, index) { + return {value: value, criteria: iterator(value, index)}; + }).sort(function(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }).pluck('value'); + }, + + toArray: function() { + return this.map(); + }, + + zip: function() { + var iterator = Prototype.K, args = $A(arguments); + if (Object.isFunction(args.last())) + iterator = args.pop(); + + var collections = [this].concat(args).map($A); + return this.map(function(value, index) { + return iterator(collections.pluck(index)); + }); + }, + + size: function() { + return this.toArray().length; + }, + + inspect: function() { + return '#'; + } +}; + +Object.extend(Enumerable, { + map: Enumerable.collect, + find: Enumerable.detect, + select: Enumerable.findAll, + filter: Enumerable.findAll, + member: Enumerable.include, + entries: Enumerable.toArray, + every: Enumerable.all, + some: Enumerable.any +}); +function $A(iterable) { + if (!iterable) return []; + if (iterable.toArray) return iterable.toArray(); + var length = iterable.length, results = new Array(length); + while (length--) results[length] = iterable[length]; + return results; +} + +if (Prototype.Browser.WebKit) { + function $A(iterable) { + if (!iterable) return []; + if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') && + iterable.toArray) return iterable.toArray(); + var length = iterable.length, results = new Array(length); + while (length--) results[length] = iterable[length]; + return results; + } +} + +Array.from = $A; + +Object.extend(Array.prototype, Enumerable); + +if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse; + +Object.extend(Array.prototype, { + _each: function(iterator) { + for (var i = 0, length = this.length; i < length; i++) + iterator(this[i]); + }, + + clear: function() { + this.length = 0; + return this; + }, + + first: function() { + return this[0]; + }, + + last: function() { + return this[this.length - 1]; + }, + + compact: function() { + return this.select(function(value) { + return value != null; + }); + }, + + flatten: function() { + return this.inject([], function(array, value) { + return array.concat(Object.isArray(value) ? + value.flatten() : [value]); + }); + }, + + without: function() { + var values = $A(arguments); + return this.select(function(value) { + return !values.include(value); + }); + }, + + reverse: function(inline) { + return (inline !== false ? this : this.toArray())._reverse(); + }, + + reduce: function() { + return this.length > 1 ? this : this[0]; + }, + + uniq: function(sorted) { + return this.inject([], function(array, value, index) { + if (0 == index || (sorted ? array.last() != value : !array.include(value))) + array.push(value); + return array; + }); + }, + + intersect: function(array) { + return this.uniq().findAll(function(item) { + return array.detect(function(value) { return item === value }); + }); + }, + + clone: function() { + return [].concat(this); + }, + + size: function() { + return this.length; + }, + + inspect: function() { + return '[' + this.map(Object.inspect).join(', ') + ']'; + }, + + toJSON: function() { + var results = []; + this.each(function(object) { + var value = Object.toJSON(object); + if (value !== undefined) results.push(value); + }); + return '[' + results.join(', ') + ']'; + } +}); + +// use native browser JS 1.6 implementation if available +if (Object.isFunction(Array.prototype.forEach)) + Array.prototype._each = Array.prototype.forEach; + +if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) { + i || (i = 0); + var length = this.length; + if (i < 0) i = length + i; + for (; i < length; i++) + if (this[i] === item) return i; + return -1; +}; + +if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) { + i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1; + var n = this.slice(0, i).reverse().indexOf(item); + return (n < 0) ? n : i - n - 1; +}; + +Array.prototype.toArray = Array.prototype.clone; + +function $w(string) { + if (!Object.isString(string)) return []; + string = string.strip(); + return string ? string.split(/\s+/) : []; +} + +if (Prototype.Browser.Opera){ + Array.prototype.concat = function() { + var array = []; + for (var i = 0, length = this.length; i < length; i++) array.push(this[i]); + for (var i = 0, length = arguments.length; i < length; i++) { + if (Object.isArray(arguments[i])) { + for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++) + array.push(arguments[i][j]); + } else { + array.push(arguments[i]); + } + } + return array; + }; +} +Object.extend(Number.prototype, { + toColorPart: function() { + return this.toPaddedString(2, 16); + }, + + succ: function() { + return this + 1; + }, + + times: function(iterator) { + $R(0, this, true).each(iterator); + return this; + }, + + toPaddedString: function(length, radix) { + var string = this.toString(radix || 10); + return '0'.times(length - string.length) + string; + }, + + toJSON: function() { + return isFinite(this) ? this.toString() : 'null'; + } +}); + +$w('abs round ceil floor').each(function(method){ + Number.prototype[method] = Math[method].methodize(); +}); +function $H(object) { + return new Hash(object); +}; + +var Hash = Class.create(Enumerable, (function() { + if (function() { + var i = 0, Test = function(value) { this.key = value }; + Test.prototype.key = 'foo'; + for (var property in new Test('bar')) i++; + return i > 1; + }()) { + function each(iterator) { + var cache = []; + for (var key in this._object) { + var value = this._object[key]; + if (cache.include(key)) continue; + cache.push(key); + var pair = [key, value]; + pair.key = key; + pair.value = value; + iterator(pair); + } + } + } else { + function each(iterator) { + for (var key in this._object) { + var value = this._object[key], pair = [key, value]; + pair.key = key; + pair.value = value; + iterator(pair); + } + } + } + + function toQueryPair(key, value) { + if (Object.isUndefined(value)) return key; + return key + '=' + encodeURIComponent(String.interpret(value)); + } + + return { + initialize: function(object) { + this._object = Object.isHash(object) ? object.toObject() : Object.clone(object); + }, + + _each: each, + + set: function(key, value) { + return this._object[key] = value; + }, + + get: function(key) { + return this._object[key]; + }, + + unset: function(key) { + var value = this._object[key]; + delete this._object[key]; + return value; + }, + + toObject: function() { + return Object.clone(this._object); + }, + + keys: function() { + return this.pluck('key'); + }, + + values: function() { + return this.pluck('value'); + }, + + index: function(value) { + var match = this.detect(function(pair) { + return pair.value === value; + }); + return match && match.key; + }, + + merge: function(object) { + return this.clone().update(object); + }, + + update: function(object) { + return new Hash(object).inject(this, function(result, pair) { + result.set(pair.key, pair.value); + return result; + }); + }, + + toQueryString: function() { + return this.map(function(pair) { + var key = encodeURIComponent(pair.key), values = pair.value; + + if (values && typeof values == 'object') { + if (Object.isArray(values)) + return values.map(toQueryPair.curry(key)).join('&'); + } + return toQueryPair(key, values); + }).join('&'); + }, + + inspect: function() { + return '#'; + }, + + toJSON: function() { + return Object.toJSON(this.toObject()); + }, + + clone: function() { + return new Hash(this); + } + } +})()); + +Hash.prototype.toTemplateReplacements = Hash.prototype.toObject; +Hash.from = $H; +var ObjectRange = Class.create(Enumerable, { + initialize: function(start, end, exclusive) { + this.start = start; + this.end = end; + this.exclusive = exclusive; + }, + + _each: function(iterator) { + var value = this.start; + while (this.include(value)) { + iterator(value); + value = value.succ(); + } + }, + + include: function(value) { + if (value < this.start) + return false; + if (this.exclusive) + return value < this.end; + return value <= this.end; + } +}); + +var $R = function(start, end, exclusive) { + return new ObjectRange(start, end, exclusive); +}; + +var Ajax = { + getTransport: function() { + return Try.these( + function() {return new XMLHttpRequest()}, + function() {return new ActiveXObject('Msxml2.XMLHTTP')}, + function() {return new ActiveXObject('Microsoft.XMLHTTP')} + ) || false; + }, + + activeRequestCount: 0 +}; + +Ajax.Responders = { + responders: [], + + _each: function(iterator) { + this.responders._each(iterator); + }, + + register: function(responder) { + if (!this.include(responder)) + this.responders.push(responder); + }, + + unregister: function(responder) { + this.responders = this.responders.without(responder); + }, + + dispatch: function(callback, request, transport, json) { + this.each(function(responder) { + if (Object.isFunction(responder[callback])) { + try { + responder[callback].apply(responder, [request, transport, json]); + } catch (e) { } + } + }); + } +}; + +Object.extend(Ajax.Responders, Enumerable); + +Ajax.Responders.register({ + onCreate: function() { Ajax.activeRequestCount++ }, + onComplete: function() { Ajax.activeRequestCount-- } +}); + +Ajax.Base = Class.create({ + initialize: function(options) { + this.options = { + method: 'post', + asynchronous: true, + contentType: 'application/x-www-form-urlencoded', + encoding: 'UTF-8', + parameters: '', + evalJSON: true, + evalJS: true + }; + Object.extend(this.options, options || { }); + + this.options.method = this.options.method.toLowerCase(); + if (Object.isString(this.options.parameters)) + this.options.parameters = this.options.parameters.toQueryParams(); + } +}); + +Ajax.Request = Class.create(Ajax.Base, { + _complete: false, + + initialize: function($super, url, options) { + $super(options); + this.transport = Ajax.getTransport(); + this.request(url); + }, + + request: function(url) { + this.url = url; + this.method = this.options.method; + var params = Object.clone(this.options.parameters); + + if (!['get', 'post'].include(this.method)) { + // simulate other verbs over post + params['_method'] = this.method; + this.method = 'post'; + } + + this.parameters = params; + + if (params = Object.toQueryString(params)) { + // when GET, append parameters to URL + if (this.method == 'get') + this.url += (this.url.include('?') ? '&' : '?') + params; + else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) + params += '&_='; + } + + try { + var response = new Ajax.Response(this); + if (this.options.onCreate) this.options.onCreate(response); + Ajax.Responders.dispatch('onCreate', this, response); + + this.transport.open(this.method.toUpperCase(), this.url, + this.options.asynchronous); + + if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1); + + this.transport.onreadystatechange = this.onStateChange.bind(this); + this.setRequestHeaders(); + + this.body = this.method == 'post' ? (this.options.postBody || params) : null; + this.transport.send(this.body); + + /* Force Firefox to handle ready state 4 for synchronous requests */ + if (!this.options.asynchronous && this.transport.overrideMimeType) + this.onStateChange(); + + } + catch (e) { + this.dispatchException(e); + } + }, + + onStateChange: function() { + var readyState = this.transport.readyState; + if (readyState > 1 && !((readyState == 4) && this._complete)) + this.respondToReadyState(this.transport.readyState); + }, + + setRequestHeaders: function() { + var headers = { + 'X-Requested-With': 'XMLHttpRequest', + 'X-Prototype-Version': Prototype.Version, + 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' + }; + + if (this.method == 'post') { + headers['Content-type'] = this.options.contentType + + (this.options.encoding ? '; charset=' + this.options.encoding : ''); + + /* Force "Connection: close" for older Mozilla browsers to work + * around a bug where XMLHttpRequest sends an incorrect + * Content-length header. See Mozilla Bugzilla #246651. + */ + if (this.transport.overrideMimeType && + (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) + headers['Connection'] = 'close'; + } + + // user-defined headers + if (typeof this.options.requestHeaders == 'object') { + var extras = this.options.requestHeaders; + + if (Object.isFunction(extras.push)) + for (var i = 0, length = extras.length; i < length; i += 2) + headers[extras[i]] = extras[i+1]; + else + $H(extras).each(function(pair) { headers[pair.key] = pair.value }); + } + + for (var name in headers) + this.transport.setRequestHeader(name, headers[name]); + }, + + success: function() { + var status = this.getStatus(); + return !status || (status >= 200 && status < 300); + }, + + getStatus: function() { + try { + return this.transport.status || 0; + } catch (e) { return 0 } + }, + + respondToReadyState: function(readyState) { + var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this); + + if (state == 'Complete') { + try { + this._complete = true; + (this.options['on' + response.status] + || this.options['on' + (this.success() ? 'Success' : 'Failure')] + || Prototype.emptyFunction)(response, response.headerJSON); + } catch (e) { + this.dispatchException(e); + } + + var contentType = response.getHeader('Content-type'); + if (this.options.evalJS == 'force' + || (this.options.evalJS && contentType + && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))) + this.evalResponse(); + } + + try { + (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON); + Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON); + } catch (e) { + this.dispatchException(e); + } + + if (state == 'Complete') { + // avoid memory leak in MSIE: clean up + this.transport.onreadystatechange = Prototype.emptyFunction; + } + }, + + getHeader: function(name) { + try { + return this.transport.getResponseHeader(name); + } catch (e) { return null } + }, + + evalResponse: function() { + try { + return eval((this.transport.responseText || '').unfilterJSON()); + } catch (e) { + this.dispatchException(e); + } + }, + + dispatchException: function(exception) { + (this.options.onException || Prototype.emptyFunction)(this, exception); + Ajax.Responders.dispatch('onException', this, exception); + } +}); + +Ajax.Request.Events = + ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; + +Ajax.Response = Class.create({ + initialize: function(request){ + this.request = request; + var transport = this.transport = request.transport, + readyState = this.readyState = transport.readyState; + + if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) { + this.status = this.getStatus(); + this.statusText = this.getStatusText(); + this.responseText = String.interpret(transport.responseText); + this.headerJSON = this._getHeaderJSON(); + } + + if(readyState == 4) { + var xml = transport.responseXML; + this.responseXML = xml === undefined ? null : xml; + this.responseJSON = this._getResponseJSON(); + } + }, + + status: 0, + statusText: '', + + getStatus: Ajax.Request.prototype.getStatus, + + getStatusText: function() { + try { + return this.transport.statusText || ''; + } catch (e) { return '' } + }, + + getHeader: Ajax.Request.prototype.getHeader, + + getAllHeaders: function() { + try { + return this.getAllResponseHeaders(); + } catch (e) { return null } + }, + + getResponseHeader: function(name) { + return this.transport.getResponseHeader(name); + }, + + getAllResponseHeaders: function() { + return this.transport.getAllResponseHeaders(); + }, + + _getHeaderJSON: function() { + var json = this.getHeader('X-JSON'); + if (!json) return null; + json = decodeURIComponent(escape(json)); + try { + return json.evalJSON(this.request.options.sanitizeJSON); + } catch (e) { + this.request.dispatchException(e); + } + }, + + _getResponseJSON: function() { + var options = this.request.options; + if (!options.evalJSON || (options.evalJSON != 'force' && + !(this.getHeader('Content-type') || '').include('application/json'))) + return null; + try { + return this.transport.responseText.evalJSON(options.sanitizeJSON); + } catch (e) { + this.request.dispatchException(e); + } + } +}); + +Ajax.Updater = Class.create(Ajax.Request, { + initialize: function($super, container, url, options) { + this.container = { + success: (container.success || container), + failure: (container.failure || (container.success ? null : container)) + }; + + options = options || { }; + var onComplete = options.onComplete; + options.onComplete = (function(response, param) { + this.updateContent(response.responseText); + if (Object.isFunction(onComplete)) onComplete(response, param); + }).bind(this); + + $super(url, options); + }, + + updateContent: function(responseText) { + var receiver = this.container[this.success() ? 'success' : 'failure'], + options = this.options; + + if (!options.evalScripts) responseText = responseText.stripScripts(); + + if (receiver = $(receiver)) { + if (options.insertion) { + if (Object.isString(options.insertion)) { + var insertion = { }; insertion[options.insertion] = responseText; + receiver.insert(insertion); + } + else options.insertion(receiver, responseText); + } + else receiver.update(responseText); + } + + if (this.success()) { + if (this.onComplete) this.onComplete.bind(this).defer(); + } + } +}); + +Ajax.PeriodicalUpdater = Class.create(Ajax.Base, { + initialize: function($super, container, url, options) { + $super(options); + this.onComplete = this.options.onComplete; + + this.frequency = (this.options.frequency || 2); + this.decay = (this.options.decay || 1); + + this.updater = { }; + this.container = container; + this.url = url; + + this.start(); + }, + + start: function() { + this.options.onComplete = this.updateComplete.bind(this); + this.onTimerEvent(); + }, + + stop: function() { + this.updater.options.onComplete = undefined; + clearTimeout(this.timer); + (this.onComplete || Prototype.emptyFunction).apply(this, arguments); + }, + + updateComplete: function(response) { + if (this.options.decay) { + this.decay = (response.responseText == this.lastText ? + this.decay * this.options.decay : 1); + + this.lastText = response.responseText; + } + this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency); + }, + + onTimerEvent: function() { + this.updater = new Ajax.Updater(this.container, this.url, this.options); + } +}); +function $(element) { + if (arguments.length > 1) { + for (var i = 0, elements = [], length = arguments.length; i < length; i++) + elements.push($(arguments[i])); + return elements; + } + if (Object.isString(element)) + element = document.getElementById(element); + return Element.extend(element); +} + +if (Prototype.BrowserFeatures.XPath) { + document._getElementsByXPath = function(expression, parentElement) { + var results = []; + var query = document.evaluate(expression, $(parentElement) || document, + null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + for (var i = 0, length = query.snapshotLength; i < length; i++) + results.push(Element.extend(query.snapshotItem(i))); + return results; + }; +} + +/*--------------------------------------------------------------------------*/ + +if (!window.Node) var Node = { }; + +if (!Node.ELEMENT_NODE) { + // DOM level 2 ECMAScript Language Binding + Object.extend(Node, { + ELEMENT_NODE: 1, + ATTRIBUTE_NODE: 2, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + ENTITY_REFERENCE_NODE: 5, + ENTITY_NODE: 6, + PROCESSING_INSTRUCTION_NODE: 7, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9, + DOCUMENT_TYPE_NODE: 10, + DOCUMENT_FRAGMENT_NODE: 11, + NOTATION_NODE: 12 + }); +} + +(function() { + var element = this.Element; + this.Element = function(tagName, attributes) { + attributes = attributes || { }; + tagName = tagName.toLowerCase(); + var cache = Element.cache; + if (Prototype.Browser.IE && attributes.name) { + tagName = '<' + tagName + ' name="' + attributes.name + '">'; + delete attributes.name; + return Element.writeAttribute(document.createElement(tagName), attributes); + } + if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName)); + return Element.writeAttribute(cache[tagName].cloneNode(false), attributes); + }; + Object.extend(this.Element, element || { }); +}).call(window); + +Element.cache = { }; + +Element.Methods = { + visible: function(element) { + return $(element).style.display != 'none'; + }, + + toggle: function(element) { + element = $(element); + Element[Element.visible(element) ? 'hide' : 'show'](element); + return element; + }, + + hide: function(element) { + $(element).style.display = 'none'; + return element; + }, + + show: function(element) { + $(element).style.display = ''; + return element; + }, + + remove: function(element) { + element = $(element); + element.parentNode.removeChild(element); + return element; + }, + + update: function(element, content) { + element = $(element); + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) return element.update().insert(content); + content = Object.toHTML(content); + element.innerHTML = content.stripScripts(); + content.evalScripts.bind(content).defer(); + return element; + }, + + replace: function(element, content) { + element = $(element); + if (content && content.toElement) content = content.toElement(); + else if (!Object.isElement(content)) { + content = Object.toHTML(content); + var range = element.ownerDocument.createRange(); + range.selectNode(element); + content.evalScripts.bind(content).defer(); + content = range.createContextualFragment(content.stripScripts()); + } + element.parentNode.replaceChild(content, element); + return element; + }, + + insert: function(element, insertions) { + element = $(element); + + if (Object.isString(insertions) || Object.isNumber(insertions) || + Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML))) + insertions = {bottom:insertions}; + + var content, t, range; + + for (position in insertions) { + content = insertions[position]; + position = position.toLowerCase(); + t = Element._insertionTranslations[position]; + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + t.insert(element, content); + continue; + } + + content = Object.toHTML(content); + + range = element.ownerDocument.createRange(); + t.initializeRange(element, range); + t.insert(element, range.createContextualFragment(content.stripScripts())); + + content.evalScripts.bind(content).defer(); + } + + return element; + }, + + wrap: function(element, wrapper, attributes) { + element = $(element); + if (Object.isElement(wrapper)) + $(wrapper).writeAttribute(attributes || { }); + else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes); + else wrapper = new Element('div', wrapper); + if (element.parentNode) + element.parentNode.replaceChild(wrapper, element); + wrapper.appendChild(element); + return wrapper; + }, + + inspect: function(element) { + element = $(element); + var result = '<' + element.tagName.toLowerCase(); + $H({'id': 'id', 'className': 'class'}).each(function(pair) { + var property = pair.first(), attribute = pair.last(); + var value = (element[property] || '').toString(); + if (value) result += ' ' + attribute + '=' + value.inspect(true); + }); + return result + '>'; + }, + + recursivelyCollect: function(element, property) { + element = $(element); + var elements = []; + while (element = element[property]) + if (element.nodeType == 1) + elements.push(Element.extend(element)); + return elements; + }, + + ancestors: function(element) { + return $(element).recursivelyCollect('parentNode'); + }, + + descendants: function(element) { + return $A($(element).getElementsByTagName('*')).each(Element.extend); + }, + + firstDescendant: function(element) { + element = $(element).firstChild; + while (element && element.nodeType != 1) element = element.nextSibling; + return $(element); + }, + + immediateDescendants: function(element) { + if (!(element = $(element).firstChild)) return []; + while (element && element.nodeType != 1) element = element.nextSibling; + if (element) return [element].concat($(element).nextSiblings()); + return []; + }, + + previousSiblings: function(element) { + return $(element).recursivelyCollect('previousSibling'); + }, + + nextSiblings: function(element) { + return $(element).recursivelyCollect('nextSibling'); + }, + + siblings: function(element) { + element = $(element); + return element.previousSiblings().reverse().concat(element.nextSiblings()); + }, + + match: function(element, selector) { + if (Object.isString(selector)) + selector = new Selector(selector); + return selector.match($(element)); + }, + + up: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(element.parentNode); + var ancestors = element.ancestors(); + return expression ? Selector.findElement(ancestors, expression, index) : + ancestors[index || 0]; + }, + + down: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return element.firstDescendant(); + var descendants = element.descendants(); + return expression ? Selector.findElement(descendants, expression, index) : + descendants[index || 0]; + }, + + previous: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element)); + var previousSiblings = element.previousSiblings(); + return expression ? Selector.findElement(previousSiblings, expression, index) : + previousSiblings[index || 0]; + }, + + next: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element)); + var nextSiblings = element.nextSiblings(); + return expression ? Selector.findElement(nextSiblings, expression, index) : + nextSiblings[index || 0]; + }, + + select: function() { + var args = $A(arguments), element = $(args.shift()); + return Selector.findChildElements(element, args); + }, + + adjacent: function() { + var args = $A(arguments), element = $(args.shift()); + return Selector.findChildElements(element.parentNode, args).without(element); + }, + + identify: function(element) { + element = $(element); + var id = element.readAttribute('id'), self = arguments.callee; + if (id) return id; + do { id = 'anonymous_element_' + self.counter++ } while ($(id)); + element.writeAttribute('id', id); + return id; + }, + + readAttribute: function(element, name) { + element = $(element); + if (Prototype.Browser.IE) { + var t = Element._attributeTranslations.read; + if (t.values[name]) return t.values[name](element, name); + if (t.names[name]) name = t.names[name]; + if (name.include(':')) { + return (!element.attributes || !element.attributes[name]) ? null : + element.attributes[name].value; + } + } + return element.getAttribute(name); + }, + + writeAttribute: function(element, name, value) { + element = $(element); + var attributes = { }, t = Element._attributeTranslations.write; + + if (typeof name == 'object') attributes = name; + else attributes[name] = value === undefined ? true : value; + + for (var attr in attributes) { + var name = t.names[attr] || attr, value = attributes[attr]; + if (t.values[attr]) name = t.values[attr](element, value); + if (value === false || value === null) + element.removeAttribute(name); + else if (value === true) + element.setAttribute(name, name); + else element.setAttribute(name, value); + } + return element; + }, + + getHeight: function(element) { + return $(element).getDimensions().height; + }, + + getWidth: function(element) { + return $(element).getDimensions().width; + }, + + classNames: function(element) { + return new Element.ClassNames(element); + }, + + hasClassName: function(element, className) { + if (!(element = $(element))) return; + var elementClassName = element.className; + return (elementClassName.length > 0 && (elementClassName == className || + new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName))); + }, + + addClassName: function(element, className) { + if (!(element = $(element))) return; + if (!element.hasClassName(className)) + element.className += (element.className ? ' ' : '') + className; + return element; + }, + + removeClassName: function(element, className) { + if (!(element = $(element))) return; + element.className = element.className.replace( + new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip(); + return element; + }, + + toggleClassName: function(element, className) { + if (!(element = $(element))) return; + return element[element.hasClassName(className) ? + 'removeClassName' : 'addClassName'](className); + }, + + // removes whitespace-only text node children + cleanWhitespace: function(element) { + element = $(element); + var node = element.firstChild; + while (node) { + var nextNode = node.nextSibling; + if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) + element.removeChild(node); + node = nextNode; + } + return element; + }, + + empty: function(element) { + return $(element).innerHTML.blank(); + }, + + descendantOf: function(element, ancestor) { + element = $(element), ancestor = $(ancestor); + + if (element.compareDocumentPosition) + return (element.compareDocumentPosition(ancestor) & 8) === 8; + + if (element.sourceIndex && !Prototype.Browser.Opera) { + var e = element.sourceIndex, a = ancestor.sourceIndex, + nextAncestor = ancestor.nextSibling; + if (!nextAncestor) { + do { ancestor = ancestor.parentNode; } + while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode); + } + if (nextAncestor) return (e > a && e < nextAncestor.sourceIndex); + } + + while (element = element.parentNode) + if (element == ancestor) return true; + return false; + }, + + scrollTo: function(element) { + element = $(element); + var pos = element.cumulativeOffset(); + window.scrollTo(pos[0], pos[1]); + return element; + }, + + getStyle: function(element, style) { + element = $(element); + style = style == 'float' ? 'cssFloat' : style.camelize(); + var value = element.style[style]; + if (!value) { + var css = document.defaultView.getComputedStyle(element, null); + value = css ? css[style] : null; + } + if (style == 'opacity') return value ? parseFloat(value) : 1.0; + return value == 'auto' ? null : value; + }, + + getOpacity: function(element) { + return $(element).getStyle('opacity'); + }, + + setStyle: function(element, styles) { + element = $(element); + var elementStyle = element.style, match; + if (Object.isString(styles)) { + element.style.cssText += ';' + styles; + return styles.include('opacity') ? + element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element; + } + for (var property in styles) + if (property == 'opacity') element.setOpacity(styles[property]); + else + elementStyle[(property == 'float' || property == 'cssFloat') ? + (elementStyle.styleFloat === undefined ? 'cssFloat' : 'styleFloat') : + property] = styles[property]; + + return element; + }, + + setOpacity: function(element, value) { + element = $(element); + element.style.opacity = (value == 1 || value === '') ? '' : + (value < 0.00001) ? 0 : value; + return element; + }, + + getDimensions: function(element) { + element = $(element); + var display = $(element).getStyle('display'); + if (display != 'none' && display != null) // Safari bug + return {width: element.offsetWidth, height: element.offsetHeight}; + + // All *Width and *Height properties give 0 on elements with display none, + // so enable the element temporarily + var els = element.style; + var originalVisibility = els.visibility; + var originalPosition = els.position; + var originalDisplay = els.display; + els.visibility = 'hidden'; + els.position = 'absolute'; + els.display = 'block'; + var originalWidth = element.clientWidth; + var originalHeight = element.clientHeight; + els.display = originalDisplay; + els.position = originalPosition; + els.visibility = originalVisibility; + return {width: originalWidth, height: originalHeight}; + }, + + makePositioned: function(element) { + element = $(element); + var pos = Element.getStyle(element, 'position'); + if (pos == 'static' || !pos) { + element._madePositioned = true; + element.style.position = 'relative'; + // Opera returns the offset relative to the positioning context, when an + // element is position relative but top and left have not been defined + if (window.opera) { + element.style.top = 0; + element.style.left = 0; + } + } + return element; + }, + + undoPositioned: function(element) { + element = $(element); + if (element._madePositioned) { + element._madePositioned = undefined; + element.style.position = + element.style.top = + element.style.left = + element.style.bottom = + element.style.right = ''; + } + return element; + }, + + makeClipping: function(element) { + element = $(element); + if (element._overflow) return element; + element._overflow = Element.getStyle(element, 'overflow') || 'auto'; + if (element._overflow !== 'hidden') + element.style.overflow = 'hidden'; + return element; + }, + + undoClipping: function(element) { + element = $(element); + if (!element._overflow) return element; + element.style.overflow = element._overflow == 'auto' ? '' : element._overflow; + element._overflow = null; + return element; + }, + + cumulativeOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + positionedOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + if (element) { + if (element.tagName == 'BODY') break; + var p = Element.getStyle(element, 'position'); + if (p == 'relative' || p == 'absolute') break; + } + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + absolutize: function(element) { + element = $(element); + if (element.getStyle('position') == 'absolute') return; + // Position.prepare(); // To be done manually by Scripty when it needs it. + + var offsets = element.positionedOffset(); + var top = offsets[1]; + var left = offsets[0]; + var width = element.clientWidth; + var height = element.clientHeight; + + element._originalLeft = left - parseFloat(element.style.left || 0); + element._originalTop = top - parseFloat(element.style.top || 0); + element._originalWidth = element.style.width; + element._originalHeight = element.style.height; + + element.style.position = 'absolute'; + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.width = width + 'px'; + element.style.height = height + 'px'; + return element; + }, + + relativize: function(element) { + element = $(element); + if (element.getStyle('position') == 'relative') return; + // Position.prepare(); // To be done manually by Scripty when it needs it. + + element.style.position = 'relative'; + var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); + var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); + + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.height = element._originalHeight; + element.style.width = element._originalWidth; + return element; + }, + + cumulativeScrollOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.scrollTop || 0; + valueL += element.scrollLeft || 0; + element = element.parentNode; + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + getOffsetParent: function(element) { + if (element.offsetParent) return $(element.offsetParent); + if (element == document.body) return $(element); + + while ((element = element.parentNode) && element != document.body) + if (Element.getStyle(element, 'position') != 'static') + return $(element); + + return $(document.body); + }, + + viewportOffset: function(forElement) { + var valueT = 0, valueL = 0; + + var element = forElement; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + + // Safari fix + if (element.offsetParent == document.body && + Element.getStyle(element, 'position') == 'absolute') break; + + } while (element = element.offsetParent); + + element = forElement; + do { + if (!Prototype.Browser.Opera || element.tagName == 'BODY') { + valueT -= element.scrollTop || 0; + valueL -= element.scrollLeft || 0; + } + } while (element = element.parentNode); + + return Element._returnOffset(valueL, valueT); + }, + + clonePosition: function(element, source) { + var options = Object.extend({ + setLeft: true, + setTop: true, + setWidth: true, + setHeight: true, + offsetTop: 0, + offsetLeft: 0 + }, arguments[2] || { }); + + // find page position of source + source = $(source); + var p = source.viewportOffset(); + + // find coordinate system to use + element = $(element); + var delta = [0, 0]; + var parent = null; + // delta [0,0] will do fine with position: fixed elements, + // position:absolute needs offsetParent deltas + if (Element.getStyle(element, 'position') == 'absolute') { + parent = element.getOffsetParent(); + delta = parent.viewportOffset(); + } + + // correct by body offsets (fixes Safari) + if (parent == document.body) { + delta[0] -= document.body.offsetLeft; + delta[1] -= document.body.offsetTop; + } + + // set position + if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; + if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; + if (options.setWidth) element.style.width = source.offsetWidth + 'px'; + if (options.setHeight) element.style.height = source.offsetHeight + 'px'; + return element; + } +}; + +Element.Methods.identify.counter = 1; + +Object.extend(Element.Methods, { + getElementsBySelector: Element.Methods.select, + childElements: Element.Methods.immediateDescendants +}); + +Element._attributeTranslations = { + write: { + names: { + className: 'class', + htmlFor: 'for' + }, + values: { } + } +}; + + +if (!document.createRange || Prototype.Browser.Opera) { + Element.Methods.insert = function(element, insertions) { + element = $(element); + + if (Object.isString(insertions) || Object.isNumber(insertions) || + Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML))) + insertions = { bottom: insertions }; + + var t = Element._insertionTranslations, content, position, pos, tagName; + + for (position in insertions) { + content = insertions[position]; + position = position.toLowerCase(); + pos = t[position]; + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + pos.insert(element, content); + continue; + } + + content = Object.toHTML(content); + tagName = ((position == 'before' || position == 'after') + ? element.parentNode : element).tagName.toUpperCase(); + + if (t.tags[tagName]) { + var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + if (position == 'top' || position == 'after') fragments.reverse(); + fragments.each(pos.insert.curry(element)); + } + else element.insertAdjacentHTML(pos.adjacency, content.stripScripts()); + + content.evalScripts.bind(content).defer(); + } + + return element; + }; +} + +if (Prototype.Browser.Opera) { + Element.Methods._getStyle = Element.Methods.getStyle; + Element.Methods.getStyle = function(element, style) { + switch(style) { + case 'left': + case 'top': + case 'right': + case 'bottom': + if (Element._getStyle(element, 'position') == 'static') return null; + default: return Element._getStyle(element, style); + } + }; + Element.Methods._readAttribute = Element.Methods.readAttribute; + Element.Methods.readAttribute = function(element, attribute) { + if (attribute == 'title') return element.title; + return Element._readAttribute(element, attribute); + }; +} + +else if (Prototype.Browser.IE) { + $w('positionedOffset getOffsetParent viewportOffset').each(function(method) { + Element.Methods[method] = Element.Methods[method].wrap( + function(proceed, element) { + element = $(element); + var position = element.getStyle('position'); + if (position != 'static') return proceed(element); + element.setStyle({ position: 'relative' }); + var value = proceed(element); + element.setStyle({ position: position }); + return value; + } + ); + }); + + Element.Methods.getStyle = function(element, style) { + element = $(element); + style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize(); + var value = element.style[style]; + if (!value && element.currentStyle) value = element.currentStyle[style]; + + if (style == 'opacity') { + if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) + if (value[1]) return parseFloat(value[1]) / 100; + return 1.0; + } + + if (value == 'auto') { + if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none')) + return element['offset' + style.capitalize()] + 'px'; + return null; + } + return value; + }; + + Element.Methods.setOpacity = function(element, value) { + function stripAlpha(filter){ + return filter.replace(/alpha\([^\)]*\)/gi,''); + } + element = $(element); + var currentStyle = element.currentStyle; + if ((currentStyle && !currentStyle.hasLayout) || + (!currentStyle && element.style.zoom == 'normal')) + element.style.zoom = 1; + + var filter = element.getStyle('filter'), style = element.style; + if (value == 1 || value === '') { + (filter = stripAlpha(filter)) ? + style.filter = filter : style.removeAttribute('filter'); + return element; + } else if (value < 0.00001) value = 0; + style.filter = stripAlpha(filter) + + 'alpha(opacity=' + (value * 100) + ')'; + return element; + }; + + Element._attributeTranslations = { + read: { + names: { + 'class': 'className', + 'for': 'htmlFor' + }, + values: { + _getAttr: function(element, attribute) { + return element.getAttribute(attribute, 2); + }, + _getAttrNode: function(element, attribute) { + var node = element.getAttributeNode(attribute); + return node ? node.value : ""; + }, + _getEv: function(element, attribute) { + var attribute = element.getAttribute(attribute); + return attribute ? attribute.toString().slice(23, -2) : null; + }, + _flag: function(element, attribute) { + return $(element).hasAttribute(attribute) ? attribute : null; + }, + style: function(element) { + return element.style.cssText.toLowerCase(); + }, + title: function(element) { + return element.title; + } + } + } + }; + + Element._attributeTranslations.write = { + names: Object.clone(Element._attributeTranslations.read.names), + values: { + checked: function(element, value) { + element.checked = !!value; + }, + + style: function(element, value) { + element.style.cssText = value ? value : ''; + } + } + }; + + Element._attributeTranslations.has = {}; + + $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' + + 'encType maxLength readOnly longDesc').each(function(attr) { + Element._attributeTranslations.write.names[attr.toLowerCase()] = attr; + Element._attributeTranslations.has[attr.toLowerCase()] = attr; + }); + + (function(v) { + Object.extend(v, { + href: v._getAttr, + src: v._getAttr, + type: v._getAttr, + action: v._getAttrNode, + disabled: v._flag, + checked: v._flag, + readonly: v._flag, + multiple: v._flag, + onload: v._getEv, + onunload: v._getEv, + onclick: v._getEv, + ondblclick: v._getEv, + onmousedown: v._getEv, + onmouseup: v._getEv, + onmouseover: v._getEv, + onmousemove: v._getEv, + onmouseout: v._getEv, + onfocus: v._getEv, + onblur: v._getEv, + onkeypress: v._getEv, + onkeydown: v._getEv, + onkeyup: v._getEv, + onsubmit: v._getEv, + onreset: v._getEv, + onselect: v._getEv, + onchange: v._getEv + }); + })(Element._attributeTranslations.read.values); +} + +else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) { + Element.Methods.setOpacity = function(element, value) { + element = $(element); + element.style.opacity = (value == 1) ? 0.999999 : + (value === '') ? '' : (value < 0.00001) ? 0 : value; + return element; + }; +} + +else if (Prototype.Browser.WebKit) { + Element.Methods.setOpacity = function(element, value) { + element = $(element); + element.style.opacity = (value == 1 || value === '') ? '' : + (value < 0.00001) ? 0 : value; + + if (value == 1) + if(element.tagName == 'IMG' && element.width) { + element.width++; element.width--; + } else try { + var n = document.createTextNode(' '); + element.appendChild(n); + element.removeChild(n); + } catch (e) { } + + return element; + }; + + // Safari returns margins on body which is incorrect if the child is absolutely + // positioned. For performance reasons, redefine Position.cumulativeOffset for + // KHTML/WebKit only. + Element.Methods.cumulativeOffset = function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + if (element.offsetParent == document.body) + if (Element.getStyle(element, 'position') == 'absolute') break; + + element = element.offsetParent; + } while (element); + + return Element._returnOffset(valueL, valueT); + }; +} + +if (Prototype.Browser.IE || Prototype.Browser.Opera) { + // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements + Element.Methods.update = function(element, content) { + element = $(element); + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) return element.update().insert(content); + + content = Object.toHTML(content); + var tagName = element.tagName.toUpperCase(); + + if (tagName in Element._insertionTranslations.tags) { + $A(element.childNodes).each(function(node) { element.removeChild(node) }); + Element._getContentFromAnonymousElement(tagName, content.stripScripts()) + .each(function(node) { element.appendChild(node) }); + } + else element.innerHTML = content.stripScripts(); + + content.evalScripts.bind(content).defer(); + return element; + }; +} + +if (document.createElement('div').outerHTML) { + Element.Methods.replace = function(element, content) { + element = $(element); + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + element.parentNode.replaceChild(content, element); + return element; + } + + content = Object.toHTML(content); + var parent = element.parentNode, tagName = parent.tagName.toUpperCase(); + + if (Element._insertionTranslations.tags[tagName]) { + var nextSibling = element.next(); + var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + parent.removeChild(element); + if (nextSibling) + fragments.each(function(node) { parent.insertBefore(node, nextSibling) }); + else + fragments.each(function(node) { parent.appendChild(node) }); + } + else element.outerHTML = content.stripScripts(); + + content.evalScripts.bind(content).defer(); + return element; + }; +} + +Element._returnOffset = function(l, t) { + var result = [l, t]; + result.left = l; + result.top = t; + return result; +}; + +Element._getContentFromAnonymousElement = function(tagName, html) { + var div = new Element('div'), t = Element._insertionTranslations.tags[tagName]; + div.innerHTML = t[0] + html + t[1]; + t[2].times(function() { div = div.firstChild }); + return $A(div.childNodes); +}; + +Element._insertionTranslations = { + before: { + adjacency: 'beforeBegin', + insert: function(element, node) { + element.parentNode.insertBefore(node, element); + }, + initializeRange: function(element, range) { + range.setStartBefore(element); + } + }, + top: { + adjacency: 'afterBegin', + insert: function(element, node) { + element.insertBefore(node, element.firstChild); + }, + initializeRange: function(element, range) { + range.selectNodeContents(element); + range.collapse(true); + } + }, + bottom: { + adjacency: 'beforeEnd', + insert: function(element, node) { + element.appendChild(node); + } + }, + after: { + adjacency: 'afterEnd', + insert: function(element, node) { + element.parentNode.insertBefore(node, element.nextSibling); + }, + initializeRange: function(element, range) { + range.setStartAfter(element); + } + }, + tags: { + TABLE: ['', '
    ', 1], + TBODY: ['', '
    ', 2], + TR: ['', '
    ', 3], + TD: ['
    ', '
    ', 4], + SELECT: ['', 1] + } +}; + +(function() { + this.bottom.initializeRange = this.top.initializeRange; + Object.extend(this.tags, { + THEAD: this.tags.TBODY, + TFOOT: this.tags.TBODY, + TH: this.tags.TD + }); +}).call(Element._insertionTranslations); + +Element.Methods.Simulated = { + hasAttribute: function(element, attribute) { + attribute = Element._attributeTranslations.has[attribute] || attribute; + var node = $(element).getAttributeNode(attribute); + return node && node.specified; + } +}; + +Element.Methods.ByTag = { }; + +Object.extend(Element, Element.Methods); + +if (!Prototype.BrowserFeatures.ElementExtensions && + document.createElement('div').__proto__) { + window.HTMLElement = { }; + window.HTMLElement.prototype = document.createElement('div').__proto__; + Prototype.BrowserFeatures.ElementExtensions = true; +} + +Element.extend = (function() { + if (Prototype.BrowserFeatures.SpecificElementExtensions) + return Prototype.K; + + var Methods = { }, ByTag = Element.Methods.ByTag; + + var extend = Object.extend(function(element) { + if (!element || element._extendedByPrototype || + element.nodeType != 1 || element == window) return element; + + var methods = Object.clone(Methods), + tagName = element.tagName, property, value; + + // extend methods for specific tags + if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]); + + for (property in methods) { + value = methods[property]; + if (Object.isFunction(value) && !(property in element)) + element[property] = value.methodize(); + } + + element._extendedByPrototype = Prototype.emptyFunction; + return element; + + }, { + refresh: function() { + // extend methods for all tags (Safari doesn't need this) + if (!Prototype.BrowserFeatures.ElementExtensions) { + Object.extend(Methods, Element.Methods); + Object.extend(Methods, Element.Methods.Simulated); + } + } + }); + + extend.refresh(); + return extend; +})(); + +Element.hasAttribute = function(element, attribute) { + if (element.hasAttribute) return element.hasAttribute(attribute); + return Element.Methods.Simulated.hasAttribute(element, attribute); +}; + +Element.addMethods = function(methods) { + var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag; + + if (!methods) { + Object.extend(Form, Form.Methods); + Object.extend(Form.Element, Form.Element.Methods); + Object.extend(Element.Methods.ByTag, { + "FORM": Object.clone(Form.Methods), + "INPUT": Object.clone(Form.Element.Methods), + "SELECT": Object.clone(Form.Element.Methods), + "TEXTAREA": Object.clone(Form.Element.Methods) + }); + } + + if (arguments.length == 2) { + var tagName = methods; + methods = arguments[1]; + } + + if (!tagName) Object.extend(Element.Methods, methods || { }); + else { + if (Object.isArray(tagName)) tagName.each(extend); + else extend(tagName); + } + + function extend(tagName) { + tagName = tagName.toUpperCase(); + if (!Element.Methods.ByTag[tagName]) + Element.Methods.ByTag[tagName] = { }; + Object.extend(Element.Methods.ByTag[tagName], methods); + } + + function copy(methods, destination, onlyIfAbsent) { + onlyIfAbsent = onlyIfAbsent || false; + for (var property in methods) { + var value = methods[property]; + if (!Object.isFunction(value)) continue; + if (!onlyIfAbsent || !(property in destination)) + destination[property] = value.methodize(); + } + } + + function findDOMClass(tagName) { + var klass; + var trans = { + "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph", + "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList", + "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading", + "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote", + "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION": + "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD": + "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR": + "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET": + "FrameSet", "IFRAME": "IFrame" + }; + if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element'; + if (window[klass]) return window[klass]; + klass = 'HTML' + tagName + 'Element'; + if (window[klass]) return window[klass]; + klass = 'HTML' + tagName.capitalize() + 'Element'; + if (window[klass]) return window[klass]; + + window[klass] = { }; + window[klass].prototype = document.createElement(tagName).__proto__; + return window[klass]; + } + + if (F.ElementExtensions) { + copy(Element.Methods, HTMLElement.prototype); + copy(Element.Methods.Simulated, HTMLElement.prototype, true); + } + + if (F.SpecificElementExtensions) { + for (var tag in Element.Methods.ByTag) { + var klass = findDOMClass(tag); + if (Object.isUndefined(klass)) continue; + copy(T[tag], klass.prototype); + } + } + + Object.extend(Element, Element.Methods); + delete Element.ByTag; + + if (Element.extend.refresh) Element.extend.refresh(); + Element.cache = { }; +}; + +document.viewport = { + getDimensions: function() { + var dimensions = { }; + $w('width height').each(function(d) { + var D = d.capitalize(); + dimensions[d] = self['inner' + D] || + (document.documentElement['client' + D] || document.body['client' + D]); + }); + return dimensions; + }, + + getWidth: function() { + return this.getDimensions().width; + }, + + getHeight: function() { + return this.getDimensions().height; + }, + + getScrollOffsets: function() { + return Element._returnOffset( + window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, + window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop); + } +}; +/* Portions of the Selector class are derived from Jack Slocum’s DomQuery, + * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style + * license. Please see http://www.yui-ext.com/ for more information. */ + +var Selector = Class.create({ + initialize: function(expression) { + this.expression = expression.strip(); + this.compileMatcher(); + }, + + compileMatcher: function() { + // Selectors with namespaced attributes can't use the XPath version + if (Prototype.BrowserFeatures.XPath && !(/(\[[\w-]*?:|:checked)/).test(this.expression)) + return this.compileXPathMatcher(); + + var e = this.expression, ps = Selector.patterns, h = Selector.handlers, + c = Selector.criteria, le, p, m; + + if (Selector._cache[e]) { + this.matcher = Selector._cache[e]; + return; + } + + this.matcher = ["this.matcher = function(root) {", + "var r = root, h = Selector.handlers, c = false, n;"]; + + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i in ps) { + p = ps[i]; + if (m = e.match(p)) { + this.matcher.push(Object.isFunction(c[i]) ? c[i](m) : + new Template(c[i]).evaluate(m)); + e = e.replace(m[0], ''); + break; + } + } + } + + this.matcher.push("return h.unique(n);\n}"); + eval(this.matcher.join('\n')); + Selector._cache[this.expression] = this.matcher; + }, + + compileXPathMatcher: function() { + var e = this.expression, ps = Selector.patterns, + x = Selector.xpath, le, m; + + if (Selector._cache[e]) { + this.xpath = Selector._cache[e]; return; + } + + this.matcher = ['.//*']; + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i in ps) { + if (m = e.match(ps[i])) { + this.matcher.push(Object.isFunction(x[i]) ? x[i](m) : + new Template(x[i]).evaluate(m)); + e = e.replace(m[0], ''); + break; + } + } + } + + this.xpath = this.matcher.join(''); + Selector._cache[this.expression] = this.xpath; + }, + + findElements: function(root) { + root = root || document; + if (this.xpath) return document._getElementsByXPath(this.xpath, root); + return this.matcher(root); + }, + + match: function(element) { + this.tokens = []; + + var e = this.expression, ps = Selector.patterns, as = Selector.assertions; + var le, p, m; + + while (e && le !== e && (/\S/).test(e)) { + le = e; + for (var i in ps) { + p = ps[i]; + if (m = e.match(p)) { + // use the Selector.assertions methods unless the selector + // is too complex. + if (as[i]) { + this.tokens.push([i, Object.clone(m)]); + e = e.replace(m[0], ''); + } else { + // reluctantly do a document-wide search + // and look for a match in the array + return this.findElements(document).include(element); + } + } + } + } + + var match = true, name, matches; + for (var i = 0, token; token = this.tokens[i]; i++) { + name = token[0], matches = token[1]; + if (!Selector.assertions[name](element, matches)) { + match = false; break; + } + } + + return match; + }, + + toString: function() { + return this.expression; + }, + + inspect: function() { + return "#"; + } +}); + +Object.extend(Selector, { + _cache: { }, + + xpath: { + descendant: "//*", + child: "/*", + adjacent: "/following-sibling::*[1]", + laterSibling: '/following-sibling::*', + tagName: function(m) { + if (m[1] == '*') return ''; + return "[local-name()='" + m[1].toLowerCase() + + "' or local-name()='" + m[1].toUpperCase() + "']"; + }, + className: "[contains(concat(' ', @class, ' '), ' #{1} ')]", + id: "[@id='#{1}']", + attrPresence: "[@#{1}]", + attr: function(m) { + m[3] = m[5] || m[6]; + return new Template(Selector.xpath.operators[m[2]]).evaluate(m); + }, + pseudo: function(m) { + var h = Selector.xpath.pseudos[m[1]]; + if (!h) return ''; + if (Object.isFunction(h)) return h(m); + return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m); + }, + operators: { + '=': "[@#{1}='#{3}']", + '!=': "[@#{1}!='#{3}']", + '^=': "[starts-with(@#{1}, '#{3}')]", + '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']", + '*=': "[contains(@#{1}, '#{3}')]", + '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]", + '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]" + }, + pseudos: { + 'first-child': '[not(preceding-sibling::*)]', + 'last-child': '[not(following-sibling::*)]', + 'only-child': '[not(preceding-sibling::* or following-sibling::*)]', + 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]", + 'checked': "[@checked]", + 'disabled': "[@disabled]", + 'enabled': "[not(@disabled)]", + 'not': function(m) { + var e = m[6], p = Selector.patterns, + x = Selector.xpath, le, m, v; + + var exclusion = []; + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i in p) { + if (m = e.match(p[i])) { + v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m); + exclusion.push("(" + v.substring(1, v.length - 1) + ")"); + e = e.replace(m[0], ''); + break; + } + } + } + return "[not(" + exclusion.join(" and ") + ")]"; + }, + 'nth-child': function(m) { + return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m); + }, + 'nth-last-child': function(m) { + return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m); + }, + 'nth-of-type': function(m) { + return Selector.xpath.pseudos.nth("position() ", m); + }, + 'nth-last-of-type': function(m) { + return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m); + }, + 'first-of-type': function(m) { + m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m); + }, + 'last-of-type': function(m) { + m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m); + }, + 'only-of-type': function(m) { + var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m); + }, + nth: function(fragment, m) { + var mm, formula = m[6], predicate; + if (formula == 'even') formula = '2n+0'; + if (formula == 'odd') formula = '2n+1'; + if (mm = formula.match(/^(\d+)$/)) // digit only + return '[' + fragment + "= " + mm[1] + ']'; + if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b + if (mm[1] == "-") mm[1] = -1; + var a = mm[1] ? Number(mm[1]) : 1; + var b = mm[2] ? Number(mm[2]) : 0; + predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " + + "((#{fragment} - #{b}) div #{a} >= 0)]"; + return new Template(predicate).evaluate({ + fragment: fragment, a: a, b: b }); + } + } + } + }, + + criteria: { + tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;', + className: 'n = h.className(n, r, "#{1}", c); c = false;', + id: 'n = h.id(n, r, "#{1}", c); c = false;', + attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;', + attr: function(m) { + m[3] = (m[5] || m[6]); + return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m); + }, + pseudo: function(m) { + if (m[6]) m[6] = m[6].replace(/"/g, '\\"'); + return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m); + }, + descendant: 'c = "descendant";', + child: 'c = "child";', + adjacent: 'c = "adjacent";', + laterSibling: 'c = "laterSibling";' + }, + + patterns: { + // combinators must be listed first + // (and descendant needs to be last combinator) + laterSibling: /^\s*~\s*/, + child: /^\s*>\s*/, + adjacent: /^\s*\+\s*/, + descendant: /^\s/, + + // selectors follow + tagName: /^\s*(\*|[\w\-]+)(\b|$)?/, + id: /^#([\w\-\*]+)(\b|$)/, + className: /^\.([\w\-\*]+)(\b|$)/, + pseudo: /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s)|(?=:))/, + attrPresence: /^\[([\w]+)\]/, + attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/ + }, + + // for Selector.match and Element#match + assertions: { + tagName: function(element, matches) { + return matches[1].toUpperCase() == element.tagName.toUpperCase(); + }, + + className: function(element, matches) { + return Element.hasClassName(element, matches[1]); + }, + + id: function(element, matches) { + return element.id === matches[1]; + }, + + attrPresence: function(element, matches) { + return Element.hasAttribute(element, matches[1]); + }, + + attr: function(element, matches) { + var nodeValue = Element.readAttribute(element, matches[1]); + return Selector.operators[matches[2]](nodeValue, matches[3]); + } + }, + + handlers: { + // UTILITY FUNCTIONS + // joins two collections + concat: function(a, b) { + for (var i = 0, node; node = b[i]; i++) + a.push(node); + return a; + }, + + // marks an array of nodes for counting + mark: function(nodes) { + for (var i = 0, node; node = nodes[i]; i++) + node._counted = true; + return nodes; + }, + + unmark: function(nodes) { + for (var i = 0, node; node = nodes[i]; i++) + node._counted = undefined; + return nodes; + }, + + // mark each child node with its position (for nth calls) + // "ofType" flag indicates whether we're indexing for nth-of-type + // rather than nth-child + index: function(parentNode, reverse, ofType) { + parentNode._counted = true; + if (reverse) { + for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) { + var node = nodes[i]; + if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++; + } + } else { + for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++) + if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++; + } + }, + + // filters out duplicates and extends all nodes + unique: function(nodes) { + if (nodes.length == 0) return nodes; + var results = [], n; + for (var i = 0, l = nodes.length; i < l; i++) + if (!(n = nodes[i])._counted) { + n._counted = true; + results.push(Element.extend(n)); + } + return Selector.handlers.unmark(results); + }, + + // COMBINATOR FUNCTIONS + descendant: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + h.concat(results, node.getElementsByTagName('*')); + return results; + }, + + child: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) { + for (var j = 0, children = [], child; child = node.childNodes[j]; j++) + if (child.nodeType == 1 && child.tagName != '!') results.push(child); + } + return results; + }, + + adjacent: function(nodes) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + var next = this.nextElementSibling(node); + if (next) results.push(next); + } + return results; + }, + + laterSibling: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + h.concat(results, Element.nextSiblings(node)); + return results; + }, + + nextElementSibling: function(node) { + while (node = node.nextSibling) + if (node.nodeType == 1) return node; + return null; + }, + + previousElementSibling: function(node) { + while (node = node.previousSibling) + if (node.nodeType == 1) return node; + return null; + }, + + // TOKEN FUNCTIONS + tagName: function(nodes, root, tagName, combinator) { + tagName = tagName.toUpperCase(); + var results = [], h = Selector.handlers; + if (nodes) { + if (combinator) { + // fastlane for ordinary descendant combinators + if (combinator == "descendant") { + for (var i = 0, node; node = nodes[i]; i++) + h.concat(results, node.getElementsByTagName(tagName)); + return results; + } else nodes = this[combinator](nodes); + if (tagName == "*") return nodes; + } + for (var i = 0, node; node = nodes[i]; i++) + if (node.tagName.toUpperCase() == tagName) results.push(node); + return results; + } else return root.getElementsByTagName(tagName); + }, + + id: function(nodes, root, id, combinator) { + var targetNode = $(id), h = Selector.handlers; + if (!targetNode) return []; + if (!nodes && root == document) return [targetNode]; + if (nodes) { + if (combinator) { + if (combinator == 'child') { + for (var i = 0, node; node = nodes[i]; i++) + if (targetNode.parentNode == node) return [targetNode]; + } else if (combinator == 'descendant') { + for (var i = 0, node; node = nodes[i]; i++) + if (Element.descendantOf(targetNode, node)) return [targetNode]; + } else if (combinator == 'adjacent') { + for (var i = 0, node; node = nodes[i]; i++) + if (Selector.handlers.previousElementSibling(targetNode) == node) + return [targetNode]; + } else nodes = h[combinator](nodes); + } + for (var i = 0, node; node = nodes[i]; i++) + if (node == targetNode) return [targetNode]; + return []; + } + return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : []; + }, + + className: function(nodes, root, className, combinator) { + if (nodes && combinator) nodes = this[combinator](nodes); + return Selector.handlers.byClassName(nodes, root, className); + }, + + byClassName: function(nodes, root, className) { + if (!nodes) nodes = Selector.handlers.descendant([root]); + var needle = ' ' + className + ' '; + for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) { + nodeClassName = node.className; + if (nodeClassName.length == 0) continue; + if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle)) + results.push(node); + } + return results; + }, + + attrPresence: function(nodes, root, attr) { + if (!nodes) nodes = root.getElementsByTagName("*"); + var results = []; + for (var i = 0, node; node = nodes[i]; i++) + if (Element.hasAttribute(node, attr)) results.push(node); + return results; + }, + + attr: function(nodes, root, attr, value, operator) { + if (!nodes) nodes = root.getElementsByTagName("*"); + var handler = Selector.operators[operator], results = []; + for (var i = 0, node; node = nodes[i]; i++) { + var nodeValue = Element.readAttribute(node, attr); + if (nodeValue === null) continue; + if (handler(nodeValue, value)) results.push(node); + } + return results; + }, + + pseudo: function(nodes, name, value, root, combinator) { + if (nodes && combinator) nodes = this[combinator](nodes); + if (!nodes) nodes = root.getElementsByTagName("*"); + return Selector.pseudos[name](nodes, value, root); + } + }, + + pseudos: { + 'first-child': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + if (Selector.handlers.previousElementSibling(node)) continue; + results.push(node); + } + return results; + }, + 'last-child': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + if (Selector.handlers.nextElementSibling(node)) continue; + results.push(node); + } + return results; + }, + 'only-child': function(nodes, value, root) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!h.previousElementSibling(node) && !h.nextElementSibling(node)) + results.push(node); + return results; + }, + 'nth-child': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root); + }, + 'nth-last-child': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, true); + }, + 'nth-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, false, true); + }, + 'nth-last-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, true, true); + }, + 'first-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, "1", root, false, true); + }, + 'last-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, "1", root, true, true); + }, + 'only-of-type': function(nodes, formula, root) { + var p = Selector.pseudos; + return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root); + }, + + // handles the an+b logic + getIndices: function(a, b, total) { + if (a == 0) return b > 0 ? [b] : []; + return $R(1, total).inject([], function(memo, i) { + if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i); + return memo; + }); + }, + + // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type + nth: function(nodes, formula, root, reverse, ofType) { + if (nodes.length == 0) return []; + if (formula == 'even') formula = '2n+0'; + if (formula == 'odd') formula = '2n+1'; + var h = Selector.handlers, results = [], indexed = [], m; + h.mark(nodes); + for (var i = 0, node; node = nodes[i]; i++) { + if (!node.parentNode._counted) { + h.index(node.parentNode, reverse, ofType); + indexed.push(node.parentNode); + } + } + if (formula.match(/^\d+$/)) { // just a number + formula = Number(formula); + for (var i = 0, node; node = nodes[i]; i++) + if (node.nodeIndex == formula) results.push(node); + } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b + if (m[1] == "-") m[1] = -1; + var a = m[1] ? Number(m[1]) : 1; + var b = m[2] ? Number(m[2]) : 0; + var indices = Selector.pseudos.getIndices(a, b, nodes.length); + for (var i = 0, node, l = indices.length; node = nodes[i]; i++) { + for (var j = 0; j < l; j++) + if (node.nodeIndex == indices[j]) results.push(node); + } + } + h.unmark(nodes); + h.unmark(indexed); + return results; + }, + + 'empty': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + // IE treats comments as element nodes + if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue; + results.push(node); + } + return results; + }, + + 'not': function(nodes, selector, root) { + var h = Selector.handlers, selectorType, m; + var exclusions = new Selector(selector).findElements(root); + h.mark(exclusions); + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!node._counted) results.push(node); + h.unmark(exclusions); + return results; + }, + + 'enabled': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!node.disabled) results.push(node); + return results; + }, + + 'disabled': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (node.disabled) results.push(node); + return results; + }, + + 'checked': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (node.checked) results.push(node); + return results; + } + }, + + operators: { + '=': function(nv, v) { return nv == v; }, + '!=': function(nv, v) { return nv != v; }, + '^=': function(nv, v) { return nv.startsWith(v); }, + '$=': function(nv, v) { return nv.endsWith(v); }, + '*=': function(nv, v) { return nv.include(v); }, + '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); }, + '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); } + }, + + matchElements: function(elements, expression) { + var matches = new Selector(expression).findElements(), h = Selector.handlers; + h.mark(matches); + for (var i = 0, results = [], element; element = elements[i]; i++) + if (element._counted) results.push(element); + h.unmark(matches); + return results; + }, + + findElement: function(elements, expression, index) { + if (Object.isNumber(expression)) { + index = expression; expression = false; + } + return Selector.matchElements(elements, expression || '*')[index || 0]; + }, + + findChildElements: function(element, expressions) { + var exprs = expressions.join(','), expressions = []; + exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) { + expressions.push(m[1].strip()); + }); + var results = [], h = Selector.handlers; + for (var i = 0, l = expressions.length, selector; i < l; i++) { + selector = new Selector(expressions[i].strip()); + h.concat(results, selector.findElements(element)); + } + return (l > 1) ? h.unique(results) : results; + } +}); + +function $$() { + return Selector.findChildElements(document, $A(arguments)); +} +var Form = { + reset: function(form) { + $(form).reset(); + return form; + }, + + serializeElements: function(elements, options) { + if (typeof options != 'object') options = { hash: !!options }; + else if (options.hash === undefined) options.hash = true; + var key, value, submitted = false, submit = options.submit; + + var data = elements.inject({ }, function(result, element) { + if (!element.disabled && element.name) { + key = element.name; value = $(element).getValue(); + if (value != null && (element.type != 'submit' || (!submitted && + submit !== false && (!submit || key == submit) && (submitted = true)))) { + if (key in result) { + // a key is already present; construct an array of values + if (!Object.isArray(result[key])) result[key] = [result[key]]; + result[key].push(value); + } + else result[key] = value; + } + } + return result; + }); + + return options.hash ? data : Object.toQueryString(data); + } +}; + +Form.Methods = { + serialize: function(form, options) { + return Form.serializeElements(Form.getElements(form), options); + }, + + getElements: function(form) { + return $A($(form).getElementsByTagName('*')).inject([], + function(elements, child) { + if (Form.Element.Serializers[child.tagName.toLowerCase()]) + elements.push(Element.extend(child)); + return elements; + } + ); + }, + + getInputs: function(form, typeName, name) { + form = $(form); + var inputs = form.getElementsByTagName('input'); + + if (!typeName && !name) return $A(inputs).map(Element.extend); + + for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) { + var input = inputs[i]; + if ((typeName && input.type != typeName) || (name && input.name != name)) + continue; + matchingInputs.push(Element.extend(input)); + } + + return matchingInputs; + }, + + disable: function(form) { + form = $(form); + Form.getElements(form).invoke('disable'); + return form; + }, + + enable: function(form) { + form = $(form); + Form.getElements(form).invoke('enable'); + return form; + }, + + findFirstElement: function(form) { + var elements = $(form).getElements().findAll(function(element) { + return 'hidden' != element.type && !element.disabled; + }); + var firstByIndex = elements.findAll(function(element) { + return element.hasAttribute('tabIndex') && element.tabIndex >= 0; + }).sortBy(function(element) { return element.tabIndex }).first(); + + return firstByIndex ? firstByIndex : elements.find(function(element) { + return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase()); + }); + }, + + focusFirstElement: function(form) { + form = $(form); + form.findFirstElement().activate(); + return form; + }, + + request: function(form, options) { + form = $(form), options = Object.clone(options || { }); + + var params = options.parameters, action = form.readAttribute('action') || ''; + if (action.blank()) action = window.location.href; + options.parameters = form.serialize(true); + + if (params) { + if (Object.isString(params)) params = params.toQueryParams(); + Object.extend(options.parameters, params); + } + + if (form.hasAttribute('method') && !options.method) + options.method = form.method; + + return new Ajax.Request(action, options); + } +}; + +/*--------------------------------------------------------------------------*/ + +Form.Element = { + focus: function(element) { + $(element).focus(); + return element; + }, + + select: function(element) { + $(element).select(); + return element; + } +}; + +Form.Element.Methods = { + serialize: function(element) { + element = $(element); + if (!element.disabled && element.name) { + var value = element.getValue(); + if (value != undefined) { + var pair = { }; + pair[element.name] = value; + return Object.toQueryString(pair); + } + } + return ''; + }, + + getValue: function(element) { + element = $(element); + var method = element.tagName.toLowerCase(); + return Form.Element.Serializers[method](element); + }, + + setValue: function(element, value) { + element = $(element); + var method = element.tagName.toLowerCase(); + Form.Element.Serializers[method](element, value); + return element; + }, + + clear: function(element) { + $(element).value = ''; + return element; + }, + + present: function(element) { + return $(element).value != ''; + }, + + activate: function(element) { + element = $(element); + try { + element.focus(); + if (element.select && (element.tagName.toLowerCase() != 'input' || + !['button', 'reset', 'submit'].include(element.type))) + element.select(); + } catch (e) { } + return element; + }, + + disable: function(element) { + element = $(element); + element.blur(); + element.disabled = true; + return element; + }, + + enable: function(element) { + element = $(element); + element.disabled = false; + return element; + } +}; + +/*--------------------------------------------------------------------------*/ + +var Field = Form.Element; +var $F = Form.Element.Methods.getValue; + +/*--------------------------------------------------------------------------*/ + +Form.Element.Serializers = { + input: function(element, value) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + return Form.Element.Serializers.inputSelector(element, value); + default: + return Form.Element.Serializers.textarea(element, value); + } + }, + + inputSelector: function(element, value) { + if (value === undefined) return element.checked ? element.value : null; + else element.checked = !!value; + }, + + textarea: function(element, value) { + if (value === undefined) return element.value; + else element.value = value; + }, + + select: function(element, index) { + if (index === undefined) + return this[element.type == 'select-one' ? + 'selectOne' : 'selectMany'](element); + else { + var opt, value, single = !Object.isArray(index); + for (var i = 0, length = element.length; i < length; i++) { + opt = element.options[i]; + value = this.optionValue(opt); + if (single) { + if (value == index) { + opt.selected = true; + return; + } + } + else opt.selected = index.include(value); + } + } + }, + + selectOne: function(element) { + var index = element.selectedIndex; + return index >= 0 ? this.optionValue(element.options[index]) : null; + }, + + selectMany: function(element) { + var values, length = element.length; + if (!length) return null; + + for (var i = 0, values = []; i < length; i++) { + var opt = element.options[i]; + if (opt.selected) values.push(this.optionValue(opt)); + } + return values; + }, + + optionValue: function(opt) { + // extend element because hasAttribute may not be native + return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; + } +}; + +/*--------------------------------------------------------------------------*/ + +Abstract.TimedObserver = Class.create(PeriodicalExecuter, { + initialize: function($super, element, frequency, callback) { + $super(callback, frequency); + this.element = $(element); + this.lastValue = this.getValue(); + }, + + execute: function() { + var value = this.getValue(); + if (Object.isString(this.lastValue) && Object.isString(value) ? + this.lastValue != value : String(this.lastValue) != String(value)) { + this.callback(this.element, value); + this.lastValue = value; + } + } +}); + +Form.Element.Observer = Class.create(Abstract.TimedObserver, { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.Observer = Class.create(Abstract.TimedObserver, { + getValue: function() { + return Form.serialize(this.element); + } +}); + +/*--------------------------------------------------------------------------*/ + +Abstract.EventObserver = Class.create({ + initialize: function(element, callback) { + this.element = $(element); + this.callback = callback; + + this.lastValue = this.getValue(); + if (this.element.tagName.toLowerCase() == 'form') + this.registerFormCallbacks(); + else + this.registerCallback(this.element); + }, + + onElementEvent: function() { + var value = this.getValue(); + if (this.lastValue != value) { + this.callback(this.element, value); + this.lastValue = value; + } + }, + + registerFormCallbacks: function() { + Form.getElements(this.element).each(this.registerCallback, this); + }, + + registerCallback: function(element) { + if (element.type) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + Event.observe(element, 'click', this.onElementEvent.bind(this)); + break; + default: + Event.observe(element, 'change', this.onElementEvent.bind(this)); + break; + } + } + } +}); + +Form.Element.EventObserver = Class.create(Abstract.EventObserver, { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.EventObserver = Class.create(Abstract.EventObserver, { + getValue: function() { + return Form.serialize(this.element); + } +}); +if (!window.Event) var Event = { }; + +Object.extend(Event, { + KEY_BACKSPACE: 8, + KEY_TAB: 9, + KEY_RETURN: 13, + KEY_ESC: 27, + KEY_LEFT: 37, + KEY_UP: 38, + KEY_RIGHT: 39, + KEY_DOWN: 40, + KEY_DELETE: 46, + KEY_HOME: 36, + KEY_END: 35, + KEY_PAGEUP: 33, + KEY_PAGEDOWN: 34, + KEY_INSERT: 45, + + cache: { }, + + relatedTarget: function(event) { + var element; + switch(event.type) { + case 'mouseover': element = event.fromElement; break; + case 'mouseout': element = event.toElement; break; + default: return null; + } + return Element.extend(element); + } +}); + +Event.Methods = (function() { + var isButton; + + if (Prototype.Browser.IE) { + var buttonMap = { 0: 1, 1: 4, 2: 2 }; + isButton = function(event, code) { + return event.button == buttonMap[code]; + }; + + } else if (Prototype.Browser.WebKit) { + isButton = function(event, code) { + switch (code) { + case 0: return event.which == 1 && !event.metaKey; + case 1: return event.which == 1 && event.metaKey; + default: return false; + } + }; + + } else { + isButton = function(event, code) { + return event.which ? (event.which === code + 1) : (event.button === code); + }; + } + + return { + isLeftClick: function(event) { return isButton(event, 0) }, + isMiddleClick: function(event) { return isButton(event, 1) }, + isRightClick: function(event) { return isButton(event, 2) }, + + element: function(event) { + var node = Event.extend(event).target; + return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node); + }, + + findElement: function(event, expression) { + var element = Event.element(event); + return element.match(expression) ? element : element.up(expression); + }, + + pointer: function(event) { + return { + x: event.pageX || (event.clientX + + (document.documentElement.scrollLeft || document.body.scrollLeft)), + y: event.pageY || (event.clientY + + (document.documentElement.scrollTop || document.body.scrollTop)) + }; + }, + + pointerX: function(event) { return Event.pointer(event).x }, + pointerY: function(event) { return Event.pointer(event).y }, + + stop: function(event) { + Event.extend(event); + event.preventDefault(); + event.stopPropagation(); + event.stopped = true; + } + }; +})(); + +Event.extend = (function() { + var methods = Object.keys(Event.Methods).inject({ }, function(m, name) { + m[name] = Event.Methods[name].methodize(); + return m; + }); + + if (Prototype.Browser.IE) { + Object.extend(methods, { + stopPropagation: function() { this.cancelBubble = true }, + preventDefault: function() { this.returnValue = false }, + inspect: function() { return "[object Event]" } + }); + + return function(event) { + if (!event) return false; + if (event._extendedByPrototype) return event; + + event._extendedByPrototype = Prototype.emptyFunction; + var pointer = Event.pointer(event); + Object.extend(event, { + target: event.srcElement, + relatedTarget: Event.relatedTarget(event), + pageX: pointer.x, + pageY: pointer.y + }); + return Object.extend(event, methods); + }; + + } else { + Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__; + Object.extend(Event.prototype, methods); + return Prototype.K; + } +})(); + +Object.extend(Event, (function() { + var cache = Event.cache; + + function getEventID(element) { + if (element._eventID) return element._eventID; + arguments.callee.id = arguments.callee.id || 1; + return element._eventID = ++arguments.callee.id; + } + + function getDOMEventName(eventName) { + if (eventName && eventName.include(':')) return "dataavailable"; + return eventName; + } + + function getCacheForID(id) { + return cache[id] = cache[id] || { }; + } + + function getWrappersForEventName(id, eventName) { + var c = getCacheForID(id); + return c[eventName] = c[eventName] || []; + } + + function createWrapper(element, eventName, handler) { + var id = getEventID(element); + var c = getWrappersForEventName(id, eventName); + if (c.pluck("handler").include(handler)) return false; + + var wrapper = function(event) { + if (!Event || !Event.extend || + (event.eventName && event.eventName != eventName)) + return false; + + Event.extend(event); + handler.call(element, event) + }; + + wrapper.handler = handler; + c.push(wrapper); + return wrapper; + } + + function findWrapper(id, eventName, handler) { + var c = getWrappersForEventName(id, eventName); + return c.find(function(wrapper) { return wrapper.handler == handler }); + } + + function destroyWrapper(id, eventName, handler) { + var c = getCacheForID(id); + if (!c[eventName]) return false; + c[eventName] = c[eventName].without(findWrapper(id, eventName, handler)); + } + + function destroyCache() { + for (var id in cache) + for (var eventName in cache[id]) + cache[id][eventName] = null; + } + + if (window.attachEvent) { + window.attachEvent("onunload", destroyCache); + } + + return { + observe: function(element, eventName, handler) { + element = $(element); + var name = getDOMEventName(eventName); + + var wrapper = createWrapper(element, eventName, handler); + if (!wrapper) return element; + + if (element.addEventListener) { + element.addEventListener(name, wrapper, false); + } else { + element.attachEvent("on" + name, wrapper); + } + + return element; + }, + + stopObserving: function(element, eventName, handler) { + element = $(element); + var id = getEventID(element), name = getDOMEventName(eventName); + + if (!handler && eventName) { + getWrappersForEventName(id, eventName).each(function(wrapper) { + element.stopObserving(eventName, wrapper.handler); + }); + return element; + + } else if (!eventName) { + Object.keys(getCacheForID(id)).each(function(eventName) { + element.stopObserving(eventName); + }); + return element; + } + + var wrapper = findWrapper(id, eventName, handler); + if (!wrapper) return element; + + if (element.removeEventListener) { + element.removeEventListener(name, wrapper, false); + } else { + element.detachEvent("on" + name, wrapper); + } + + destroyWrapper(id, eventName, handler); + + return element; + }, + + fire: function(element, eventName, memo) { + element = $(element); + if (element == document && document.createEvent && !element.dispatchEvent) + element = document.documentElement; + + if (document.createEvent) { + var event = document.createEvent("HTMLEvents"); + event.initEvent("dataavailable", true, true); + } else { + var event = document.createEventObject(); + event.eventType = "ondataavailable"; + } + + event.eventName = eventName; + event.memo = memo || { }; + + if (document.createEvent) { + element.dispatchEvent(event); + } else { + element.fireEvent(event.eventType, event); + } + + return event; + } + }; +})()); + +Object.extend(Event, Event.Methods); + +Element.addMethods({ + fire: Event.fire, + observe: Event.observe, + stopObserving: Event.stopObserving +}); + +Object.extend(document, { + fire: Element.Methods.fire.methodize(), + observe: Element.Methods.observe.methodize(), + stopObserving: Element.Methods.stopObserving.methodize() +}); + +(function() { + /* Support for the DOMContentLoaded event is based on work by Dan Webb, + Matthias Miller, Dean Edwards and John Resig. */ + + var timer, fired = false; + + function fireContentLoadedEvent() { + if (fired) return; + if (timer) window.clearInterval(timer); + document.fire("dom:loaded"); + fired = true; + } + + if (document.addEventListener) { + if (Prototype.Browser.WebKit) { + timer = window.setInterval(function() { + if (/loaded|complete/.test(document.readyState)) + fireContentLoadedEvent(); + }, 0); + + Event.observe(window, "load", fireContentLoadedEvent); + + } else { + document.addEventListener("DOMContentLoaded", + fireContentLoadedEvent, false); + } + + } else { + document.write(" + + +

    '.$message.'

    + ' . $help_guide; + echo $out; + } + + /** + * top2 : alias to top() + * @param $message: message title + * @param $hp: help file + * @param $$hp2 = NULL : gaslight help file + * + * @return + * @access + **/ + function top2($message, $hp,$hp2 = NULL) { + // make this an alias to top() + // by calling top instead of adding extra code + top($message, $hp, $hp2); + + } + + /******************************************************************************** + * + * DO NOT EDIT THIS SECTION + * + ********************************************************************************/ + + if ($DEBUG) { + echo '
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

    Portable Site Data - setup.phtml

    CVS Version Id:$Id: setup_functions.phtml,v 1.2 2009/12/15 20:18:15 jamie Exp $
    SITENAME'.SITENAME.'
    BASE'.BASE.'
    UP_BASE'.UP_BASE.'
    HELP_BASE'.HELP_BASE.'
    IMG_BASE'.IMG_BASE.'
    URL_BASE'.URL_BASE.'
    CONN_STR'.CONN_STR.'
    STYLE'.STYLE.'
    ORIGINAL_PATH'.ORIGINAL_PATH.'
    RESIZED_PATH'.RESIZED_PATH.'
    MIDSIZED_PATH'.MIDSIZED_PATH.'
    THUMB_PATH'.THUMB_PATH.'
    ORIGINAL'.ORIGINAL.'
    RESIZED'.RESIZED.'
    MIDSIZED'.MIDSIZED.'
    THUMB'.THUMB.'
    $CALLED_FROM_DIR'.$CALLED_FROM_DIR.' 
    $BASE_PATH'.$BASE_PATH.'
    $BASE_URL'.$BASE_URL.'
    $BASE_SECURE_URL'.$BASE_SECURE_URL.'
    +   +

    +


    +

    +

    + '; + } + + /** + * date_entry : Generate the select boxes for date entry + * month-day-year as drop down select + * @param $month: + * @param $day: + * @param $year: + * @param $month_name: name of select month + * @param $day_name: name of select day + * @param $$year_name : name of select year + * + * @return + * @access + **/ + function date_entry($month, $day, $year, $month_name, $day_name, $year_name, $onChange = NULL) + { + $cur_date = getdate(); + + if ($month == '') { + $month = $cur_date['mon']; + } + if($day == '') { + $day = $cur_date['mday']; + } + if($year == '') { + $year = $cur_date['year']; + } + $date = '"; + for ($i = 1; $i <= 12; ++$i) { + $time .= "
+ +
  • Click "Finish"
  • +
  • Click on the "Tools" menu then "Accounts..."
  • +
  • Click on the desired E-Mail account then click "Properties"
  • +
  • Click on the "Advanced" tab at the top
  • +
  • Verify and correct the following settings +
  • "Incoming mail (pop3):" should be "110"
  • +
  • "Outgoing mail (smtp):" should be "2500"
  • +
  • Both "This server requires a secure connection (ssl)" should NOT be checked
  • +
  • Click "OK" then "Close" + + +

     

    +


    +

     

    + + +

    Use this procedure if you are using Mozilla Thunderbird

    + +
      +
    1. Start Thunderbird
    2. +
    3. Click on "Tools" menu then "Account Settings..."
    4. +
    5. Click on Add account below the left window
    6. +
    7. select "Email account", then click "Next"
    8. +
    9. On the "Identity" page, Enter the following settings +
        +
      • "Your Name:" is the name that you want people to see when they recieve a E-mail from you
      • +
      • "Email Address:" should be your complete E-Mail address including domain
      • +
      +
    10. +
    11. Click "Next"
    12. +
    13. On the "Server information" page, Enter the following settings +
        +
      • "type of incoming server" should be "POP"
      • +
      • "Incoming Server:" should be "pop.{domain name}"
      • +
      • "Outgoing Server:" should be "smtp.{domain name}"
      • +
      +
    14. +
    15. Click "Next"
    16. +
    17. On the "User Names" page, Enter the following settings +
        +
      • "Incoming User Name:" should be your complete E-Mail address including domain
      • +
      • "Outgoing User Name:" should be your complete E-Mail address including domain
      • +
      +
    18. +
    19. Click "Next"
    20. +
    21. On the "Account Name" page, Enter the following settings +
        +
      • "Account Name:" should be your complete E-Mail address including domain
      • +
      +
    22. +
    23. Click "Next"
    24. +
    25. Click "Finish"
    26. +
    27. Click "OK"
    28. +
    29. Click on "Tools" menu then "Account Settings..."
    30. +
    31. Click on "Outgoing Server (SMTP)" in the left window
    32. +
    33. Click on the E-Mail server that includes "(Default)" then click "Edit"
    34. +
    35. Verify and correct as necessary the following settings +
        +
      • "Server Name:" should be "smtp.{domain name}"
      • +
      • "Port:" should be 2500
      • +
      • "Use name and password" should be checked
      • +
      • "User Name:" should be your complete E-Mail address including domain
      • +
      • "Use secure connection:" "No" should be selected
      • +
      +
    36. +
    37. Click "OK" then click "OK"
    38. +
    + +

     

    +


    +

     

    + + +

    Use this procedure if you are using Apple Mail

    + +
      +
    1. Start Apple Mail
    2. +
    3. Click on the "Mail" menu then click "Preferences"
    4. +
    5. Click on "Accounts" at the top
    6. +
    7. Click on the "+" sign at the bottom of the page
    8. +
    9. Click the "Account Information" Tab
    10. +
    11. Enter the following settings +
        +
      • "Account Type:" should be "POP"
      • +
      • "Description:" should be your full E-Mail address including domain
      • +
      • "E-Mail Address:" should be your full E-Mail address including domain
      • +
      • "Full Name:" should be your the name you want people to see when they recieve an email from you
      • +
      • "Incoming Mail Server:" should be "pop.{domain name}"
      • +
      • "User Name:" should be your full E-Mail address including domain
      • +
      +
    12. +
    13. Click on the "Outgoing Mail Server (SMTP):" list and select "Edit Server List"
    14. +
    15. Select the current SMTP server from the drop down list
    16. +
    17. Select the "Account Information" tab
    18. +
    19. "Server Name:" should be "smtp.{domain name}"
    20. +
    21. Click on the "Advanced" tab
    22. +
    23. Verify and correct as necessary the following settings +
        +
      • "Server Port:" should be 2500
      • +
      • "Use Secure Sockets Layer (SSL)" should NOT be clicked
      • +
      • "Authentication:" should be "Password"
      • +
      +
    24. +
    25. Click "Ok", If it asks you to save click "Save"
    26. +
    27. Close the Preferences panel, selecting "Save" from the dialogue box that appears.
    28. +
    + +

     

    +


    +

     

    + + +

    If you have other E-Mail client software not listed above

    + +

    Verify and correct as necessary the following settings

    +
      +
    • Incoming mail server should be "pop.{domain name}"
    • +
    • Outgoing mail server should be "smtp.{domain name}"
    • +
    • Outgoing port should be "2500"
    • +
    • SMTP Authentication should be enabled
    • +
    + + + + diff --git a/webmail/spam.html b/webmail/spam.html new file mode 100755 index 0000000..a7dbefd --- /dev/null +++ b/webmail/spam.html @@ -0,0 +1,242 @@ + + + +Gaslight Media Anti-SPAM Services + + + + + + +
    +
    + logo (5K) +

    ANTI-SPAM

    +
    +

    We're moving to a new E-Mail system for faster delivery, greater reliability, and exciting new features!

    + + + +
    + + + +

    Customer Mail Software Settings for New Gaslight Media Mail Service

    + +

    Use these procedures ONLY IF YOU HAVE BEEN NOTIFIED that your E-Mail account is ready to move to our + new E-Mail services.

    + +

    Please follow the procedure below carefully to configure your E-Mail account to use our new E-Mail + services. You should only need to make the changes requested in the procedure for the E-Mail software + you are using.

    + +

    For these procedures your full E-Mail address should look something like this + +

    jim@gaslightmedia.com
    +

    + +

    The part of your E-Mail address after the "@" sign is the "Domain Name". Please enter this + wherever you see "{domain name}" in the procedure below. For example, the server settings + for the "jim@gaslightmedia.com" account would be... + +

    Incoming mail server: pop.gaslightmedia.com
    + Outgoing mail server: smtp.gaslightmeda.com
    +

    + +

    Please call Gaslight Media Technical Support if you have any problems with these settings or are unable to send or receive mail using our new E-Mail services. +

    Gaslight Media Technical Support: 231-487-0692
    +
    After Hours Technical Support: 231-487-9773
    +

    + +

    Select the proceedure for your E-Mail software

    + + +

     

    +


    +

     

    + + +

    Use this procedure if you are using Outlook 2003 or Outlook 2007

    + +
      +
    1. Start Outlook
    2. +
    3. Click on the "Tools" menu then "E-mail Accounts"
    4. +
    5. Select "View or change existing e-mail accounts" then click "Next"
    6. +
    7. Select the desired E-Mail account then click "Change"
    8. +
    9. Verify and correct as necessary the following settings +
        +
      • "E-mail Address:" should have your complete E-Mail address including domain
      • +
      • "Incoming mail server (POP3):" should be "pop.{domain name}"
      • +
      • "Outgoing mail server (SMTP):" should be "smtp.{domain name}"
      • +
      • "User Name:" should be your complete E-Mail address including domain
      • +
      • "Password:" your current password setting should be correct
      • +
      • "Log on using Secure Password Authentication (SPA)" should NOT be checked
      • +
      +
    10. +
    11. Click "More Settings..."
    12. +
    13. Select the "Outgoing Server" tab
    14. +
    15. Verify that the following items are checked +
        +
      • "My outgoing server (SMTP) requires authentication"
      • +
      • "Use same settings as my incoming mail server"
      • +
      +
    16. +
    17. Click on the "Advanced" tab
    18. +
    19. Change "Outgoing server (SMTP):" to 2500
    20. +
    21. Click OK.
    22. +
    23. Click "Next" then "Finish"
    24. +
    + +

     

    +


    +

     

    + + +

    Use this procedure if you are using Outlook Express

    + +
      +
    1. Start Outlook Express
    2. +
    3. Click on "Tools" menu then "Accounts..."
    4. +
    5. Click on the desired E-Mail account then click "Properties"
    6. +
    7. Click on the "General" tab at the top
    8. +
    9. "E-Mail address:" should be your complete E-Mail address including domain
    10. +
    11. Click on the "Servers" tab at the top
    12. +
    13. Verify and correct as necessary the following settings +
        +
      • "Incoming mail (POP3):" should be "pop.{domain name}"
      • +
      • "Outgoing mail (SMTP):" should be "smtp.{domain name}"
      • +
      • "Account name:" should be your complete E-Mail address including domain
      • +
      • "Log on using Secure Password Authentication" should NOT be checked
      • +
      • "My server requires authentication" should be checked
      • +
      +
    14. +
    15. Click on the "Settings..." button
    16. +
    17. "Use same settings as my incoming mail server" should be selected
    18. +
    19. Click "OK"
    20. +
    21. Click on "Advanced" tab at the top
    22. +
    23. Verify and correct as necessary the following settings +
        +
      • "Outgoing mail (SMTP):" should be 2500
      • +
      • "Incoming mail (POP3):" should be 110
      • +
      +
    24. +
    25. Both "This server requires a secure connection (SSL)" should NOT be checked
    26. +
    27. Click "OK" then "Close"
    28. +
    + +

     

    +


    +

     

    + + +

    Use this procedure if you are using Mozilla Thunderbird

    + +
      +
    1. Start Thunderbird
    2. +
    3. Click on "Tools" menu then "Account Settings..."
    4. +
    5. Click on the desired E-Mail account in the left window
    6. +
    7. If there is a small "+" to the left of the account, click on that "+"
    8. +
    9. Verify and correct as necessary the following settings +
        +
      • "Email Address:" should be your complete E-Mail address including domain
      • +
      • "Outgoing Server (SMTP):" should be "Use Default Server"
      • +
      +
    10. +
    11. Click on "Server Settings" under your selected account in the left window
    12. +
    13. Verify and correct as necessary the following settings +
        +
      • "Server Name:" should be "pop.{domain name}"
      • +
      • "User Name:" should be your complete E-Mail address including domain
      • +
      +
    14. +
    15. Click on "Outgoing Server (SMTP)" in the left window
    16. +
    17. Click on the E-Mail server that includes "(Default)" then click "Edit"
    18. +
    19. Verify and correct as necessary the following settings +
        +
      • "Server Name:" should be "smtp.{domain name}"
      • +
      • "Port:" should be 2500
      • +
      • "Use name and password" should be checked
      • +
      • "User Name:" should be your complete E-Mail address including domain
      • +
      • "Use secure connection:" "No" should be selected
      • +
      +
    20. +
    21. Click "OK" then click "OK"
    22. +
    + +

     

    +


    +

     

    + + +

    Use this procedure if you are using Apple Mail

    + +
      +
    1. Start Apple Mail
    2. +
    3. Click on the "Mail" menu then click "Preferences"
    4. +
    5. Click on "Accounts" at the top
    6. +
    7. Click on the desired E-Mail account at the left
    8. +
    9. Click the "Account Information" Tab
    10. +
    11. Verify and correct as necessary the following settings +
        +
      • "E-Mail Address:" should be your full E-Mail address including domain
      • +
      • "Incoming Mail Server:" should be "pop.{domain name}"
      • +
      • "User Name:" should be your full E-Mail address including domain
      • +
      +
    12. +
    13. Click on the "Outgoing Mail Server (SMTP):" list and select "Edit Server List"
    14. +
    15. Select the current SMTP server from the drop down list
    16. +
    17. Select the "Account Information" tab
    18. +
    19. "Server Name:" should be "smtp.{domain name}"
    20. +
    21. Click on the "Advanced" tab
    22. +
    23. Verify and correct as necessary the following settings +
        +
      • "Server Port:" should be 2500
      • +
      • "Use Secure Sockets Layer (SSL)" should NOT be clicked
      • +
      • "Authentication:" should be "Password"
      • +
      +
    24. +
    25. Click "Ok", If it asks you to save click "Save"
    26. +
    27. Close the Preferences panel, selecting "Save" from the dialogue box that appears.
    28. +
    + +

     

    +


    +

     

    + + +

    If you have other E-Mail client software not listed above

    + +

    Verify and correct as necessary the following settings

    +
      +
    • Incoming mail server should be "pop.{domain name}"
    • +
    • Outgoing mail server should be "smtp.{domain name}"
    • +
    • Outgoing port should be "2500"
    • +
    • SMTP Authentication should be enabled
    • +
    +
    +
    + + diff --git a/webmail/styles.css b/webmail/styles.css new file mode 100755 index 0000000..2dc8019 --- /dev/null +++ b/webmail/styles.css @@ -0,0 +1,126 @@ +body { + margin: 0; + padding: 0; + text-align: center; + font-family: arial, sans-serif; + font-size: 12px; + background: #C2D9FF; +} +a:link {color: #1D58A5; } +a:visited {color: #1D58A5; } +a:hover {color: #000; } +a:active {color: #1D58A5; } + +img {border: 0; display: block;} +#wrapper { + width: 760px; + margin: 0 auto; + text-align: left; + background: white; + height: 1%; + overflow: hidden; + } +#top { + position: relative; + height: 1%; + overflow: hidden; + padding-bottom: 10px; + } +#top img { + float: left; + position: relative; + margin: 20px 0 0 40px; + } +#top h1 { + color: #1d58a5; + text-transform: uppercase; + font-size: 22px; + position: absolute; + bottom: 10px; + right: 40px; + } + +#intro { + margin: 1em 40px; + border: 2px dashed #1d58a5; + background: #eee; + padding: 15px; + font-size: 1.2em; + } +#instructions { + margin: 0 40px; + clear: both; + padding-top: 1em; + } +#instructions h2 {font-size: 18px; color: #3B74BF; } +#instructions h3 {font-size: 16px; color: #3B74BF;} + + +#column1{ + width: 318px; + float: left; + position: relative; + background: #fff; + } +#column2 { + width: 318px; + float: right; + position: relative; + background: #fff; + } + + +#column1 { + margin: 10px 20px 10px 40px; + display: inline; + } +#column2 {margin: 10px 40px 10px 20px;} + +#column1 h2, #column2 h2 { + background-color: #1d58a5; + background-color: #3B74BF; + color: white; + font-size: 1.5em; + margin: 0 0 10px 0; + padding: 10px; + position: relative; + } +#column1 a, #column2 a { + color: black; + cursor: hand; + cursor: pointer; + text-decoration: none; + display: block; + } +/* Header :hover */ +#column1 a:hover h2, +#column2 a:hover h2 { + background-color: #E25D21; + background-color: #FF854F; + } + +/* Screenshot centering */ +#column1 img, +#column2 img { + margin: 0 auto; + } +/* Coulmn paragraphs */ +#column1 p, +#column2 p { + margin: 1em 20px; + } + +.c-off {border: 1px solid #FF854F;} +.c-on {border: 1px solid #FF854F;} + +p#bottom { + margin: 1em 40px; + padding: 10px; + font-size: 1.1em; + clear: both; + } +.warning { + color: #e25d21; + font-weight: bold; + } + diff --git a/webmail/webadmin.html b/webmail/webadmin.html new file mode 100755 index 0000000..e4b9269 --- /dev/null +++ b/webmail/webadmin.html @@ -0,0 +1,166 @@ + + + +Gaslight Media Email Services + + + + + + +
    +
    + logo (5K) +

    WEBADMIN Help

    +
    +
    + + + +

    Webadmin for Gaslight Media Mail Service

    + +

    Please call Gaslight Media Technical Support if you have any problems with these settings or are unable to send or receive mail using our new E-Mail services. +

    Gaslight Media Technical Support: 231-487-0692
    +

    + +

    Select a proceedure

    + + +

     

    +


    +

     

    + + +

    Adding an E-mail account to your domain

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using suplied user name and password
    4. +
    5. Click on settings on the top of the page
    6. +
    7. Click on "Email Account management"
    8. +
    9. Click on "Add email account" button
    10. +
    11. Complete the form with following +
        +
      • "Username:" has to be the complete E-Mail address including domain
      • +
      • "Password:" Must be a min. of 6 char. and include at least 1 number and one letter
      • +
      • "First Name:" this will be included in the signiture on the bottom of E-mails sent from webmail
      • +
      • "Lasy Name:" this will be included in the signiture on the bottom of E-mails sent from webmail
      • +
      • All other settings are optional
      • +
      +
    12. +
    13. Click "Create a Gaslight Media Sub-Account"
    14. +
    + +

     

    +


    +

     

    + + +

    Remove an E-mail account from your domain

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using suplied user name and password
    4. +
    5. Click on settings on the top of the page
    6. +
    7. Click on "Email Account management"
    8. +
    9. Check the account(s) you want to delete
    10. +
    11. Click "termanate" at the bottom of the page
    12. +
    13. Check the "Terminate user(s) and all data immediately"
    14. +
    15. Click "Yes"
    16. +
    + +

     

    +


    +

     

    + + +

    Change a password for an E-mail account in your domain

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using suplied user name and password
    4. +
    5. Click on settings on the top of the page
    6. +
    7. Click on "Email Account management"
    8. +
    9. Check the account you want to Change
    10. +
    11. Click "edit" at the bottom of the page
    12. +
    13. Enter the new password in the "Password:" field
    14. +
    15. Click "Edit Gaslight Media Sub-Account"
    16. +
    + +

     

    +


    +

     

    + + +

    Change a password for the Admin account on your domain

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using suplied user name and password
    4. +
    5. Click on settings on the top of the page
    6. +
    7. Click on "Account Maintenance"
    8. +
    9. Click "Change Password & Secret Question/Answer"
    10. +
    11. Complete the form with following +
        +
      • "Old Password:" enter your existing password
      • +
      • "New Password:" Must be a min. of 6 char. and include at least 1 number and one letter
      • +
      • "Re-type New Password:" For verification
      • +
      +
    12. +
    13. Click "Update Password & Secret Question"
    14. +
    + +

     

    +


    +

     

    + + +

    Add an Alias/Forwarder

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using suplied user name and password
    4. +
    5. Click on settings on the top of the page
    6. +
    7. Click on "Forwards, Autorespond, Lists"
    8. +
    9. Click on "Mail Forwarders"
    10. +
    11. Click on "Add a new mail forwarder to a domain"
    12. +
    13. Complete the form with following +
        +
      • "Mail Forwarder Name:" The user part of the email you want forwarded
      • +
      • "Domain" Select the domain you want it added to
      • +
      • "Email Address to Forward to:" where you want the mail sent to
      • +
      +
    14. +
    15. Click "Add Mail Forwarder"
    16. +
    + +

     

    +


    +

     

    + + +

    Remove an Alias/Forwarder

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using suplied user name and password
    4. +
    5. Click on settings on the top of the page
    6. +
    7. Click on "Forwards, Autorespond, Lists"
    8. +
    9. Click on "Mail Forwarders"
    10. +
    11. Check the account(s) you want to delete
    12. +
    13. Click "Delete" at the bottom of the page
    14. +
    15. Click "Yes"
    16. +
    + +
    +
    + + diff --git a/webmail/webuser.html b/webmail/webuser.html new file mode 100755 index 0000000..be2f8b0 --- /dev/null +++ b/webmail/webuser.html @@ -0,0 +1,147 @@ + + + +Gaslight Media Email Services + + + + + + +
    +
    + logo (5K) +

    WEBADMIN Help

    +
    +
    + + + +

    Webmail for Gaslight Media Mail Service

    + +

    Please call Gaslight Media Technical Support if you have any problems with these settings or are unable to send or receive mail using our new E-Mail services. +

    Gaslight Media Technical Support: 231-487-0692
    +

    + +

    Select a proceedure

    + + +

     

    +


    +

     

    + + +

    Checking your E-mail online

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using your email address and password
    4. +
    5. Click on "mail" on the top of the page
    6. +
    + +

     

    +


    +

     

    + + +

    Check your spam online

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using your email address and password
    4. +
    5. Click on "mail" on the top of the page
    6. +
    7. Click on "spam" on the left bar of the page
    8. +
    + +

     

    +


    +

     

    + + +

    Mark a message that was determined to be spam as not spam

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using your email address and password
    4. +
    5. Click on "mail" on the top of the page
    6. +
    7. Click on "spam" on the left bar of the page
    8. +
    9. Select the message you want to mark as not spam
    10. +
    11. At the bottom of the page click the "preform this action" drop down box and select "Mark checked as not spam"
    12. +
    + +

     

    +


    +

     

    + + +

    Setup an out of office message

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using your email address and password
    4. +
    5. Click on settings on the top of the page
    6. +
    7. Click on "Forwards, Autorespond, Lists" on the left
    8. +
    9. Click on "Setup Vacation Message"
    10. +
    11. Complete the form with following +
        +
      • "From:" select your E-mail address
      • +
      • "Reply Subject:" Subject for email to be sent
      • +
      • "Reply Body:" Message you want sent
      • +
      +
    12. +
    13. Click "Update Vacation Message"
    14. +
    15. Dont forget to Remove an out of office message when you return
    16. +
    + +

     

    +


    +

     

    + + +

    Remove an out of office message

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using your email address and password
    4. +
    5. Click on settings on the top of the page
    6. +
    7. Click on "Forwards, Autorespond, Lists" on the left
    8. +
    9. Click on "Setup Vacation Message"
    10. +
    11. Click "Disable Vacation Message"
    12. +
    + +

     

    +


    +

     

    + + +

    Change Your Password

    + +
      +
    1. Open a browser to "webmail.(your domain)"
    2. +
    3. Log on using your email account and password
    4. +
    5. Click on settings on the top of the page
    6. +
    7. Click on "Account Maintenance"
    8. +
    9. Click on "Mail Forwarders"
    10. +
    11. Click on "Change Password & Secret Question/Answer"
    12. +
    13. Complete the form with following +
        +
      • "Old Password:" Your existing password
      • +
      • "New Password" New password
      • +
      • "Re-type New Password:" For verification
      • +
      +
    14. +
    15. Click "Update Password & Secret Question"
    16. +
    + +
    +
    + +