UserArea files, Contact page
authorLaury GvR <laury@gaslightmedia.com>
Thu, 24 Jul 2014 13:18:02 +0000 (09:18 -0400)
committerLaury GvR <laury@gaslightmedia.com>
Thu, 24 Jul 2014 13:18:02 +0000 (09:18 -0400)
Added UserArea files from Cheboygancounty, though only functional
under some circumstances. Added 10.phtml from Demo, static contacts.

153 files changed:
Toolkit/Contacts/config.ini
Toolkit/UserArea/Admin/EditUser.php [new file with mode: 0644]
Toolkit/UserArea/Admin/IndexController.php [new file with mode: 0644]
Toolkit/UserArea/Admin/ListLogs.php [new file with mode: 0644]
Toolkit/UserArea/Admin/ListUsers.php [new file with mode: 0644]
Toolkit/UserArea/Admin/Log.php [new file with mode: 0644]
Toolkit/UserArea/Admin/PageTree.php [new file with mode: 0644]
Toolkit/UserArea/Auth.php [new file with mode: 0644]
Toolkit/UserArea/Auth/Container.php [new file with mode: 0644]
Toolkit/UserArea/Auth/LoginForm.php [new file with mode: 0644]
Toolkit/UserArea/Auth/PasswordForm.php [new file with mode: 0644]
Toolkit/UserArea/BreadCrumbsAbstract.php [new file with mode: 0644]
Toolkit/UserArea/Database/application.sql [new file with mode: 0644]
Toolkit/UserArea/Database/apps.sql [new file with mode: 0644]
Toolkit/UserArea/Database/removeApplication.sql [new file with mode: 0644]
Toolkit/UserArea/Database/tables/apps.sql [new file with mode: 0644]
Toolkit/UserArea/Database/tables/logs.sql [new file with mode: 0644]
Toolkit/UserArea/Database/tables/userapps.sql [new file with mode: 0644]
Toolkit/UserArea/Database/tables/users.sql [new file with mode: 0644]
Toolkit/UserArea/DraftPagesTree.php [new file with mode: 0644]
Toolkit/UserArea/EditDraftController.php [new file with mode: 0644]
Toolkit/UserArea/EditPageController.php [new file with mode: 0644]
Toolkit/UserArea/Exception.php [new file with mode: 0644]
Toolkit/UserArea/FileExtension.php [new file with mode: 0644]
Toolkit/UserArea/FormControllerAbstract.php [new file with mode: 0644]
Toolkit/UserArea/Forms/EditPage.php [new file with mode: 0644]
Toolkit/UserArea/Forms/EditParagraph.php [new file with mode: 0644]
Toolkit/UserArea/Forms/SearchForm.php [new file with mode: 0644]
Toolkit/UserArea/GatewayAbstract.php [new file with mode: 0644]
Toolkit/UserArea/GatewayFactoryAbstract.php [new file with mode: 0644]
Toolkit/UserArea/IndexController.php [new file with mode: 0644]
Toolkit/UserArea/ListDraftsController.php [new file with mode: 0644]
Toolkit/UserArea/Models/App.php [new file with mode: 0644]
Toolkit/UserArea/Models/Log.php [new file with mode: 0644]
Toolkit/UserArea/Models/Mapper.php [new file with mode: 0644]
Toolkit/UserArea/Models/User.php [new file with mode: 0644]
Toolkit/UserArea/Models/UserApp.php [new file with mode: 0644]
Toolkit/UserArea/Navigation.php [new file with mode: 0644]
Toolkit/UserArea/Page.php [new file with mode: 0644]
Toolkit/UserArea/PageBreadCrumbs.php [new file with mode: 0644]
Toolkit/UserArea/PageDraftBreadCrumbs.php [new file with mode: 0644]
Toolkit/UserArea/PageGatewayAbstract.php [new file with mode: 0644]
Toolkit/UserArea/PageGatewayDraft.php [new file with mode: 0644]
Toolkit/UserArea/PageGatewayDraftFactory.php [new file with mode: 0644]
Toolkit/UserArea/PageGatewayPublish.php [new file with mode: 0644]
Toolkit/UserArea/PageGatewayPublishFactory.php [new file with mode: 0644]
Toolkit/UserArea/PagesTree.php [new file with mode: 0644]
Toolkit/UserArea/ParagraphBreadCrumbs.php [new file with mode: 0644]
Toolkit/UserArea/ParagraphDraftBreadCrumbs.php [new file with mode: 0644]
Toolkit/UserArea/ParagraphGatewayAbstract.php [new file with mode: 0644]
Toolkit/UserArea/ParagraphGatewayDraft.php [new file with mode: 0644]
Toolkit/UserArea/ParagraphGatewayDraftFactory.php [new file with mode: 0644]
Toolkit/UserArea/ParagraphGatewayPublish.php [new file with mode: 0644]
Toolkit/UserArea/ParagraphGatewayPublishFactory.php [new file with mode: 0644]
Toolkit/UserArea/ParagraphsController.php [new file with mode: 0644]
Toolkit/UserArea/ParagraphsDraftController.php [new file with mode: 0644]
Toolkit/UserArea/ParagraphsDraftTree.php [new file with mode: 0644]
Toolkit/UserArea/ParagraphsTree.php [new file with mode: 0644]
Toolkit/UserArea/SearchController.php [new file with mode: 0644]
Toolkit/UserArea/SearchTree.php [new file with mode: 0644]
Toolkit/UserArea/TreeAbstract.php [new file with mode: 0644]
Toolkit/UserArea/assets/.keepme [new file with mode: 0644]
Toolkit/UserArea/assets/arrow.png [new file with mode: 0755]
Toolkit/UserArea/assets/arrowClosed.png [new file with mode: 0755]
Toolkit/UserArea/assets/arrowOpen.png [new file with mode: 0755]
Toolkit/UserArea/assets/collapse.png [new file with mode: 0755]
Toolkit/UserArea/assets/expand.png [new file with mode: 0755]
Toolkit/UserArea/assets/grnball.gif [new file with mode: 0755]
Toolkit/UserArea/assets/mobilemgreen.jpg [new file with mode: 0644]
Toolkit/UserArea/assets/mobilemred.jpg [new file with mode: 0644]
Toolkit/UserArea/assets/redball.gif [new file with mode: 0755]
Toolkit/UserArea/assets/template1.gif [new file with mode: 0755]
Toolkit/UserArea/assets/template2.gif [new file with mode: 0755]
Toolkit/UserArea/assets/template3.gif [new file with mode: 0755]
Toolkit/UserArea/assets/template4.gif [new file with mode: 0755]
Toolkit/UserArea/assets/template5.gif [new file with mode: 0755]
Toolkit/UserArea/assets/template6.gif [new file with mode: 0644]
Toolkit/UserArea/config.ini [new file with mode: 0644]
Toolkit/UserArea/css/styles.css [new file with mode: 0644]
Toolkit/UserArea/fixPageNoContent.php [new file with mode: 0644]
Toolkit/UserArea/fixPagePos.php [new file with mode: 0644]
Toolkit/UserArea/libjs/edit-page.js [new file with mode: 0644]
Toolkit/UserArea/libjs/edit-paragraph.js [new file with mode: 0644]
Toolkit/UserArea/libjs/editUser.js [new file with mode: 0644]
Toolkit/UserArea/libjs/jquery.columnview.js [new file with mode: 0755]
Toolkit/UserArea/libjs/pagesTree.js [new file with mode: 0644]
Toolkit/UserArea/libjs/paragraph-tree.js [new file with mode: 0644]
Toolkit/UserArea/moveBySelect.php [new file with mode: 0644]
Toolkit/UserArea/moveBySelectPara.php [new file with mode: 0644]
Toolkit/UserArea/pageChangeState.php [new file with mode: 0644]
Toolkit/UserArea/pageMobileChangeState.php [new file with mode: 0644]
Toolkit/UserArea/pageMove.php [new file with mode: 0644]
Toolkit/UserArea/paragraphChangeState.php [new file with mode: 0644]
Toolkit/UserArea/paragraphFileUpload.php [new file with mode: 0644]
Toolkit/UserArea/paragraphMove.php [new file with mode: 0644]
Toolkit/UserArea/styles.css [new file with mode: 0644]
Toolkit/UserArea/views/EditUserApps.html [new file with mode: 0644]
admin/nav.phtml
admin/userArea.php [new file with mode: 0644]
static/11.phtml [new file with mode: 0644]
userArea/CommonEvents/.htaccess [new file with mode: 0644]
userArea/CommonEvents/index.php [new file with mode: 0644]
userArea/Contact/contact_inquiry.phtml [new file with mode: 0755]
userArea/Contact/contact_setup.inc [new file with mode: 0755]
userArea/Contact/del_query.phtml [new file with mode: 0755]
userArea/Contact/download.phtml [new file with mode: 0755]
userArea/Contact/edit_autoresponse.phtml [new file with mode: 0755]
userArea/Contact/edit_contact.php [new file with mode: 0644]
userArea/Contact/edit_group.php [new file with mode: 0644]
userArea/Contact/edit_inquiry.phtml [new file with mode: 0755]
userArea/Contact/emails.php [new file with mode: 0644]
userArea/Contact/form.js [new file with mode: 0755]
userArea/Contact/help/contact.phtml [new file with mode: 0755]
userArea/Contact/htmlarea.css [new file with mode: 0644]
userArea/Contact/index.phtml [new file with mode: 0755]
userArea/Contact/list_contact.phtml [new file with mode: 0755]
userArea/Contact/list_groups.php [new file with mode: 0644]
userArea/Contact/list_query.phtml [new file with mode: 0755]
userArea/Contact/mailout.phtml [new file with mode: 0644]
userArea/Contact/main.css [new file with mode: 0755]
userArea/Contact/msg.js [new file with mode: 0755]
userArea/Contact/newsletter_template.html [new file with mode: 0755]
userArea/Contact/notes/ChangeLog [new file with mode: 0755]
userArea/Contact/notes/Contact [new file with mode: 0755]
userArea/Contact/notes/contact.sql [new file with mode: 0755]
userArea/Contact/preview.phtml [new file with mode: 0755]
userArea/Contact/query_contact.phtml [new file with mode: 0755]
userArea/Contact/query_db.phtml [new file with mode: 0755]
userArea/Contact/query_save.phtml [new file with mode: 0755]
userArea/Contact/update_autoresponse.phtml [new file with mode: 0755]
userArea/Contact/update_contact.phtml [new file with mode: 0755]
userArea/Contact/update_inquiry.phtml [new file with mode: 0755]
userArea/Contact/verify.js [new file with mode: 0755]
userArea/Contact/view_newsletter.phtml [new file with mode: 0755]
userArea/Contact/wm.js [new file with mode: 0755]
userArea/banners.php [new file with mode: 0644]
userArea/css/banner.css [new file with mode: 0644]
userArea/css/contactform.css [new file with mode: 0644]
userArea/css/main.css [new file with mode: 0755]
userArea/index.php [new file with mode: 0644]
userArea/login.php [new file with mode: 0644]
userArea/main.css [new file with mode: 0644]
userArea/members.php [new file with mode: 0755]
userArea/nav.php [new file with mode: 0644]
userArea/photos.php [new file with mode: 0644]
userArea/setup.php [new file with mode: 0644]
userArea/slideshow.php [new file with mode: 0644]
userArea/splash.php [new file with mode: 0644]
userArea/templates/frameSet.html [new file with mode: 0644]
userArea/templates/loginPage.html [new file with mode: 0644]
userArea/toolbox.php [new file with mode: 0644]
userArea/verify.js [new file with mode: 0755]
userArea/videos.php [new file with mode: 0644]

index c77d0d2..aaecfc3 100644 (file)
@@ -9,6 +9,6 @@ sequence = "contact_id_seq"
 
 [contact_types]
 1 = "Web Contact"
-2 = "E-News"
-3 = "Travel Planner"
-4 = "Visitor Guide"
+;2 = "E-News"
+;3 = "Travel Planner"
+;4 = "Visitor Guide"
diff --git a/Toolkit/UserArea/Admin/EditUser.php b/Toolkit/UserArea/Admin/EditUser.php
new file mode 100644 (file)
index 0000000..8d230be
--- /dev/null
@@ -0,0 +1,675 @@
+<?php
+
+/**
+ * EditUser.php
+ *
+ * PHP version 5
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2010 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: EditContact.php,v 1.3 2010/05/13 20:18:38 matrix Exp $
+ * @link      http://pear.php.net/package/Contacts
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * Toolkit_UserArea_Admin_EditUser
+ *
+ * Edit Process class to insert or update a user
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2010 Steve Sutton
+ * @license   Gaslight Media
+ * @version   Release: @package_version@
+ * @link      http://pear.php.net/package/Contacts
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_UserArea_Admin_EditUser
+    extends Toolkit_FormBuilder
+{
+
+    /**
+     * 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();
+
+    /**
+     * What do you want the error msg to be if the form doesn't validate
+     *
+     * @var string
+     * @access protected
+     */
+    protected $errorMsg
+        = '<div id="form-warning-top">
+                Warning: The form was not sent, please review the errors below.
+           </div>';
+
+    /**
+     * What do you want the success msg to be if the form validates successfully
+     *
+     * @var string
+     * @access protected
+     */
+    protected $successMsg
+        = '<div id="form-success-top">
+                The information below has been successfully submitted.
+           </div>';
+
+    /**
+     * The default templates to inject into the form renderer
+     *
+     * @var string
+     * @access protected
+     */
+    protected $template;
+
+    /**
+     * The default rules to register for validating
+     *
+     * We have to register these rules, or any others we want, before
+     * we are able to use them in our forms.
+     *
+     * These rules can be removed in subclasses before the rules are configured
+     * if you want to omit any of them from validating input - just remember
+     * to not call them in your configured rules!
+     *
+     * Phone: validates input against US and CA style phone #'s
+     * <code>
+     * $rules[] = array('element'    => 'phone',
+     *                  'message'    => 'ERROR: Invalid Phone Format!',
+     *                  'type'       => 'phone',
+     *                  'format'     => null,
+     *                  'validation' => $this->validationType,
+     *                  'reset'      => true,
+     *                  'force'      => false);
+     * </code>
+     *
+     * Zip: Validates input against US and CA zip codes, if DB check is
+     *      set to true, validate zip codes against all the zip codes in the
+     *      DB.
+     * <code>
+     * $rules[] = array('element'    => 'zip',
+     *                  'message'    => 'ERROR: Invalid Zip!',
+     *                  'type'       => 'zip',
+     *                  'format'     => array('requireDBCheck' => true),
+     *                  'validation' => $this->validationType,
+     *                  'reset'      => true,
+     *                  'force'      => false);
+     * </code>
+     *
+     * Banwords: Make sure each each doesn't contain a banned word. Checking
+     *           against a DB of banned words.
+     *
+     * State: Validate input against US and CA region / province codes.  If DB
+     *        check is set to true, validate region / province against all the
+     *        regions / provinces in the DB.
+     * <code>
+     * $rules[] = array('element'    => 'state_id',
+     *                  'message'    => 'ERROR: Invalid State / Province!',
+     *                  'type'       => 'state',
+     *                  'format'     => array('requireDBCheck' => true),
+     *                  'validation' => $this->validationType,
+     *                  'reset'      => true,
+     *                  'force'      => false);
+     * </code>
+     *
+     * @var array
+     * @access protected
+     * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Zip.php
+     * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Phone.php
+     * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/Banwords.php
+     * @see app.gaslightmedia.com/glmPEAR/HTML/QuickForm/Rule/State.php
+     */
+    protected $registeredRules = array();
+
+    /**
+     * 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 <form> tag
+     * @param bool   $trackSubmit (optional)Whether to track if the form was
+     *                            submitted by adding a special hidden field
+     *
+     * @author Jamie Kahgee <jamie.kahgee@gmail.com>
+     * @access public
+     * @link   http://pear.php.net/package/HTML_QuickForm/docs/latest/HTML_QuickForm/HTML_QuickForm.html
+     * @see    HTML_QuickForm
+     */
+    public function __construct(
+        PDO $pdo,
+        $formName,
+        $method = 'post',
+        $action = '',
+        $target = '',
+        $attributes = null,
+        $trackSubmit = false
+    ) {
+        parent::__construct(
+            $formName,
+            $method,
+            $action,
+            $target,
+            $attributes,
+            $trackSubmit
+        );
+
+        $this->dbh = $pdo;
+
+        /**
+         * Where are the flexy templates stored at for this class.
+         */
+        define('TEMPLATES_DIR', BASE . 'Toolkit/Contacts/templates');
+
+        /**
+         * Where are the compiled flexy templates stored at for this class.
+         */
+        define('COMPILED_DIR', BASE . 'Toolkit/Contacts/templates/compiled');
+        $oldUmask = umask(0);
+        if (!is_dir(TEMPLATES_DIR)) {
+            mkdir(TEMPLATES_DIR, 0770, true);
+        }
+        if (!is_dir(COMPILED_DIR)) {
+            mkdir(COMPILED_DIR, 0770, true);
+        }
+        umask($oldUmask);
+
+        $this->flexyOptions                = $GLOBALS['flexyOptions'];
+        $this->flexyOptions['templateDir'] = TEMPLATES_DIR;
+        $this->flexyOptions['compileDir']  = COMPILED_DIR;
+
+    }
+
+    /**
+     * Constant variables for the form
+     *
+     * These values won't get overridden by POST or GET vars
+     *
+     * @return void
+     * @access public
+     */
+    public function configureConstants()
+    {
+        $c = array(
+            'toolbox' => true
+        );
+        if ($id = filter_var($_REQUEST['id'], FILTER_VALIDATE_INT)) {
+            $c['id'] = $id;
+        }
+        $this->setupConstants($c);
+    }
+
+    /**
+     * Initializes default form values
+     *
+     * @return void
+     * @access public
+     */
+    public function configureDefaults()
+    {
+        $id = filter_var($_REQUEST['id'], FILTER_VALIDATE_INT);
+        if ($id) {
+            $mapper
+                = new Toolkit_UserArea_Models_Mapper();
+            $user
+                = $mapper->fetchUserById($this->dbh, $id);
+            $defaults = array(
+                'id'       => $user->getId(),
+                'username' => $user->getUsername(),
+                'password' => $user->getPassword(),
+                'name'     => $user->getName(),
+                'active'   => $user->getActive()
+            );
+        } else {
+            $defaults = array();
+        }
+
+        $this->setupDefaults($defaults);
+    }
+
+    /**
+     * Form element definitions
+     *
+     * @return void
+     * @access public
+     */
+    public function configureElements()
+    {
+        $e = array();
+        $id = filter_var($_REQUEST['id'], FILTER_VALIDATE_INT);
+        //  All Elements are created here.  This includes group element definitions.
+
+        $e[] = array(
+            'type'    => 'header',
+            'display' => 'User Information'
+        );
+        if ($id) {
+            $e[] = array(
+                'type' => 'hidden',
+                'req'  => false,
+                'name' => 'id',
+                'opts'  => array('id' => 'userId')
+            );
+        }
+        $e[] = array(
+            'type' => 'hidden',
+            'req'  => false,
+            'name' => 'toolbox'
+        );
+        $e[] = array(
+            'type'    => 'advcheckbox',
+            'req'     => false,
+            'name'    => 'active',
+            'display' => '',
+            'opts'    => 'Active?',
+            'val'     => array(0, 1)
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'name',
+            'display' => 'Name'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'username',
+            'display' => 'User Name'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'password',
+            'display' => 'Password'
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'display' => '<b>Applications</b>
+                <div id="appData"></div>'
+        );
+
+        $e[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'submit_rmv',
+            'display' => 'Save'
+        );
+
+        $this->setupElements($e);
+    }
+
+    /**
+     * Form rule definitions
+     *
+     * Adds validation rules for the given fields
+     *
+     * @return void
+     * @access public
+     */
+    public function configureRules()
+    {
+        $r = array();
+        //  Form Rules
+
+        $r[] = array(
+            'element'    => 'username',
+            'message'    => 'ERROR: Sorry, but this username has already been taken!',
+            'type'       => 'callback',
+            'format'     => array($this, 'checkUName'),
+            'validation' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+
+        $this->setupRules($r);
+    }
+
+    /**
+     * 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($_REQUEST['id'])) {
+                $and = "AND id <> :id";
+            }
+            $sql = "
+                SELECT count(*) AS total
+                  FROM auth.users
+                 WHERE username = :name
+                  $and";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':name', $data, PDO::PARAM_STR);
+            if (is_numeric($_REQUEST['id'])) {
+                $stmt->bindParam(':id', $_REQUEST['id'], PDO::PARAM_STR);
+            }
+            $stmt->execute();
+            $stmt->bindColumn('total', $valid);
+            $stmt->fetch();
+
+            return !(bool) $valid;
+        } catch (PDOException $e) {
+            return Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Form filter definitions
+     *
+     * Applies a data filter for the given fields when the form is submitted
+     *
+     * @return void
+     * @access public
+     */
+    public function configureFilters()
+    {
+        $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter' => 'trim'
+        );
+
+        $this->setupFilters($f);
+    }
+
+    /**
+     * Helper function, configures the entire form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureFilters();
+        $this->configureRules();
+        $this->configureDefaults();
+        $this->configureConstants();
+    }
+
+    /**
+     * 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);
+
+        //  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);
+        $id     = filter_var($_REQUEST['id'], FILTER_VALIDATE_INT);
+        $user   = Toolkit_UserArea_Models_User::createUserFromValues($values);
+        if ($id) {
+            $this->Action = 'Updated';
+        } else {
+            $this->Action = 'Added';
+        }
+        $user->save($this->dbh);
+        $mapper = new Toolkit_UserArea_Models_Mapper();
+        $mapper->saveUserAppData(
+            $this->dbh,
+            $user,
+            $values['app'],
+            $values['pages'],
+            $values['eventCategories']
+        );
+        return true;
+    }
+
+    /**
+     * setConfig
+     *
+     * @param Config_Container $c instance of Config Container
+     *
+     * @access public
+     * @return string
+     */
+    function setConfig(Config_Container $c)
+    {
+        $this->config = $c;
+    }
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+    protected function setupRenderers()
+    {
+        parent::setupRenderers();
+        $renderer =& $this->defaultRenderer();
+        $required = '<!-- BEGIN required -->
+            <span class="req"> * </span>
+            <!-- END required -->';
+        $error    = '<!-- BEGIN error -->
+            <div class="req"> {error} </div>
+            <!-- END error -->';
+        $renderer->setElementTemplate(
+            '<tr>
+               <td colspan="2" class="fieldcell checkbox">
+               '.$required.'{label}'.$error.'{element}
+               </td>
+             </tr>',
+            'interest'
+        );
+
+        $renderer->setElementTemplate(
+            '<tr><td colspan="2">'.$required.'{label}'.$error.'{element}</td></tr>',
+            'comments'
+        );
+        $renderer->setElementTemplate(
+            '<tr align="center">
+                <td colspan="2">'.$required.'{label}'.$error.'{element}
+                    </td>
+             </tr>',
+            'submit'
+        );
+
+        $renderer->setElementTemplate(
+            '<tr>
+               <td class="labelcell">
+                 <label>{label}</label>
+               </td>
+               <td class="fieldcell captcha">
+                 {element}
+               </td>
+             </tr>',
+            'captcha_question');
+        $renderer->setElementTemplate(
+            '<tr>
+                <td class="labelcell">
+                  '.$required.'<label>{label}</label>
+                </td>
+                <td class="fieldcell">
+                  '.$error.'{element}
+                  <span class="tooltip" title="Verification Code|To help us
+                  distinguish between information submitted by individuals
+                  and those automatically entered by software robots, please
+                  type the letters shown.">What is this?</span>
+                </td>
+              </tr>',
+            'captcha_rmv'
+        );
+    }
+
+    /**
+     * 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()
+    {
+        $GLOBALS['styleSheets'][]
+            = MEDIA_APP_BASE_URL . 'libjs/jqueryui/1.8.13/development-bundle/themes/base/jquery.ui.all.css';
+        $GLOBALS['styleSheets'][]
+            = MEDIA_APP_BASE_URL . 'libjs/plugins/asmselect/1.0.4a/jquery.asmselect.css';
+        $GLOBALS['topScripts'][]
+            = MEDIA_APP_BASE_URL . 'libjs/jqueryui/1.8.13/js/jquery-ui-1.8.13.custom.min.js';
+        $GLOBALS['bottomScripts'][]
+            = MEDIA_BASE_URL . 'Toolkit/UserArea/libjs/jquery.columnview.js';
+        $GLOBALS['bottomScripts'][]
+            = MEDIA_APP_BASE_URL . 'libjs/plugins/asmselect/1.0.4a/jquery.asmselect.js';
+        $GLOBALS['bottomScripts'][]
+            = MEDIA_BASE_URL . 'Toolkit/UserArea/libjs/editUser.js';
+
+        $this->setupRenderers();
+        if ($this->validate()) {
+            $this->cleanForm();
+            if ($this->process(array(&$this, 'processData'), $this->mergeFiles)) {
+                $this->freeze();
+                $output = $this->successMsg;
+                header("Location: userArea.php");
+                exit;
+            }
+        } elseif ($this->isSubmitted()) {
+            $output  = $this->errorMsg;
+            $output .= parent::toHTML();
+        } else {
+            $output = parent::toHTML();
+        }
+        return $output;
+    }
+
+    /**
+     * Load option elements into the parent select list
+     *
+     * These options are loaded via this seperate function vs inline w/ the
+     * element definition b/c we need a little more control defining
+     * the class names for each option so they will render nice when a user
+     * is looking at the list.
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @return void
+     * @throws PDOException throws exception on sql error
+     * @access public
+     */
+    public function loadParentPages(PDO $dbh)
+    {
+        try {
+            //  Get a tree list of categories in linear order with
+            //  category keys in the values and their level in the tree
+            //  in the value
+            $c = Toolkit_Common::getHierarchicalTreeStructure(
+                $dbh,
+                'pages',
+                'id',
+                'parent',
+                'pos',
+                0,
+                0
+            );
+
+            //  unset the home page, this is never an option to have children
+            //  underneath it.
+            unset($c[HOME_ID]);
+
+            //  If we are editing a page, then we don't want that page
+            //  to show up as an option in the select list.
+            if (is_numeric($_GET['id'])) {
+                reset($c);
+                //  Get us to the point in the array were this page is located
+                while (key($c) != $_GET['id'] && current($c) !== false) {
+                    next($c);
+                }
+                //  Make sure we didn't traverse off the end of the array
+                if (current($c) !== false) {
+                    //  get the starting level we are currently at
+                    $sl = current($c);
+                    //  remove this page (the one we're editing) from the
+                    //  array and advance the internal array pointer
+                    unset($c[key($c)]);
+                    //  now we need to make sure all sub pages beneath this
+                    //  page are also not being shown
+
+                    //  while we don't traverse off the end of the array
+                    while (current($c) !== false) {
+                        //  get the current sub level we are at
+                        $csl = current($c);
+                        //  if the current sub-level is the same as the
+                        //  starting level, that means we have traversed through
+                        //  all the sub-pages and can break out of the loop
+                        if ($csl <= $sl) {
+                            break;
+                        } else {
+                            //  we are still in a sub-level page, so unset
+                            //  this page so it doesn't show, and advance
+                            //  the internal array pointer
+                            unset($c[key($c)]);
+                        }
+                    }
+                }
+            }
+
+            //  Get all the data about each category
+            $sql = "
+                SELECT *
+                  FROM pages
+                 WHERE id = ?";
+
+            $stmt = $dbh->prepare($sql);
+            //  Get the member categories select list element
+            $e =& $this->getElement('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['navigation_name'],
+                    $i,
+                    array('class' => "level-$x")
+                );
+            }
+        } catch (PDOException $e) {
+            Toolkit_Logger::logException('DB error', $e);
+            throw new Toolkit_Toolbox_Exception(
+                "Error loading parent pages"
+            );
+        }
+    }
+
+}
diff --git a/Toolkit/UserArea/Admin/IndexController.php b/Toolkit/UserArea/Admin/IndexController.php
new file mode 100644 (file)
index 0000000..d790db9
--- /dev/null
@@ -0,0 +1,170 @@
+<?php
+
+/**
+ * User.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+if (!defined('COMMON_APP_BASE')) {
+    define('COMMON_APP_BASE', '/var/www/server/CommonApps/');
+}
+require_once COMMON_APP_BASE . 'EventCalendar/V1/models/EventMapper.php';
+define('COMMON_EVENTS_SCHEMA', 'events');
+/**
+ * Toolkit_UserArea_Admin_User
+ *
+ * Description of User
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Admin_IndexController
+    extends Toolkit_BaseControllerAbstract
+    implements Toolkit_IController
+{
+
+    const TOOLBOX_APP_ID = 1;
+    const EVENT_APP_ID   = 2;
+    const HAS_TOOLBOX    = true;
+    const HAS_EVENTS     = true;
+
+    public function indexAction()
+    {
+        $users = new Toolkit_UserArea_Admin_ListUsers(
+            Toolkit_Database::getInstance()
+        );
+        $users->setQuery();
+        $html = $users->toHtml();
+
+        return $html;
+    }
+
+    public function showPagesAction()
+    {
+        $pageTree = new Toolkit_UserArea_Admin_PageTree($this->registry->dbh);
+        echo $pageTree->toHtml();
+        exit;
+    }
+
+    private function _getPageName($pageId)
+    {
+        try {
+            $sql = "
+            SELECT navigation_name
+              FROM toolbox.pages
+             WHERE id = :id";
+            $stmt = $this->registry->dbh->prepare($sql);
+            $stmt->bindParam(':id', $pageId, PDO::PARAM_INT);
+            $stmt->execute();
+            return $stmt->fetchColumn();
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+
+    }
+
+    private function _getEventCategories()
+    {
+        static $categories = array();
+        if (empty($categories)) {
+            $eventMapper = new EventMapper(Toolkit_Database::getInstance());
+            $categories  = $eventMapper->fetchAllCategories();
+        }
+        return $categories;
+    }
+
+    public function GetUserAppsAction()
+    {
+        $userEventCategories    = array();
+        $options                = $GLOBALS['flexyOptions'];
+        $options['templateDir'] = BASE . 'Toolkit/UserArea/views';
+        $options['compileDir']  = BASE . 'Toolkit/UserArea/views/compiled';
+        $options['flexyIgnore'] = true;
+        $tpl          = new HTML_Template_Flexy($options);
+        $userId       = filter_var($_REQUEST['userId'], FILTER_VALIDATE_INT);
+        $mapper       = new Toolkit_UserArea_Models_Mapper();
+        $userApps     = array();
+        $toolboxPages = array();
+        if ($userId) {
+            $user
+                = $mapper->fetchUserById($this->registry->dbh, $userId);
+            $userAppsData
+                = $mapper->fetchAllUserApps($this->registry->dbh, $user);
+            if ($userAppsData) {
+                foreach ($userAppsData as $apps) {
+                    $userApps[] = $apps->getAppId();
+                    if ($apps->getAppId() == self::TOOLBOX_APP_ID) {
+                        $hasToolbox = true;
+                        if ($appId = filter_var($apps->getConfig(), FILTER_VALIDATE_INT)) {
+                            $toolboxPages[] = array(
+                                'id'   => $apps->getConfig(),
+                                'name' => $this->_getPageName($appId)
+                            );
+                        }
+                    } else if ($apps->getAppId() == self::EVENT_APP_ID) {
+                        $config = $apps->getConfig();
+                        if ($config) {
+                            $userEventCategories = unserialize($config);
+                        }
+                    }
+                }
+            }
+        }
+        $tpl->compile('EditUserApps.html');
+        $page             = new stdClass();
+        $page->stuff      = null;
+        $page->apps       = $mapper->fetchAllApps($this->registry->dbh);
+        $page->userApps   = ($userApps) ? $userApps : null;
+        $page->pages      = $toolboxPages;
+        $page->hasToolbox = self::HAS_TOOLBOX;
+        $page->hasEvents  = self::HAS_EVENTS;
+        $page->categories = $this->_getEventCategories();
+        $page->userEventCategories
+            = $userEventCategories;
+        $html
+            = $tpl->bufferedOutputObject($page);
+        echo $html;
+        exit;
+    }
+
+    public function EditAction()
+    {
+        $editUser = new Toolkit_UserArea_Admin_EditUser(
+            $this->registry->dbh,
+            'edit-user-form',
+            'post'
+        );
+        $editUser->configureForm();
+        $html = $editUser->toHtml();
+        $id   = filter_var($_REQUEST['id'], FILTER_VALIDATE_INT);
+        return $html;
+    }
+
+    public function DeleteAction()
+    {
+        $userId = filter_var($_REQUEST['id'], FILTER_VALIDATE_INT);
+        if ($userId) {
+            $dbh = Toolkit_Database::getInstance();
+            $user = Toolkit_UserArea_Models_User::fetchUserById(
+                $dbh,
+                $userId
+            );
+            $user->delete($dbh);
+        }
+        return $this->indexAction();
+    }
+
+}
diff --git a/Toolkit/UserArea/Admin/ListLogs.php b/Toolkit/UserArea/Admin/ListLogs.php
new file mode 100644 (file)
index 0000000..5213ae1
--- /dev/null
@@ -0,0 +1,156 @@
+<?php
+
+/**
+ * ListLogs.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_UserArea_Admin_ListLogs
+ *
+ * Create the list of logs for a user
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Admin_ListLogs
+    extends Toolkit_DataGridBuilder
+{
+    private $_userId;
+    /**
+     * How many records must exist in the Datagrid before the sort form shows up
+        *
+     * @var    integer
+     * @access protected
+     */
+       protected $sortableAfter = null;
+
+    /**
+        * Message to display to users if no records were found
+        *
+        * @var         String
+        * @access      Protected
+        * @see         Toolkit_DataGridBuilder::setNoRecordMessage()
+        */
+       protected $noRecMessage = 'No Logs';
+
+       public function __construct(
+        PDO $pdo,
+        $limit = null,
+        $page = null,
+        $rendererType = null
+    ) {
+               parent::__construct($pdo, $limit, $page, $rendererType);
+               $this->options = array('dbc' => $pdo);
+               if (!is_null($limit)) {
+                       $this->sortableAfter = $limit;
+               }
+       }
+
+    protected function configureColumns()
+    {
+        $this->addColumn(new Structures_DataGrid_Column(
+            'Alter Time',
+            'alter_time',
+            null
+        ));
+        $this->addColumn(new Structures_DataGrid_Column(
+            'Type',
+            'alter_type',
+            null
+        ));
+        $this->addColumn(new Structures_DataGrid_Column(
+            'Comment',
+            'comment',
+            null
+        ));
+    }
+
+    public function setUserId($id)
+    {
+        if (   !is_int($id)
+            && !ctype_digit($id)
+            && $id <= 0
+        ) {
+            throw new InvalidArgumentException('Id must be an integer');
+        }
+        $this->_userId = $id;
+    }
+
+       public function setQuery()
+       {
+
+               $sql = "
+        SELECT *
+          FROM auth.logs
+         WHERE user_id = {$this->_userId}";
+
+               parent::setQuery($sql);
+       }
+
+    /**
+     * 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);
+                       }
+
+                       return $gridPager . $gridBody . $gridPager;
+               } else {
+                       return "<h2>{$this->noRecMessage}</h2>";
+               }
+       }
+}
+
diff --git a/Toolkit/UserArea/Admin/ListUsers.php b/Toolkit/UserArea/Admin/ListUsers.php
new file mode 100644 (file)
index 0000000..f5c281e
--- /dev/null
@@ -0,0 +1,104 @@
+<?php
+
+/**
+ * ListUsers.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Package_ListUsers
+ *
+ * List the User in the User Area
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Admin_ListUsers
+    extends Toolkit_DataGridBuilder
+{
+
+    public function __construct(
+        PDO $pdo,
+        $limit = null,
+        $page = null,
+        $rendererType = null
+    ) {
+        parent::__construct($pdo, $limit, $page, $rendererType);
+        $this->options = array('dbc' => $pdo);
+        if (!is_null($limit)) {
+            $this->sortableAfter = $limit;
+        }
+    }
+
+    protected function configureColumns()
+    {
+        $this->addColumn(new Structures_DataGrid_Column(
+            'Edit',
+            null,
+            null,
+            array('class' => 'editLink'),
+            null,
+            array(&$this, 'renderEditLink')
+        ));
+        $this->addColumn(new Structures_DataGrid_Column(
+            'Name',
+            'name',
+            'name'
+        ));
+        $this->addColumn(new Structures_DataGrid_Column(
+            'Delete',
+            null,
+            null,
+            array('class' => 'editLink'),
+            null,
+            array(&$this, 'renderDeleteLink')
+        ));
+    }
+
+    public function renderEditLink($data)
+    {
+        extract($data['record']);
+        $link = '<a href="%sadmin/userArea.php?ac=Edit&amp;id=%s">Edit</a>';
+        return sprintf($link, MEDIA_BASE_URL, $id);
+    }
+
+    public function renderDeleteLink($data)
+    {
+        extract($data['record']);
+        $link = '<a href="%s" onClick="return confirm(\'This will Delete the user. Are You sure?\');">Delete</a>';
+        return sprintf(
+            $link,
+           MEDIA_BASE_URL . "admin/userArea.php?ac=Delete&amp;id={$id}"
+        );
+    }
+
+    public function setQuery()
+    {
+
+        $sql = "
+        SELECT *
+          FROM auth.users";
+
+        $params = array();
+        if (isset($_GET['_qf__search_form']) && !empty($params)) {
+            $params = implode(' AND ', $params);
+            $sql    = "{$sql} WHERE $params";
+        }
+
+        parent::setQuery($sql);
+    }
+}
diff --git a/Toolkit/UserArea/Admin/Log.php b/Toolkit/UserArea/Admin/Log.php
new file mode 100644 (file)
index 0000000..84122e7
--- /dev/null
@@ -0,0 +1,366 @@
+<?php
+
+/**
+ * Log.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Package_Log
+ *
+ * Object representation of the auth.logs table record
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Admin_Log
+{
+    private $_id;
+    private $_userId;
+    private $_alterTime;
+    private $_dbTable;
+    private $_alterType;
+    private $_foreignKey;
+    private $_comment;
+
+    /**
+     * Creates an object of type Log
+     *
+     * @param array $values Log values
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    private function __construct(array $values)
+    {
+        extract($values);
+        $this->setUserId($user_id)
+            ->setAlterTime($alter_time)
+            ->setAlterType($alter_type)
+            ->setDbTable($db_table)
+            ->setForeignKey($foreign_key)
+            ->setComment($comment);
+        if ($id) {
+            $this->setId($id);
+        }
+        return $this;
+    }
+
+    /**
+     * Static method for creating Log objects
+     *
+     * @param array $values Log values
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public static function createLogWithValues(array $values)
+    {
+        return new Toolkit_UserArea_Admin_Log($values);
+    }
+
+    /**
+     * Returns an array of logs for a user
+     *
+     * @param PDO $dbh    Database Connection
+     * @param int $userId User's id
+     *
+     * @return array
+     */
+    public static function fetchLogsByUserId(PDO $dbh, $userId)
+    {
+        $logs = array();
+        try {
+            $sql = "
+              SELECT *
+                FROM logs
+               WHERE user_id = :user_id
+            ORDER BY alter_time DESC";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
+            $stmt->execute();
+            while ($values = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $logs[] = new Toolkit_UserArea_Admin_Log($values);
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $logs;
+    }
+
+    /**
+     * Return the Log id
+     *
+     * @return int
+     */
+    public function getId()
+    {
+        return (int)$this->_id;
+    }
+
+    /**
+     * Sets the Log id
+     *
+     * @param int $id Log id
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     * @throws InvalidArgumentException
+     */
+    public function setId($id)
+    {
+        if (   !is_int($id)
+            && !ctype_digit($id)
+            && $id <= 0
+        ) {
+            throw new InvalidArgumentException('Id must be an integer');
+        }
+        if (!$this->id) {
+            $this->_id = (int)$id;
+        }
+        return $this;
+    }
+
+    /**
+     * Returns Log user_id
+     *
+     * @return int
+     */
+    public function getUserId()
+    {
+        return $this->_userId;
+    }
+
+    /**
+     * Sets the Log user_id
+     *
+     * @param int $userId Log user_id
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     * @throws InvalidArgumentException
+     */
+    public function setUserId($userId)
+    {
+        if (   !is_int($userId)
+            && !ctype_digit($userId)
+            && $userId <= 0
+        ) {
+            throw new InvalidArgumentException('userId must be an integer');
+        }
+        $this->_userId = (int)$userId;
+        return $this;
+    }
+
+    /**
+     * Returns the Logs alter_time
+     *
+     * @return string
+     */
+    public function getAlterTime()
+    {
+        return $this->_alterTime;
+    }
+
+    /**
+     * Sets the Logs alter_time
+     *
+     * @param string $alterTime Logs alter_time
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public function setAlterTime($alterTime)
+    {
+        $this->_alterTime = $alterTime;
+        return $this;
+    }
+
+    /**
+     * Returns the Logs db_table
+     *
+     * @return string
+     */
+    public function getDbTable()
+    {
+        return $this->_dbTable;
+    }
+
+    /**
+     * Sets the Logs db_table
+     *
+     * @param string $dbTable Logs db_table
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public function setDbTable($dbTable)
+    {
+        $this->_dbTable = $dbTable;
+        return $this;
+    }
+
+    /**
+     * Returns Logs alter_type
+     *
+     * @return string
+     */
+    public function getAlterType()
+    {
+        return $this->_alterType;
+    }
+
+    /**
+     * Sets the Logs alter_type
+     *
+     * @param string $alterType Logs alter_type
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public function setAlterType($alterType)
+    {
+        $this->_alterType = $alterType;
+        return $this;
+    }
+
+    /**
+     * Returns the Logs foreign_key
+     *
+     * @return int
+     */
+    public function getForeignKey()
+    {
+        return (int)$this->_foreignKey;
+    }
+
+    /**
+     * Sets the Logs foreign_key
+     *
+     * @param int $foreignKey Logs foreign_key
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     * @throws InvalidArgumentException
+     */
+    public function setForeignKey($foreignKey)
+    {
+        if (!is_int($foreignKey) && !ctype_digit($foreignKey)) {
+            throw new InvalidArgumentException('foreignKey must be an integer');
+        }
+        $this->_foreignKey = (int)$foreignKey;
+        return $this;
+    }
+
+    /**
+     * Returns the Logs comments
+     *
+     * @return string
+     */
+    public function getComment()
+    {
+        return $this->_comment;
+    }
+
+    /**
+     * Sets the Logs comment
+     *
+     * @param string $comment Comment for the log
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public function setComment($comment)
+    {
+        $this->_comment = $comment;
+        return $this;
+    }
+
+
+    /**
+     * if $this->_id is set then it will run update.
+     * if $this->_id is not set then it will run insert.
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public function save(PDO $dbh)
+    {
+        if ($this->_id) {
+            $this->_update($dbh);
+        } else {
+            $this->_insert($dbh);
+        }
+        return $this;
+    }
+
+    /**
+     * Insert the record into the database
+     *
+     * @param PDO $dbh Database connection
+     *
+     * @return void
+     */
+    private function _insert(PDO $dbh)
+    {
+        try {
+            $sql = "
+            INSERT INTO
+            auth.logs
+            (user_id,alter_time,db_table,alter_type,foreign_key,comment)
+            VALUES
+            (:user_id,:alter_time,:db_table,:alter_type,:foreign_key,:comment)
+            RETURNING id";
+            $insert = $dbh->prepare($sql);
+            $insert->bindParam(':user_id', $this->_userId, PDO::PARAM_INT);
+            $insert->bindParam(':foreign_key', $this->_foreignKey, PDO::PARAM_INT);
+            $insert->bindParam(':alter_time', $this->_alterTime);
+            $insert->bindParam(':db_table', $this->_dbTable);
+            $insert->bindParam(':alter_type', $this->_alterType);
+            $insert->bindParam(':comment', $this->_comment);
+            $insert->execute();
+            $this->setId($insert->fetchColumn());
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Update the Log in the database
+     *
+     * @param PDO $dbh Database connection
+     *
+     * @return void
+     */
+    private function _update(PDO $dbh)
+    {
+        try {
+            $sql = "
+            UPDATE log
+               SET user_id = :user_id,
+                   alter_time = :alter_time,
+                   db_table = :db_table,
+                   alter_type = :alter_type,
+                   foreign_key = :foreign_key,
+                   comment = :comment
+             WHERE id = :id";
+            $update = $dbh->prepare($sql);
+            $update->bindParam(':user_id', $this->_userId, PDO::PARAM_INT);
+            $update->bindParam(':foreign_key', $this->_foreignKey, PDO::PARAM_INT);
+            $update->bindParam(':id', $this->_id, PDO::PARAM_INT);
+            $update->bindParam(':alter_time', $this->_alterTime);
+            $update->bindParam(':db_table', $this->_dbTable);
+            $update->bindParam(':alter_type', $this->_alterType);
+            $update->bindParam(':comment', $this->_comment);
+            $update->execute();
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+}
diff --git a/Toolkit/UserArea/Admin/PageTree.php b/Toolkit/UserArea/Admin/PageTree.php
new file mode 100644 (file)
index 0000000..9e88b3a
--- /dev/null
@@ -0,0 +1,150 @@
+<?php
+
+/**
+ * PageTree.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   Blocks
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Package_PageTree
+ *
+ * Display the toolbox page as ul lil list for jQuery-Column viewer
+ *
+ * @category  Toolkit
+ * @package   Blocks
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Admin_PageTree
+{
+    private $_dbh;
+    private $_rootNodeStart = "<ul class=\"menu\" id=\"demo1\">\n";
+    private $_leafStartExpanded = "\n\t<li class=\"expanded\" %s>\n";
+    private $_leafStartLeaf = "\n\t<li class=\"leaf\" %s>\n";
+    private $_subTreeStart = "\n<ul class=\"menu\">\n";
+    private $_treeEnd = "\n</ul>\n";
+    private $_leafEnd = "\n\t</li>\n";
+    private $_tree;
+
+    public function __construct(PDO $dbh)
+    {
+        $this->_dbh = $dbh;
+    }
+
+    /**
+     * creates and executes the sql query for getting the pages
+     *
+     * @return array | null
+     */
+    private function _findAll()
+    {
+        try {
+            if (defined('MEMBERS_CATEGORY')
+                && MEMBERS_CATEGORY
+            ) {
+                $sql = "
+                    SELECT id,parent,navigation_name
+                      FROM pages
+                     WHERE id NOT IN (".MEMBERS_CATEGORY.")
+                       AND parent NOT IN (".MEMBERS_CATEGORY.")
+                     ORDER by parent, pos";
+            } else {
+                $sql = "
+                    SELECT id,parent,navigation_name
+                      FROM pages
+                     ORDER by parent, pos";
+            }
+
+            return $this->_dbh
+                ->query($sql)
+                ->fetchAll(PDO::FETCH_ASSOC);
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Get all pages for the tree
+     *
+     * @return array
+     */
+    private function _fetchPages()
+    {
+        $pages = $this->_findAll();
+        if (is_array($pages)) {
+            $threads = array();
+            foreach ($pages as $page) {
+                $page['children'] = array();
+                $threads[] = $page;
+            }
+
+            $children = array();
+            while (list($key, $value) = each ($threads)) {
+                $children[$value['parent']][$value['id']] = $value;
+            }
+
+            $this->_tree = $children;
+        } else {
+            $this->_tree = array();
+        }
+    }
+
+    /**
+     * Create html of the pages tree for jqueyr.columnview
+     *
+     * @return string
+     */
+    public function toHtml()
+    {
+        $this->_fetchPages();
+        if (is_array($this->_tree)) {
+            $html = $this->createTree($this->_tree, reset($this->_tree));
+        }
+        return $html;
+    }
+
+    /**
+     * Creates the tree structure for the pages jquery column view
+     *
+     * @param array $tree  Array for tree
+     * @param type  $leaf  Array for leaf
+     * @param type  $level tree level
+     *
+     * @return string
+     */
+    protected function createTree(array $tree, $leaf, $level = 0)
+    {
+        $html = !$level ? $this->_rootNodeStart : $this->_subTreeStart;
+        if (is_array($leaf) && !empty($leaf)) {
+            while (list($parent, $branch) = each($leaf)) {
+                $pageName = htmlspecialchars($branch['navigation_name']);
+                if ($tree[$parent]) {
+                    $html .= sprintf($this->_leafStartExpanded, null);
+                    $html .= "<a href=\"#\" data-page=\"{$branch['id']}\" data-name=\"{$pageName}\">{$branch['navigation_name']} </a> ";
+                    $html .= $this->createTree($tree, $tree[$parent], $level + 1);
+                } else {
+                    $html .= sprintf($this->_leafStartLeaf, null);
+                    $html .= "<a href=\"#\" data-page=\"{$branch['id']}\" data-name=\"{$pageName}\">{$branch['navigation_name']} </a> ";
+                    $html .= $this->_leafEnd;
+                }
+            }
+        }
+        $html .= $this->_treeEnd;
+        if ($level) {
+            $html .= $this->_leafEnd;
+        }
+        return $html;
+    }
+}
diff --git a/Toolkit/UserArea/Auth.php b/Toolkit/UserArea/Auth.php
new file mode 100644 (file)
index 0000000..ce21ae0
--- /dev/null
@@ -0,0 +1,225 @@
+<?php
+
+/**
+ * Auth.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   UserArea_Auth
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_UserArea_Auth
+ *
+ * Description of Auth
+ *
+ * @category  Toolkit
+ * @package   UserArea_Auth
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Auth
+    extends Auth
+{
+
+    /**
+     * 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 = 3600;
+
+    /**
+     * Constructor
+     *
+     * Sets up the storage driver
+     *
+     * @param Config_Container              $c             Configuration object
+     * @param Toolkit_Members_AuthContainer $storageDriver 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(
+        Toolkit_UserArea_Auth_Container $storageDriver,
+        $loginFunction = '',
+        $showLogin = true
+    ) {
+        $loginFunction = array($this, 'loginForm');
+        parent::Auth($storageDriver, '', $loginFunction, $showLogin);
+        $this->setSessionName('UserArea');
+    }
+
+    /**
+     * 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 Toolkit_UserArea_Auth_LoginForm(
+            'userarea_login',
+            'post',
+           MEDIA_BASE_URL . 'userArea/login.php'
+        );
+
+        $login->setDbh(Toolkit_Database::getInstance());
+        $login->configureForm();
+        echo $login->toHtml();
+    }
+
+    /**
+     * Function to set up the forgot password form
+     *
+     * @return void
+     * @access public
+     */
+    protected function passwordForm()
+    {
+        $pword = new Toolkit_UserArea_Auth_PasswordForm('userarea_password');
+        $pword->setDbh(Toolkit_Database::getInstance());
+        $pword->configureForm();
+        echo $pword->toHtml();
+    }
+
+    /**
+     * 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);
+    }
+
+    /**
+     * Returns the current page assigned to the User
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return int
+     */
+    public function getUserPageId(PDO $dbh)
+    {
+        if ($pageId = filter_var($_SESSION['pageId'], FILTER_VALIDATE_INT)) {
+            return $pageId;
+        }
+
+        try {
+            $sql = "
+            SELECT page
+              FROM auth.users
+             WHERE id = :id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':id', $this->getAuthData('id'), PDO::PARAM_INT);
+            $stmt->execute();
+            return $stmt->fetchColumn();
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    public function getUserEventCategories(PDO $dbh)
+    {
+        try {
+            $sql = "
+            SELECT config
+              FROM auth.userapps
+             WHERE app_id = :app_id
+               AND user_id = :user_id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindValue(
+                ':app_id',
+                Toolkit_UserArea_Admin_IndexController::EVENT_APP_ID,
+                PDO::PARAM_INT
+            );
+            $stmt->bindParam(
+                ':user_id',
+                $this->getAuthData('id'),
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+            $config = $stmt->fetchColumn();
+            return ($config) ? unserialize($config) : array();
+        } catch(PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Returns Active state of User
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return bool
+     */
+    public function isUserActive(PDO $dbh)
+    {
+        try {
+            $sql = "
+            SELECT active
+              FROM auth.users
+             WHERE id = :id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':id', $this->getAuthData('id'), PDO::PARAM_INT);
+            $stmt->execute();
+            return (bool)$stmt->fetchColumn();
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Returns Active state of User
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return bool
+     */
+    public function hasToolbox(PDO $dbh)
+    {
+        try {
+            $sql = "
+            SELECT toolbox
+              FROM auth.users
+             WHERE id = :id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':id', $this->getAuthData('id'), PDO::PARAM_INT);
+            $stmt->execute();
+            return (bool)$stmt->fetchColumn();
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+
+}
diff --git a/Toolkit/UserArea/Auth/Container.php b/Toolkit/UserArea/Auth/Container.php
new file mode 100644 (file)
index 0000000..508af08
--- /dev/null
@@ -0,0 +1,185 @@
+<?php
+
+/**
+ * Authentication container for members only area
+ *
+ * Custom container which allows us to utilize our PDO Singleton which
+ * takes advantage of schema based partitioning of our tables
+ *
+ * PHP version 5
+ *
+ * The license text...
+ *
+ * @category  Toolkit
+ * @package   UserArea_Auth
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   CVS: $Id: AuthContainer.php,v 1.3 2010/06/22 11:45:34 jamie Exp $
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * Authentication container for UsarArea
+ *
+ * Custom container which allows us to utilize our PDO Singleton which
+ * takes advantage of schema based partitioning of our tables
+ *
+ * @category  Toolkit
+ * @package   UserArea_Auth
+ * @author    Jamie Kahgee <steve@gaslightmedia.com>
+ * @copyright 2010 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com/ Gaslightmedia
+ * @version   Release: @package_version@
+ * @link      <>
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_UserArea_Auth_Container
+    extends Auth_Container
+{
+
+    /**
+     * Database handler
+     * @var    PDO
+     * @access private
+     */
+       private $_dbh;
+
+       /**
+        * Addition options for the storage container
+        * @var array
+        * @access private
+        */
+       private $_options = array();
+
+    /**
+     * Constructor
+     *
+     * @param PDO   $dbh     Database handler
+     * @param array $options Addition options for the storage container
+        *
+     * @return void
+     * @access public
+     */
+       public function __construct(PDO $dbh, array $options = null)
+       {
+               $this->_dbh = $dbh;
+               $this->_setDefaults();
+               if (is_array($options)) {
+                       $this->_parseOptions($options);
+               }
+       }
+
+       /**
+        * Set some default options
+        *
+        * @access private
+        * @return void
+        */
+       private function _setDefaults()
+       {
+               $this->_options['table']       = 'auth.users';
+               $this->_options['usernamecol'] = 'username';
+               $this->_options['passwordcol'] = 'password';
+               $this->_options['db_fields']   = array('id', 'name', 'active');
+               $this->_options['cryptType']   = 'none';
+               $this->_options['db_where']    = 'active';
+       }
+
+       /**
+        * Parse options passed to the container class
+        *
+        * @param array $array options for class
+        *
+        * @access private
+        * @return void
+        */
+       private function _parseOptions(array $array)
+       {
+               foreach ($array as $key => $value) {
+                       if (isset($this->_options[$key])) {
+                               $this->_options[$key] = $value;
+                       }
+               }
+       }
+
+    /**
+     * Get the user information from the database
+     *
+     * @param string $username username to authenticate
+     * @param string $password password to authenticate against username
+        *
+     * @return boolean If the user was authenticated or not
+     * @access public
+     * @throws Toolkit_Members_Exception upon error querying DB for user
+     */
+       public function fetchData($username, $password)
+       {
+               if (   is_string($this->_options['db_fields'])
+                       && strstr($this->_options['db_fields'], '*')
+               ) {
+                       $sqlFrom = '*';
+               } else {
+                       $sqlFrom  = $this->_options['usernamecol'];
+
+                       if (strlen($fields = $this->_getDBFields()) > 0) {
+                               $sqlFrom .= ", $fields";
+                       }
+
+               }
+
+               $pword = ($this->_options['cryptType'] == 'md5') ? 'MD5(:pword)' : ':pword';
+
+               $sql = "
+            SELECT $sqlFrom
+              FROM {$this->_options['table']}
+             WHERE {$this->_options['usernamecol']} = :uname
+               AND {$this->_options['passwordcol']} = $pword";
+
+
+               //      check if there is an optional parameter db_where
+               if ($this->_options['db_where'] != '') {
+                       //      There is one, so add it to the query
+                       $sql .= " AND {$this->_options['db_where']}";
+               }
+
+               try {
+                       $stmt = $this->_dbh->prepare($sql);
+                       $stmt->bindParam(':uname', $username, PDO::PARAM_STR);
+                       $stmt->bindParam(':pword', $password, PDO::PARAM_STR);
+                       $stmt->execute();
+                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+
+                       if ($row !== false) {
+                               foreach ($row as $key => $value) {
+                                       $this->_auth_obj->setAuthData($key, $value);
+                               }
+                               return true;
+                       }
+
+                       return false;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_Members_Exception(
+                               "Error validating user `$username` - `$password`"
+                       );
+               }
+       }
+
+       /**
+        * Get extra db fields to fetch and set in the auth data
+        *
+        * @return array comma separated string of extra db fields for a SQL query
+        * @access private
+        */
+       private function _getDBFields()
+       {
+               if (isset($this->_options['db_fields'])) {
+                       if (is_array($this->_options['db_fields'])) {
+                               return implode(', ', $this->_options['db_fields']);
+                       }
+               }
+       }
+
+}
diff --git a/Toolkit/UserArea/Auth/LoginForm.php b/Toolkit/UserArea/Auth/LoginForm.php
new file mode 100644 (file)
index 0000000..fe08c63
--- /dev/null
@@ -0,0 +1,213 @@
+<?php
+
+/**
+ * LoginForm.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   UserArea_Auth
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_UserArea_Auth_LoginForm
+ *
+ * Handles rendering and validating the UserArea login form
+ *
+ * @category  Toolkit
+ * @package   UserArea_Auth
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Auth_LoginForm
+    extends Toolkit_FormBuilder
+{
+
+    /**
+     * 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';
+    protected $tpl;
+
+    /**
+     * 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()
+       {
+        $e = array();
+               $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')
+        );
+
+               $this->setupElements($e);
+       }
+
+    /**
+     * 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);
+       }
+
+    /**
+     * Helper method to setup form
+     *
+     * @param Config_Container $c Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureFilters();
+        $this->configureRules();
+    }
+
+    /**
+     * Sets up required rules and extra defined rules for the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function configureRules()
+       {
+               $this->setupRules($r);
+       }
+
+    /**
+     * 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;
+    }
+
+    /**
+     * Inject custom renderers into the forms elements for custom display
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+        $options = $GLOBALS['flexyOptions'];
+        $options['templateDir'] = BASE . 'userArea/templates';
+        $options['compiledDir'] = BASE . 'userArea/templates/compiled';
+        $this->tpl = new HTML_Template_Flexy($options);
+
+        $renderer = new HTML_QuickForm_Renderer_ObjectFlexy($this->tpl);
+
+        $this->accept($renderer);
+        $this->view = new StdClass();
+        $this->view->form = $renderer->toObject();
+        $this->tpl->compile('loginPage.html');
+       }
+
+    /**
+     * 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: ' .MEDIA_BASE_URL . 'userArea/index.php');
+               } elseif ($this->isSubmitted()) {
+                       $errors  = $this->errorMsg;
+            $this->view->errors = $errors;
+                       $output .= $this->tpl->bufferedOutputObject($this->view);
+               } 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;
+                               }
+                               $errors = "<div id=\"form-warning-top\">$error</div>";
+                $this->view->errors = $errors;
+                       }
+                       $output .= $this->tpl->bufferedOutputObject($this->view);
+               }
+
+               return $output;
+       }
+
+}
diff --git a/Toolkit/UserArea/Auth/PasswordForm.php b/Toolkit/UserArea/Auth/PasswordForm.php
new file mode 100644 (file)
index 0000000..d0c4ec3
--- /dev/null
@@ -0,0 +1,335 @@
+<?php
+
+/**
+ * PasswordForm.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   UserArea_Auth
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_UserArea_Auth_PasswordForm
+ *
+ * Handles rendering and validating the UserArea password form
+ *
+ * @category  Toolkit
+ * @package   UserArea_Auth
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Auth_PasswordForm
+{
+
+    /**
+     * 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';
+
+    /**
+     * 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 <form> 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/';
+       }
+
+    /**
+     * 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);
+               }
+       }
+
+    /**
+     * 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);
+       }
+
+    /**
+     * 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);
+       }
+
+    /**
+     * Helper method to setup form
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+    {
+        $this->configureElements();
+        $this->configureFilters();
+        $this->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);
+       }
+
+    /**
+     * 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;
+    }
+
+    /**
+     * Inject custom renderers into the forms elements for custom display
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+
+               $renderer =& $this->defaultRenderer();
+               $required = '<!-- BEGIN required --><span class="req">*</span><!-- END required -->';
+               $error    = '<!-- BEGIN error --><div class="form-warning-inside">{error}</div><!-- END error -->';
+
+               $renderer->setElementTemplate('<tr><td colspan="2" align="center">{element}</td></tr>', 'submit');
+       }
+
+    /**
+     * 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();
+               } catch (PDOException $e) {
+                       Toolkit_Common::handlError($e);
+               }
+
+               $htmlMsg
+                       = "Here is your " . SITENAME . " password:<br><br>" .
+                         "Login: {$row['member_login']}<br>" .
+                         "Email: {$values['email']}<br>" .
+                         "Password: {$row['member_passwd']}<br><br>";
+
+               $msg
+                       = "Here is your " . SITENAME . " password:\n\n" .
+                         "Login: {$row['member_login']}\n" .
+                         "Email: {$values['email']}\n" .
+                         "Password: {$row['member_passwd']}";
+
+               $mimeMail = new Mail_mime("\n");
+               $mimeMail->setHTMLBody($htmlMsg);
+               $mimeMail->setTXTBody($msg);
+
+               $body = $mimeMail->get();
+               $hdrs = $mimeMail->headers(
+                       array(
+                               'From' => DO_NOT_REPLY_EMAIL,
+                               'Subject' => 'Your ' . htmlspecialchars_decode(SITENAME) . ' Password',
+                               'Reply-To' => SITENAME . '<' . MEMBER_FORGOT_PASSWORD_EMAIL_REPLY_TO . '>'
+                       )
+               );
+
+               $mail =& Mail::factory('mail');
+
+               $res = $mail->send($values['email'], $hdrs, $body);
+
+               return PEAR::isError($res) ?
+                               Toolkit_Common::handleError($res) :
+                               $res;
+       }
+
+    /**
+     * 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   = MEDIA_BASE_URL . 'userArea/index.php';
+                               $e     =& $this->getElement('email');
+                               $email = $e->getValue();
+                               $output
+                    = "<p>Your Login Information has been sent to $email</p>" .
+                                         "<p>Continue to <a href=\"$url\">User Login</a></p>";
+                       } else {
+                               $output = '<p>Email address not found.</p>';
+                       }
+               } elseif ($this->isSubmitted()) {
+                       $output  = $this->errorMsg;
+                       $output .= parent::toHtml();
+               } else {
+                       $output .= parent::toHtml();
+               }
+
+               return $output;
+       }
+
+}
diff --git a/Toolkit/UserArea/BreadCrumbsAbstract.php b/Toolkit/UserArea/BreadCrumbsAbstract.php
new file mode 100644 (file)
index 0000000..026670a
--- /dev/null
@@ -0,0 +1,143 @@
+<?php
+
+abstract class Toolkit_UserArea_BreadCrumbsAbstract
+{
+       //      {{{     properties
+
+    protected $dbh;
+    protected $id;
+    protected $path;
+
+       //      }}}
+       //      {{{     __construct()
+
+    public function __construct(PDO $dbh, $id)
+    {
+        $this->dbh = $dbh;
+
+        if (!ctype_digit((string)$id)) {
+            throw new InvalidArgumentException(
+                "\$id must be an integer `$id` given"
+            );
+        }
+
+        $this->id = $id;
+    }
+
+       //      }}}
+       //      {{{     getPage()
+
+    protected function getPage($id)
+    {
+        try {
+            $sql = "
+                SELECT *
+                  FROM pages
+                 WHERE id = :id";
+
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+            $stmt->execute();
+
+            return $stmt->fetch(PDO::FETCH_ASSOC);
+        } catch (PDOException $e) {
+            Toolkit_Logger::logException('DB Error', $e);
+            throw new Toolkit_UserArea_Exception(
+                "Could not fetch parent for page `$id`"
+            );
+        }
+    }
+
+       //      }}}
+       //      {{{     __toString()
+
+    public function __toString()
+    {
+        return '<div id="breadcrumbs">' . $this->getPath() . '</div>';
+    }
+
+       //      }}}
+       //      {{{     getId()
+
+       /**
+        * @return the $id
+        */
+       public function getId()
+       {
+               return $this->id;
+       }
+
+       //      }}}
+       //      {{{     getPageUri()
+
+       abstract protected function getPageUri(array $page);
+
+       //      }}}
+    public function getAuthData()
+    {
+        static $authData;
+        if ($authData) {
+            return $authData;
+        }
+        $authContainer = new Toolkit_UserArea_Auth_Container(
+            Toolkit_Database::getInstance()
+        );
+        $userAuth = new Toolkit_UserArea_Auth(
+            $authContainer,
+            '',
+            false
+        );
+        $userAuth->setIdle();
+        $userAuth->start();
+        $authData = $userAuth->getAuthData();
+        return $authData;
+    }
+       //      {{{     getPath()
+
+       /**
+        * @return the $path
+        */
+       public function getPath()
+       {
+               if ($this->id == HOME_ID) {
+                       return;
+               }
+        $authData = $this->getAuthData();
+           $id = $this->id;
+           $stack = array();
+           do {
+               $page = $this->getPage($id);
+               $navigationName
+                = ($this->id == $id || $id == AUTH_USER_PAGE_ID)
+                   ? $page['navigation_name']
+                   : $this->getPageUri($page);
+
+               $stack[] = $navigationName;
+
+            if (AUTH_USER_PAGE_ID && $id == AUTH_USER_PAGE_ID) {
+                $id = 0;
+            } else {
+                $id = $page['parent'];
+            }
+           } while ($id != 0);
+
+           $reverse = array_reverse($stack);
+        $this->path = implode(' > ', $reverse);
+
+               return $this->path;
+       }
+
+       //      }}}
+       //      {{{     setId()
+
+       /**
+        * @param $id the $id to set
+        */
+       public function setId($id)
+       {
+               $this->id = $id;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/Database/application.sql b/Toolkit/UserArea/Database/application.sql
new file mode 100644 (file)
index 0000000..1edc2f1
--- /dev/null
@@ -0,0 +1,13 @@
+--
+-- Set up schema
+--
+
+CREATE SCHEMA auth;
+GRANT ALL ON SCHEMA auth TO nobody;
+
+\i ./tables/users.sql
+-- \i ./tables/logs.sql
+\i ./tables/apps.sql
+\i ./tables/userapps.sql
+
+INSERT INTO auth.users (name,username,password) VALUES ('Steve Sutton', 'steve', 'admin');
\ No newline at end of file
diff --git a/Toolkit/UserArea/Database/apps.sql b/Toolkit/UserArea/Database/apps.sql
new file mode 100644 (file)
index 0000000..8f1ec39
--- /dev/null
@@ -0,0 +1,33 @@
+--
+-- PostgreSQL database dump
+--
+
+SET statement_timeout = 0;
+SET client_encoding = 'UTF8';
+SET standard_conforming_strings = off;
+SET check_function_bodies = false;
+SET client_min_messages = warning;
+SET escape_string_warning = off;
+
+SET search_path = auth, pg_catalog;
+
+--
+-- Name: apps_id_seq; Type: SEQUENCE SET; Schema: auth; Owner: postgres
+--
+
+SELECT pg_catalog.setval('apps_id_seq', 3, true);
+
+
+--
+-- Data for Name: apps; Type: TABLE DATA; Schema: auth; Owner: postgres
+--
+
+INSERT INTO apps (id, name, page, config) VALUES (1, 'Toolbox', 'toolbox.php', true);
+INSERT INTO apps (id, name, page, config) VALUES (2, 'Events', 'CommonEvents/', false);
+INSERT INTO apps (id, name, page, config) VALUES (3, 'Photo Gallery', 'photos.php', false);
+
+
+--
+-- PostgreSQL database dump complete
+--
+
diff --git a/Toolkit/UserArea/Database/removeApplication.sql b/Toolkit/UserArea/Database/removeApplication.sql
new file mode 100644 (file)
index 0000000..d238733
--- /dev/null
@@ -0,0 +1,8 @@
+--
+--     This will drop everything in the toolbox schema.
+--     Nothing better be in here except toolbox related objects
+--     or it will be dropped
+--
+--     The force is strong w/ this one, use it wisely.
+--
+DROP SCHEMA IF EXISTS auth CASCADE;
diff --git a/Toolkit/UserArea/Database/tables/apps.sql b/Toolkit/UserArea/Database/tables/apps.sql
new file mode 100644 (file)
index 0000000..124ffc2
--- /dev/null
@@ -0,0 +1,13 @@
+DROP TABLE IF EXISTS auth.apps CASCADE;
+
+CREATE TABLE auth.apps
+(
+id SERIAL,
+name TEXT,
+page TEXT,
+config BOOLEAN DEFAULT false,
+PRIMARY KEY (id)
+);
+
+GRANT ALL ON auth.apps TO nobody;
+GRANT ALL ON auth.apps_id_seq TO nobody;
\ No newline at end of file
diff --git a/Toolkit/UserArea/Database/tables/logs.sql b/Toolkit/UserArea/Database/tables/logs.sql
new file mode 100644 (file)
index 0000000..2ce9096
--- /dev/null
@@ -0,0 +1,16 @@
+DROP TABLE IF EXISTS auth.logs CASCADE;
+
+CREATE TABLE auth.logs
+(
+id SERIAL,
+user_id INT NOT NULL,
+alter_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+db_table TEXT NOT NULL,
+alter_type TEXT,
+foreign_key INTEGER,
+comment TEXT,
+PRIMARY KEY (id)
+);
+
+GRANT ALL ON auth.logs TO nobody;
+GRANT ALL ON auth.logs_id_seq TO nobody;
\ No newline at end of file
diff --git a/Toolkit/UserArea/Database/tables/userapps.sql b/Toolkit/UserArea/Database/tables/userapps.sql
new file mode 100644 (file)
index 0000000..f5467db
--- /dev/null
@@ -0,0 +1,13 @@
+DROP TABLE IF EXISTS auth.userapps CASCADE;
+
+CREATE TABLE auth.userapps
+(
+id SERIAL,
+user_id INTEGER,
+app_id INTEGER,
+config TEXT,
+PRIMARY KEY (id)
+);
+
+GRANT ALL ON auth.userapps TO nobody;
+GRANT ALL ON auth.userapps_id_seq TO nobody;
\ No newline at end of file
diff --git a/Toolkit/UserArea/Database/tables/users.sql b/Toolkit/UserArea/Database/tables/users.sql
new file mode 100644 (file)
index 0000000..b0a75fa
--- /dev/null
@@ -0,0 +1,14 @@
+DROP TABLE IF EXISTS auth.users CASCADE;
+
+CREATE TABLE auth.users
+(
+id SERIAL,
+active BOOLEAN DEFAULT TRUE,
+name TEXT,
+username TEXT,
+password TEXT,
+PRIMARY KEY (id)
+);
+
+GRANT ALL ON auth.users TO nobody;
+GRANT ALL ON auth.users_id_seq TO nobody;
\ No newline at end of file
diff --git a/Toolkit/UserArea/DraftPagesTree.php b/Toolkit/UserArea/DraftPagesTree.php
new file mode 100644 (file)
index 0000000..46cb43f
--- /dev/null
@@ -0,0 +1,42 @@
+<?php
+class Toolkit_UserArea_DraftPagesTree extends Toolkit_UserArea_PagesTree
+{
+       //      {{{     createTree()
+
+       protected function createTree(array $tree, $leaf, $level = 0)
+       {
+               $html = !$level ? $this->rootNodeStart : $this->subTreeStart;
+
+               if (is_array($leaf) && !empty($leaf)) {
+                       foreach ($tree as $parent => $children) {
+                               foreach ($children as $branch) {
+                                       $html .= sprintf($this->leafStart, $branch['id'], null);
+                                       $previewUrl = BASE_URL . "index.php?rt=Draft&amp;catid={$branch['id']}";
+
+                                       $html .= "<strong>{$branch['navigation_name']}</strong>";
+
+                                       $html .= '<div class="right-element">';
+
+                                       $html .= '<a href="'.MEDIA_BASE_URL.'userArea/toolbox.php?rt=EditDraft&amp;id='.$branch['id'].'" class="editPage">[Edit]</a> ';
+                                       $html .= '<a href="'.MEDIA_BASE_URL.'userArea/toolbox.php?rt=ParagraphsDraft&amp;pageid='.$branch['id'].'" class="editParagraphs">[Paragraphs]</a> ';
+                                       $html .= '<a href="'.$previewUrl.'" class="pagePreview">[Preview]</a> ';
+                                       $html .= $this->getActiveBall($branch);
+
+                                       $html .= '</div>';
+
+                                       $html .= $this->leafEnd;
+                               }
+                       }
+               }
+
+               $html .= $this->treeEnd;
+               if ($level) {
+                       $html .= $this->leafEnd;
+               }
+
+               return $html;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/EditDraftController.php b/Toolkit/UserArea/EditDraftController.php
new file mode 100644 (file)
index 0000000..4b036a2
--- /dev/null
@@ -0,0 +1,218 @@
+<?php
+
+class Toolkit_UserArea_EditDraftController
+       extends Toolkit_UserArea_FormControllerAbstract
+{
+       //      {{{     cancel()
+
+       protected function cancel()
+       {
+               header('Location: ' .MEDIA_BASE_URL . 'userArea/toolbox.php?rt=EditDraft');
+               exit();
+       }
+
+       //      }}}
+
+       //      {{{     delete()
+
+       protected function delete($id)
+       {
+               $gateway = new Toolkit_UserArea_PageGatewayDraft($this->registry->dbh);
+               $gateway->delete($id);
+       }
+
+       //      }}}
+
+       //      {{{     indexAction()
+
+       public function indexAction()
+       {
+           if (ctype_digit($_GET['id'])) {
+            $breadCrumbs = new Toolkit_UserArea_PageDraftBreadCrumbs(
+                $this->registry->dbh,
+                $_GET['id']
+            );
+            $html = (string) $breadCrumbs;
+           }
+
+               $form = $this->getForm(
+                       'EditDraft',
+                       new Toolkit_UserArea_PageGatewayDraftFactory($this->registry->dbh)
+               );
+               $html .= $form->toHtml($this->registry->dbh);
+
+               return $html;
+       }
+
+       //      }}}
+
+       protected function preview($form)
+       {
+               die('preview');
+       }
+
+       //      {{{     processAction()
+
+       public function processAction()
+       {
+               return $this->processForm(
+                       'EditDraft',
+                       new Toolkit_UserArea_PageGatewayDraftFactory($this->registry->dbh),
+                       new Cache_Lite($GLOBALS['cacheOptions'])
+               );
+       }
+
+       //      }}}
+       //      {{{     publishPage()
+
+       protected function publishPage(HTML_QuickForm $form, Cache_Lite $cache)
+       {
+               $pageGatewayDraft = new Toolkit_UserArea_PageGatewayDraft(
+                       $this->registry->dbh
+               );
+               $pageGatewayPublish = new Toolkit_UserArea_PageGatewayPublish(
+                       $this->registry->dbh
+               );
+               $paragraphGatewayDraft = new Toolkit_UserArea_ParagraphGatewayDraft(
+                       $this->registry->dbh
+               );
+               $paragraphGatewayPublish = new Toolkit_UserArea_ParagraphGatewayPublish(
+                       $this->registry->dbh
+               );
+
+               if ($form->validate()) {
+                       $draftPageId = $form->getSubmitValue('id');
+                       $existingDraft = $pageGatewayDraft->find($draftPageId);
+                       if (is_null($existingDraft['published_page'])) {
+                               $publishId = $pageGatewayPublish->insert(
+                                       $form->getSubmitValues()
+                               );
+
+                               $paragraphs = $paragraphGatewayDraft->findAll(
+                                       $form->getSubmitValue('id')
+                               );
+
+                               $this->_convertOldFilesToUploadedFiles(
+                                       $paragraphGatewayPublish,
+                                       $paragraphs,
+                                       $publishId
+                               );
+                       } else {
+                $oldPageId = $existingDraft['published_page'];
+                // delete from staff
+                $deleteSql = "
+                DELETE
+                  FROM staff.staff
+                 WHERE page = :page";
+                $delete = $this->registry->dbh->prepare($deleteSql);
+                $delete->bindParam(':page', $oldPageId, PDO::PARAM_INT);
+                $delete->execute();
+                // delete from staff contacts
+                $deleteSql = "
+                DELETE
+                  FROM staff.contacts
+                 WHERE page = :page";
+                $delete = $this->registry->dbh->prepare($deleteSql);
+                $delete->bindParam(':page', $oldPageId, PDO::PARAM_INT);
+                $delete->execute();
+
+                               $pageGatewayPublish->update(
+                                       $form->getSubmitValues(),
+                                       $existingDraft['published_page']
+                               );
+
+                               $existingParagraphs = $paragraphGatewayPublish->findAll(
+                                       $existingDraft['published_page']
+                               );
+
+                               foreach ($existingParagraphs as $paragraph) {
+                                       $paragraphGatewayPublish->delete($paragraph['id']);
+                               }
+
+                               $updatedParagraphs = $paragraphGatewayDraft->findAll(
+                                       $form->getSubmitValue('id')
+                               );
+
+                               $this->_convertOldFilesToUploadedFiles(
+                                       $paragraphGatewayPublish,
+                                       $updatedParagraphs,
+                                       $existingDraft['published_page']
+                               );
+                       }
+
+                       $pageGatewayDraft->delete($draftPageId);
+            $cache->clean('Nav');
+            if ($existingDraft['published_page']) {
+                $cache->remove("page-{$existingDraft['published_page']}", 'Toolbox');
+                $cache->remove("paragraphs-{$existingDraft['published_page']}", 'Toolbox');
+                $cache->remove("sectionLinks-{$existingDraft['published_page']}", 'Toolbox');
+            }
+                       
+                       header('Location: ' .MEDIA_BASE_URL . 'userArea/toolbox.php');
+                       exit();
+               } else {
+                       $return  = $form->getErrorMessage();
+                       $return .= $form->toHtml();
+
+                       return $return;
+               }
+       }
+
+       //      }}}
+
+       //      {{{     _convertOldFilesToUploadedFiles()
+
+       private function _convertOldFilesToUploadedFiles(
+               Toolkit_UserArea_ParagraphGatewayAbstract $paragraphGateway,
+               &$paragraphs,
+               $newPageId
+       ) {
+               if (is_array($paragraphs)) {
+                       foreach ($paragraphs as &$paragraph) {
+                               if (is_array($paragraph['files'])) {
+                                       $paragraph['uploaded_files'] = array(
+                                               'urltext' => array(),
+                                               'filename' => array(),
+                                               'bytes' => array(),
+                                               'type' => array()
+                                       );
+                                       foreach ($paragraph['files'] as $file) {
+                                               $paragraph['uploaded_files']['urltext'][] = $file['urltext'];
+                                               $paragraph['uploaded_files']['filename'][] = $file['filename'];
+                                               $paragraph['uploaded_files']['bytes'][] = $file['bytes'];
+                                               $paragraph['uploaded_files']['type'][] = $file['type'];
+                                       }
+                               }
+                               $paragraph['page'] = $newPageId;
+                               $paragraphGateway->insert($paragraph);
+                       }
+               }
+       }
+
+       //      }}}
+
+       //      {{{     saveDraft()
+
+       protected function saveDraft(HTML_QuickForm $form)
+       {
+               $gateway = new Toolkit_UserArea_PageGatewayDraft($this->registry->dbh);
+               if ($form->validate()) {
+                       $pageId = $form->getSubmitValue('id');
+                       if ($pageId) {
+                               $gateway->update($form->getSubmitValues(), $pageId);
+                       } else {
+                               $gateway->insert($form->getSubmitValues());
+                       }
+                       header('Location: ' .MEDIA_BASE_URL . 'userArea/toolbox.php');
+                       exit();
+               } else {
+                       $return  = $form->getErrorMessage();
+                       $return .= $form->toHtml();
+
+                       return $return;
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/EditPageController.php b/Toolkit/UserArea/EditPageController.php
new file mode 100644 (file)
index 0000000..83ad7fb
--- /dev/null
@@ -0,0 +1,265 @@
+<?php
+
+/**
+ * EditUser.php
+ *
+ * PHP version 5
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2010 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: EditContact.php,v 1.3 2010/05/13 20:18:38 matrix Exp $
+ * @link      http://pear.php.net/package/Contacts
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * Toolkit_UserArea_EditPageController
+ *
+ * Edit Process class to insert or update a user
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2010 Steve Sutton
+ * @license   Gaslight Media
+ * @version   Release: @package_version@
+ * @link      http://pear.php.net/package/Contacts
+ * @see       References to other sections (if any)...
+ */
+class Toolkit_UserArea_EditPageController
+    extends Toolkit_UserArea_FormControllerAbstract
+{
+    //  {{{ cancel()
+
+    protected function cancel()
+    {
+        header('Location: ' .MEDIA_BASE_URL . 'userArea/toolbox.php');
+        exit();
+    }
+
+    //  }}}
+
+    //  {{{ delete ()
+
+    protected function delete($id)
+    {
+        // try to get AuthUser from registry
+        $authUser = Registry::get('Toolkit_UserArea_Auth');
+        $userId = $authUser->getAuthData('id');
+        $gateway = new Toolkit_UserArea_PageGatewayPublish($this->registry->dbh);
+        $page    = $gateway->findNavItem($id);
+
+        $logData = array(
+            'user_id'     => $userId,
+            'alter_time'  => date('m/d/Y H:i:s'),
+            'db_table'    => 'pages',
+            'alter_type'  => 'delete',
+            'foreign_key' => $id,
+            'comment'     => $page['navigation_name']
+        );
+
+        try {
+            $log = Toolkit_UserArea_Admin_Log::createLogWithValues($logData);
+            $log->save($this->registry->dbh);
+        } catch(InvalidArgumentException $e) {
+            echo $e->getTraceAsString();
+            echo $e->getMessage();
+            exit;
+        }
+
+        $gateway = new Toolkit_UserArea_PageGatewayPublish($this->registry->dbh);
+        $gateway->delete($id);
+    }
+
+    //  }}}
+
+    //  {{{ indexAction()
+
+    public function indexAction()
+    {
+        if ($pageId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+            $breadCrumbs = new Toolkit_UserArea_PageBreadCrumbs(
+                $this->registry->dbh,
+                $pageId
+            );
+            $html = (string) $breadCrumbs;
+        }
+
+        $form = $this->getForm(
+            'EditPage',
+            new Toolkit_UserArea_PageGatewayPublishFactory($this->registry->dbh)
+        );
+        $html .= $form->toHtml($this->registry->dbh);
+
+        return $html;
+    }
+
+    //  }}}
+
+    //  {{{ processAction()
+
+    public function processAction()
+    {
+        return $this->processForm(
+            'EditPage',
+            new Toolkit_UserArea_PageGatewayPublishFactory($this->registry->dbh),
+            new Cache_Lite($GLOBALS['cacheOptions'])
+        );
+    }
+
+    //  }}}
+    //  {{{ publishPage()
+
+    protected function publishPage(HTML_QuickForm $form, Cache_Lite $cache)
+    {
+        // try to get AuthUser from registry
+        $authUser = Registry::get('Toolkit_UserArea_Auth');
+        $userId = $authUser->getAuthData('id');
+        $gateway = new Toolkit_UserArea_PageGatewayPublish($this->registry->dbh);
+        if ($form->validate()) {
+
+            $pageId = $form->getSubmitValue('id');
+            if ($pageId) {
+                $gateway->update($form->getSubmitValues(), $pageId);
+
+                $logData = array(
+                    'user_id'     => $userId,
+                    'alter_time'  => date('m/d/Y H:i:s'),
+                    'db_table'    => 'pages',
+                    'alter_type'  => 'update',
+                    'foreign_key' => $pageId,
+                    'comment'     => $form->getSubmitValue('navigation_name')
+                );
+            } else {
+                $pageId = $gateway->insert($form->getSubmitValues());
+                $logData = array(
+                    'user_id'     => $userId,
+                    'alter_time'  => date('m/d/Y H:i:s'),
+                    'db_table'    => 'pages',
+                    'alter_type'  => 'insert',
+                    'foreign_key' => $pageId,
+                    'comment'     => $form->getSubmitValue('navigation_name')
+                );
+            }
+
+            try {
+                $log = Toolkit_UserArea_Admin_Log::createLogWithValues($logData);
+                $log->save($this->registry->dbh);
+            } catch(InvalidArgumentException $e) {
+                echo $e->getTraceAsString();
+                echo $e->getMessage();
+                exit;
+            }
+            $cache->clean('Nav');
+            $cache->remove("page-$pageId", 'Toolbox');
+            $cache->remove("paragraphs-$pageId", 'Toolbox');
+            $cache->remove("sectionLinks-$pageId", 'Toolbox');
+
+            header('Location: ' .MEDIA_BASE_URL . 'userArea/toolbox.php');
+            exit();
+        } else {
+            $return  = $form->getErrorMessage();
+            $return .= $form->toHtml();
+
+            return $return;
+        }
+    }
+
+    //  }}}
+
+    //  {{{ saveDraft()
+
+    protected function saveDraft(HTML_QuickForm $form)
+    {
+        $pageGatewayDraft = new Toolkit_UserArea_PageGatewayDraft(
+            $this->registry->dbh
+        );
+        $paragraphGatewayPublish = new Toolkit_UserArea_ParagraphGatewayPublish(
+            $this->registry->dbh
+        );
+        $paragraphGatewayDraft = new Toolkit_UserArea_ParagraphGatewayDraft(
+            $this->registry->dbh
+        );
+
+        if ($form->validate()) {
+            $draftId = $pageGatewayDraft->insert($form->getSubmitValues());
+
+            //  drafting an already published page,
+            //  need to bring over the paragraphs
+            if (ctype_digit($form->getSubmitValue('id'))) {
+                $paragraphs = $paragraphGatewayPublish->findAll(
+                    $form->getSubmitValue('id')
+                );
+
+                if (is_array($paragraphs)) {
+                    foreach ($paragraphs as &$paragraph) {
+                        if (is_array($paragraph['files'])) {
+                            $paragraph['uploaded_files'] = array(
+                                'urltext' => array(),
+                                'filename' => array(),
+                                'bytes' => array(),
+                                'type' => array()
+                            );
+                            foreach ($paragraph['files'] as $file) {
+                                $paragraph['uploaded_files']['urltext'][] = $file['urltext'];
+                                $paragraph['uploaded_files']['filename'][] = $file['filename'];
+                                $paragraph['uploaded_files']['bytes'][] = $file['bytes'];
+                                $paragraph['uploaded_files']['type'][] = $file['type'];
+                            }
+                        }
+                        $paragraph['page'] = $draftId;
+                        $paragraphGatewayDraft->insert($paragraph);
+                    }
+                }
+                // Need to copy over the Staff
+                try {
+                    $staffSql = "
+                    SELECT *
+                      FROM staff.staff
+                     WHERE page = :page";
+                    $staffStmt = $this->registry->dbh->prepare($staffSql);
+                    $staffStmt->bindParam(':page', $oldPageId, PDO::PARAM_INT);
+                    $staffStmt->execute();
+                    $staffData = $staffStmt->fetch(PDO::FETCH_ASSOC);
+                    unset($staffData['id']);
+                    $staffData['page'] = $draftId;
+                    $staffModel = new Toolkit_Staff_Models_Staff();
+                    $staff = $staffModel->createByValues($staffData);
+                    $staff->save($this->registry->dbh);
+                    $contactSql = "
+                    SELECT *
+                      FROM staff.contacts
+                     WHERE page = :page";
+                    $contactStmt = $this->registry->dbh->prepare($contactSql);
+                    $contactStmt->bindParam(':page', $oldPageId, PDO::PARAM_INT);
+                    $contactStmt->execute();
+                    $pos = 1;
+                    while ($row = $contactStmt->fetch(PDO::FETCH_ASSOC)) {
+                        unset($row['id']);
+                        $row['page']  = $draftId;
+                        $row['pos']   = $pos;
+                        $contactModel = new Toolkit_Staff_Models_Contact();
+                        $contact      = $contactModel->createByValues($row);
+                        $contact->save($this->registry->dbh);
+                        ++$pos;
+                    }
+                } catch (PDOException $e) {
+                    Toolkit_Common::handleError($e);
+                }
+            }
+
+            header('Location: ' .MEDIA_BASE_URL . 'userArea/toolbox.php?rt=ListDrafts');
+            exit();
+        } else {
+            $return  = $form->getErrorMessage();
+            $return .= $form->toHtml();
+
+            return $return;
+        }
+    }
+
+    //  }}}
+}
diff --git a/Toolkit/UserArea/Exception.php b/Toolkit/UserArea/Exception.php
new file mode 100644 (file)
index 0000000..dc96907
--- /dev/null
@@ -0,0 +1,3 @@
+<?php
+class Toolkit_UserArea_Exception extends Exception {}
+?>
diff --git a/Toolkit/UserArea/FileExtension.php b/Toolkit/UserArea/FileExtension.php
new file mode 100644 (file)
index 0000000..9862c4d
--- /dev/null
@@ -0,0 +1,133 @@
+<?php
+/**
+ * FileExtension.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Toolbox
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_UserArea_FileExtension
+ *
+ * Description for Toolkit_UserArea_FileExtension
+ *
+ * @category Toolkit
+ * @package  Toolbox
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_UserArea_FileExtension
+{
+       //      {{{     getImage()
+
+    /**
+     * Description for getImage()
+     * 
+     * @param string $filename File name
+     * 
+     * @return string 
+     * @access public
+     */
+       public function getImage($filename)
+       {
+               switch (pathinfo($filename, PATHINFO_EXTENSION)) {
+               case 'avi' :
+                       $img = 'avi.gif';
+                       break;
+
+               case 'mp3' :
+                       $img = 'mp3.gif';
+                       break;
+
+               case 'pdf' :
+                       $img = 'pdf.png';
+                       break;
+
+               case 'xls' :
+               case 'xlsx' :
+                       $img = 'xls.gif';
+                       break;
+
+               case 'ppt' :
+                       $img = 'ppt.gif';
+                       break;
+
+               case 'mov' :
+                       $img = 'mov.gif';
+                       break;
+
+               case 'cad' :
+                       $img = 'cad.gif';
+                       break;
+
+               case 'html' :
+                       $img = 'html.gif';
+                       break;
+
+               case 'doc' :
+               case 'docx' :
+               case 'msword' :
+                       $img = 'doc.gif';
+                       break;
+
+               case 'txt' :
+                       $img = 'txt.png';
+                       break;
+
+               case 'zip' :
+                       $img = 'zip.png';
+                       break;
+
+               case 'rar' :
+                       $img = 'rar.gif';
+                       break;
+
+               case 'png' : // image does not exist yet.
+               case 'jpeg' :
+               case 'jpg' :
+                       $img = 'jpg.gif';
+                       break;
+
+               case 'gif' :
+                       $img = 'gif.gif';
+                       break;
+
+               case 'wmv' :
+                       $img = 'wmv.gif';
+                       break;
+
+               default :
+                       $img = 'download.gif';
+                       break;
+               }
+
+               return $img;
+       }
+
+       //      }}}
+       //      {{{     getClassForType()
+
+    /**
+     * Description for getClassForType()
+     * 
+     * @param string $filename File name
+     * 
+     * @return string
+     * @access public  
+     */
+       public function getClassForType($filename)
+       {
+               $image = $this->getImage($filename);
+               $pieces = explode('.', $image);
+               reset($pieces);
+               return current($pieces);
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/UserArea/FormControllerAbstract.php b/Toolkit/UserArea/FormControllerAbstract.php
new file mode 100644 (file)
index 0000000..c345a4d
--- /dev/null
@@ -0,0 +1,118 @@
+<?php
+
+abstract class Toolkit_UserArea_FormControllerAbstract
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     getForm()
+
+       protected function getForm(
+               $controller,
+               Toolkit_UserArea_GatewayFactoryAbstract $factory
+       ) {
+               //      Need three separate objects otherwise,
+               //      new parses overwrite existing root variable data.
+
+               if (defined('MEMBERS_DB') && MEMBERS_DB) {
+                       $memConf = new Config;
+                       $memRoot =& $memConf->parseConfig(
+                               BASE . 'Toolkit/Members/config.ini',
+                               'IniFile'
+                       );
+               }
+
+               if (defined('COUPONS') && COUPONS) {
+                       $cpnConf = new Config;
+                       $cpnRoot =& $cpnConf->parseConfig(
+                               BASE . 'Toolkit/Coupons/config.ini',
+                               'IniFile'
+                       );
+               }
+               $tlbConf = new Config;
+               $tbxRoot =& $tlbConf->parseConfig(
+                       BASE . 'Toolkit/UserArea/config.ini',
+                       'IniFile'
+               );
+
+               $form = new Toolkit_UserArea_Forms_EditPage(
+                       'edit_page',
+                       'post',
+               MEDIA_BASE_URL . "userArea/toolbox.php?rt=$controller&ac=process"
+               );
+
+               $form->configureForm(
+                       $this->registry->dbh,
+                       $factory,
+                       new Toolkit_FileServer_ImageAdapter(),
+                       $memRoot,
+                       $cpnRoot
+               );
+
+               return $form;
+       }
+
+       //      }}}
+
+       //      {{{     savePage()
+
+       protected function savePage(
+               Toolkit_UserArea_PageGatewayAbstract $gateway,
+               HTML_QuickForm $form
+       ) {
+               if ($form->validate()) {
+                       $pageId = $form->getSubmitValue('id');
+                       if ($pageId) {
+                               $gateway->update($form->getSubmitValues(), $pageId);
+                       } else {
+                               $gateway->insert($form->getSubmitValues());
+                       }
+                       header('Location: ' .MEDIA_BASE_URL . 'userArea/toolbox.php');
+                       exit();
+               } else {
+                       $return  = $form->getErrorMessage();
+                       $return .= $form->toHtml();
+
+                       return $return;
+               }
+       }
+
+       //      }}}
+
+       //      {{{     processForm()
+
+       protected function processForm(
+               $controller,
+               Toolkit_UserArea_GatewayFactoryAbstract $factory,
+               Cache_Lite $cache
+       ) {
+               $form = $this->getForm($controller, $factory);
+
+               if ($form->isSubmitted()) {
+                       if ($form->getSubmitValue('cancel')) {
+                               //      do nothing
+                               $this->cancel();
+                       } elseif ($form->getSubmitValue('previewPage')) {
+                               $this->preview();
+                       } elseif ($form->getSubmitValue('saveDraft')) {
+                               //      save draft
+                               $return = $this->saveDraft($form);
+                       } elseif ($form->getSubmitValue('publishPage')) {
+                               //      publish page
+                               $return = $this->publishPage($form, $cache);
+                       } elseif ($form->getSubmitValue('deletePage')) {
+                               //      delete page
+                               $this->delete($form->getSubmitValue('id'));
+                               $navTitle = $form->getSubmitValue('navigation_name');
+                               $return = "[<b>$navTitle</b>] successfully deleted.";
+                       } else {
+                               $return  = $form->getErrorMessage();
+                               $return .= $form->toHtml();
+                       }
+               } else {
+                       $return = $form->toHtml();
+               }
+
+               return $return;
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/UserArea/Forms/EditPage.php b/Toolkit/UserArea/Forms/EditPage.php
new file mode 100644 (file)
index 0000000..6540dd2
--- /dev/null
@@ -0,0 +1,1208 @@
+<?php
+//  vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Toolbox page edit form
+ *
+ * PHP version 5
+ *
+ * @category Toolbox
+ * @package  Toolkit_UserArea
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @release  CVS: $Id: EditPage.php,v 1.10 2010/08/15 19:29:57 jamie Exp $:
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     http://demo.gaslightmedia.com
+ */
+
+require_once BASE . 'Toolkit/Forms/Rules/Image.php';
+require_once BASE . 'Toolkit/Forms/Rules/ShortUrl.php';
+
+/**
+ * Edit Toolbox page
+ *
+ * Handles form to insert/edit a toolbox page
+ *
+ * @category  Toolbox
+ * @package   Toolkit_UserArea
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_UserArea_Forms_EditPage
+    extends Toolkit_FormBuilder
+{
+    //  {{{ properties
+
+    /**
+     * How many levels deep do you want to show in the parent select list
+     *
+     * 0 = Show All Levels
+     *
+     * @var    integer
+     * @access protected
+     */
+    protected $maxDepth = 0;
+
+    /**
+     * Don't need to register any rules for this form.
+     * @var    array
+     * @access protected
+     */
+    protected $registeredRules = array();
+
+    //  }}}
+
+    //  {{{ configureConstants()
+
+    /**
+     * Configure form constants
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @return void
+     * @access public
+     */
+    public function configureConstants(PDO $dbh)
+    {
+        $c = array(
+            'id' => $_GET['id']
+        );
+
+        $this->setupConstants($c);
+    }
+
+    //  }}}
+    //  {{{ configureDefaults()
+
+    /**
+     * Initializes default form values
+     *
+     * @param Toolkit_UserArea_GatewayFactoryAbstract $factory Gateway factory
+     * @param integer                                $id      page id (optional)
+     *
+     * @return void
+     * @access public
+     */
+    public function configureDefaults(
+        Toolkit_UserArea_GatewayFactoryAbstract $factory,
+        $id = null
+    ) {
+        if (!is_null($id)) {
+            $gateway = $factory->createGateway();
+            $page = $gateway->find($id);
+        } else {
+            $page = array(
+                'template' => 1,
+                'current_image_thumb' => 'Image not yet uploaded',
+                'search_form' => 1
+            );
+        }
+        $this->setupDefaults($page);
+    }
+
+    //  }}}
+    //  {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+     * @param PDO $dbh Database handler
+     * @param Config_Container $memRoot Configuration object
+     * @param Config_Container $cpnRoot Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureElements(
+        PDO $dbh,
+        Config_Container $memRoot = null,
+        Config_Container $cpnRoot = null,
+        $id = null
+    ) {
+        $e = array();
+
+        if (!is_null($memRoot)) {
+            $pluralMem = $memRoot->getItem('section', 'listing type')
+                            ->getItem('directive', 'plural')
+                            ->getContent();
+            $singularMem = $memRoot->getItem('section', 'listing type')
+                            ->getItem('directive', 'singular')
+                            ->getContent();
+            $hasRegions = $memRoot->getItem('section', 'conf')
+                ->getItem('directive', 'regions')
+                ->getContent();
+        }
+
+        if (!is_null($cpnRoot)) {
+            $pluralCpn = $cpnRoot->getItem('section', 'listing type')
+                            ->getItem('directive', 'plural')
+                            ->getContent();
+            $singularCpn = $cpnRoot->getItem('section', 'listing type')
+                            ->getItem('directive', 'singular')
+                            ->getContent();
+        }
+
+        $hideDelete = (!is_null($id) && $id == HOME_ID);
+        $dir = dir(BASE . 'static');
+        $staticPages = array();
+        while (false !== ($page = $dir->read())) {
+            $pieces = explode('.', $page);
+            if ($pageId = filter_var($pieces[0], FILTER_VALIDATE_INT)) {
+                $staticPages[] = $pageId;
+            }
+        }
+        $hideDelete = ($hideDelete || in_array($id, $staticPages) || is_null($id));
+
+        $showParentPage = ($id != HOME_ID);
+        $auth = Registry::get('Toolkit_UserArea_Auth');
+        $authData = $auth->getAuthData();
+        if (AUTH_USER_PAGE_ID == $id) {
+            $showParentPage = false;
+            $hideDelete     = true;
+        }
+
+        //  Grouped Elements are defined here.
+        $submitBtns = array();
+
+        $submitBtns[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'publishPage',
+            'display' => 'Publish Page'
+        );
+        $submitBtns[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'saveDraft',
+            'display' => 'Save as draft'
+        );
+        $submitBtns[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'cancel',
+            'display' => 'Cancel'
+        );
+        if (!$hideDelete) {
+            $submitBtns[] = array(
+                'type'    => 'submit',
+                'req'     => false,
+                'name'    => 'deletePage',
+                'display' => 'Delete Page'
+            );
+        }
+
+        $templates = array();
+
+        $options = range(1, 6);
+        foreach ($options as $i) {
+            $img = '<img src="'
+                .MEDIA_BASE_URL.'Toolkit/UserArea/assets/template'
+                .$i.'.gif" alt="page template '.$i.'">';
+
+            $templates[] = array(
+                'type'    => 'radio',
+                'req'     => false,
+                'name'    => 'template',
+                'att'     => $i,
+                'opts'    => "Template $i<br>$img",
+            );
+        }
+
+        //  All Elements are created here.
+        //  This includes group element definitions.
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'pageContentHdr',
+            'display' => 'Page Content'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'id'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'published_page'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => true,
+            'name'    => 'navigation_name',
+            'display' => 'Navigation Name',
+            'opts' => array('size' => 35)
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'title',
+            'display' => 'Page Title',
+            'opts' => array('size' => 35)
+        );
+        if ($_GET['rt'] == 'EditPage' && $showParentPage) {
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => false,
+                'name'    => 'parent',
+                'display' => 'Parent Page',
+                'opts'    => array(),
+            );
+        } else {
+            $e[] = array(
+                'type' => 'hidden',
+                'req' => false,
+                'name' => 'parent'
+            );
+        }
+        $e[] = array(
+            'type'    => 'textarea',
+            'req'     => false,
+            'name'    => 'description',
+            'opts'    => array(
+                'cols' => 60,
+                'rows' => 60,
+                'id' => 'description'
+            ),
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type'    => 'file',
+            'req'     => false,
+            'name'    => 'file',
+            'display' => 'New Image'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'caption',
+            'display' => 'Image Caption',
+            'opts' => array('size' => 35)
+        );
+        $e[] = array(
+            'type'    => 'static',
+            'req'     => false,
+            'name'    => 'current_image_thumb',
+            'display' => 'Current Image'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'image',
+        );
+        if (!empty($this->_defaultValues['image'])
+            || ($this->isSubmitted() && $this->getSubmitValue('remove_image'))
+        ) {
+            $e[] = array(
+                'type'    => 'checkbox',
+                'req'     => false,
+                'name'    => 'remove_image',
+                'display' => 'Remove Current Image'
+            );
+        }
+
+        $e[] = array(
+            'type'    => 'html',
+            'req'     => false,
+            'name'    => '</tbody>',
+        );
+        $e[] = array(
+            'type'    => 'html',
+            'req'     => false,
+            'name'    => '<tbody id="attributes" class="section">',
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'pageAttributesHdr',
+            'display' => 'Page Attributes'
+        );
+        if (defined('SHORT_URLS') && SHORT_URLS) {
+            $e[] = array(
+                'type'    => 'static',
+                'req'     => false,
+                'name'    => 'short_url_instructions',
+                'display' => '',
+                'opts' => "Short URL's Must not contain any spaces or non alpha characters.<br>Only A-Z, a-z, 0-9, _(underscore), -(dash) allowed"
+            );
+            $e[] = array(
+                'type'    => 'text',
+                'req'     => false,
+                'name'    => 'short_url',
+                'display' => 'Short URL',
+            );
+        }
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'keyword',
+            'display' => 'Keyword',
+            'opts' => array('size' => 35)
+        );
+        $e[] = array(
+            'type'    => 'advcheckbox',
+            'req'     => false,
+            'name'    => 'paragraph_links',
+            'display' => 'Paragraph Links',
+            'opts'    => 'Show links to the paragraph headlines at the top of the page',
+            'val'     => array(0, 1)
+        );
+
+        if (!is_null($memRoot)) {
+            $e[] = array(
+                'type'    => 'html',
+                'req'     => false,
+                'name'    => '</tbody>',
+            );
+            $e[] = array(
+                'type'    => 'html',
+                'req'     => false,
+                'name'    => '<tbody id="members" class="section">',
+            );
+            $e[] = array(
+                'type'    => 'header',
+                'req'     => false,
+                'name'    => 'memberDbHdr',
+                'display' => $pluralMem,
+            );
+            $e[] = array(
+                'type'    => 'advcheckbox',
+                'req'     => false,
+                'name'    => 'include_members',
+                'display' => "Members",
+                'opts' => "Include Members On Page",
+                'val'     => array(0, 1)
+            );
+            $e[] = array(
+                'type' => 'html',
+                'req'  => false,
+                'name' => '<tr>
+                    <td class="labelcell"></td>
+                    <td class="fieldcell">
+                        To include all members, turn this feature on and
+                        don\'t select categories or regions below.<br>
+                        To restrict to specific categories, select desired
+                        categories under Category Filter.<br>
+                        To restrict to specific regions, select desired
+                        regions under Region Filter.
+                    </td>
+                </tr>'
+            );
+            //  Note that we call to populate this select list at the
+            //  bottom of this function after the element is made
+            //  so we load attributes (classes) into each option as needed.
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => false,
+                'name'    => 'member_categories',
+                'display' => 'Category Filter<br>(none = all)',
+                'opts'    => array(),
+                'att'     => array(
+                    'multiple' => 'multiple',
+                    'size'     => 7,
+                    'title' => '-- Select to Add --',
+                    'id' => 'MemberCategories'
+                )
+            );
+            if ($hasRegions) {
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => false,
+                'name'    => 'member_regions',
+                'display' => 'Region Filter<br>(none = all)',
+                'opts'    => array(),
+                'att'     => array(
+                    'multiple' => 'multiple',
+                    'size'     => 7,
+                    'title' => '-- Select to Add --',
+                    'id' => 'MemberRegions'
+                )
+            );
+            }
+            $e[] = array(
+                'type'    => 'advcheckbox',
+                'req'     => false,
+                'name'    => 'include_member_map',
+                'display' => "Google Map",
+                'opts' => "Include Map On Page",
+                'val'     => array(0, 1)
+            );
+            $e[] = array(
+                'type'    => 'advcheckbox',
+                'req'     => false,
+                'name'    => 'search_form',
+                'display' => "Search Box",
+                'opts' => 'Include Search Box',
+                'val'     => array(0, 1)
+            );
+        }
+
+        if (!is_null($cpnRoot)) {
+            $e[] = array(
+                'type'    => 'html',
+                'req'     => false,
+                'name'    => '</tbody>',
+            );
+            $e[] = array(
+                'type'    => 'html',
+                'req'     => false,
+                'name'    => '<tbody id="coupons" class="section">',
+            );
+            $e[] = array(
+                'type'    => 'header',
+                'req'     => false,
+                'name'    => 'couponsHdr',
+                'display' => $pluralCpn
+            );
+            $e[] = array(
+                'type'    => 'advcheckbox',
+                'req'     => false,
+                'name'    => 'include_coupons',
+                'display' => "Coupons",
+                'opts' => "Include Coupons On Page",
+                'val'     => array(0, 1)
+            );
+            $e[] = array(
+                'type' => 'html',
+                'req'  => false,
+                'name' => '<tr>
+                    <td class="labelcell"></td>
+                    <td class="fieldcell">
+                        To include all coupons, turn this feature on and
+                        don\'t select categories below.<br>
+                        To restrict to specific categories, select desired
+                        categories under Categories Filter.
+                    </td>
+                </tr>'
+            );
+            //  Note that we call to populate this select list at the
+            //  bottom of this function after the element is made
+            //  so we load attributes (classes) into each option as needed.
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => false,
+                'name'    => 'coupon_categories',
+                'display' => 'Category Filter<br>(none = all)',
+                'opts'    => $this->_getCouponCategories($dbh),
+                'att'     => array(
+                    'multiple' => 'multiple',
+                    'size'     => 4,
+                    'title' => '-- Select to Add --',
+                    'id' => 'CouponCategories'
+                )
+            );
+        }
+
+        $e[] = array(
+            'type'    => 'html',
+            'req'     => false,
+            'name'    => '</tbody>',
+        );
+        $e[] = array(
+            'type'    => 'html',
+            'req'     => false,
+            'name'    => '<tbody id="staff" class="section">',
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'staffHdr',
+            'display' => 'Staff'
+        );
+        $e[] = array(
+            'type'    => 'static',
+            'req'     => false,
+            'name'    => 'staff_pick',
+            'display' => '<div id="staffPick" style="border: #DDD 1px solid;">Here is staff stuff</div>'
+        );
+
+        if (defined('HOME_HEADLINES') && HOME_HEADLINES) {
+            $e[] = array(
+                'type'    => 'hidden',
+                'req'     => false,
+                'name'    => 'headline',
+                'display' => 'Headline',
+                'opts' => 'Include this page in the Home Page Headlines',
+                'val'     => array(0, 1)
+            );
+            $e[] = array(
+                'type'    => 'hidden',
+                'req'     => false,
+                'name'    => 'headline_intro',
+                'display' => 'Intro',
+                'opts' => array('size' => 55),
+                'noCharLimit' => true
+            );
+        }
+        $e[] = array(
+            'type'    => 'html',
+            'req'     => false,
+            'name'    => '</tbody>',
+        );
+        if ($_SERVER['PHP_AUTH_USER'] == 'MediaAdmin' || DEVELOPMENT) {
+            $e[] = array(
+                'type'    => 'html',
+                'req'     => false,
+                'name'    => '<tbody id="metadata" class="section">',
+            );
+            $e[] = array(
+                'type'    => 'header',
+                'req'     => false,
+                'name'    => 'metaHdr',
+                'display' => 'Metadata Information'
+            );
+            $e[] = array(
+                'type'    => 'text',
+                'req'     => false,
+                'name'    => 'meta_title',
+                'display' => 'Title Tag',
+                'opts' => array('size' => 35)
+            );
+            $e[] = array(
+                'type'    => 'textarea',
+                'req'     => false,
+                'name'    => 'meta_description',
+                'display' => 'Description',
+                'opts'    => array(
+                    'cols' => 40,
+                    'rows' => 5
+                ),
+            );
+            $e[] = array(
+                'type'    => 'html',
+                'req'     => false,
+                'name'    => '</tbody>',
+            );
+        } else {
+            $e[] = array(
+                'type'    => 'hidden',
+                'req'     => false,
+                'name'    => 'meta_title'
+            );
+            $e[] = array(
+                'type'    => 'hidden',
+                'req'     => false,
+                'name'    => 'meta_description'
+            );
+        }
+        $e[] = array(
+            'type'    => 'html',
+            'req'     => false,
+            'name'    => '<tbody id="template" class="section">',
+        );
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'templatesHdr',
+            'display' => 'Page Layout'
+        );
+        $e[] = array(
+            'type'       => 'group',
+            'req'        => false,
+            'name'       => 'page_layout',
+            'group'      => $templates,
+            'seperator'  => '',
+            'appendName' => false
+        );
+        $e[] = array(
+            'type'    => 'html',
+            'req'     => false,
+            'name'    => '</tbody>',
+        );
+        if (isset($_GET['id']) && ctype_digit($_GET['id'])) {
+            $e[] = array(
+                'type'    => 'html',
+                'req'     => false,
+                'name'    => '<tbody id="data" class="section">',
+            );
+            $e[] = array(
+                'type'    => 'header',
+                'req'     => false,
+                'name'    => 'templatesHdr',
+                'display' => 'Page Information'
+            );
+            $e[] = array(
+                'type'    => 'static',
+                'req'     => false,
+                'name'    => 'page_id',
+                'display' => 'Page ID',
+            );
+            $e[] = array(
+                'type'    => 'static',
+                'req'     => false,
+                'name'    => 'active_alt',
+                'display' => 'State',
+            );
+            $e[] = array(
+                'type'    => 'static',
+                'req'     => false,
+                'name'    => 'revised',
+                'display' => 'Revised',
+            );
+            $e[] = array(
+                'type'    => 'static',
+                'req'     => false,
+                'name'    => 'created',
+                'display' => 'Created Date',
+            );
+            $e[] = array(
+                'type'    => 'static',
+                'req'     => false,
+                'name'    => 'last_modified',
+                'display' => 'Last Modified Date',
+            );
+            $e[] = array(
+                'type'    => 'html',
+                'req'     => false,
+                'name'    => '</tbody>',
+            );
+        }
+        $e[] = array(
+            'type'    => 'html',
+            'req'     => false,
+            'name'    => '<tbody>',
+        );
+
+        //  If we are editing a page, show three submit buttons
+        //  otherwise, just show one insert button.
+        $e[] = array(
+            'type'       => 'group',
+            'req'        => false,
+            'name'       => 'submit_buttons',
+            'group'      => $submitBtns,
+            'label'      => '',
+            'seperator'  => '',
+            'appendName' => false,
+        );
+
+        $this->setupElements($e);
+
+        //  Do the same for the pages
+        if ($_GET['rt'] == 'EditPage' && $showParentPage) {
+            $this->loadParentPages($dbh);
+        }
+
+        //  Load the member categories after the elements have been created
+        //  so we can get more control how the options are rendered
+        //  ie (adding classes to them)
+        if (defined('MEMBERS_DB') && MEMBERS_DB) {
+            $this->loadMemberCategories($dbh);
+            if ($hasRegions) {
+                $this->loadMemberRegions($dbh);
+            }
+        }
+    }
+
+    //  }}}
+    //  {{{ configureFilters()
+
+    /**
+     * Form filter definitions
+     *
+     * Applies a data filter for the given fields when the form is submitted
+     *
+     * @return void
+     * @access public
+     */
+    public function configureFilters()
+    {
+        $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter'  => 'trim'
+        );
+
+        $this->setupFilters($f);
+    }
+
+    //  }}}
+    //  {{{ configureForm()
+
+    /**
+     * Bundle all form configuration calls into one function call
+     *
+     * @param PDO                                    $dbh     Database handler
+     * @param Toolkit_UserArea_GatewayFactoryAbstract $factory Gateway factory
+     * @param Toolkit_FileServer_ImageApater         $is      Image Server
+     * @param Config_Container                       $memRoot (optional) Configuration object
+     * @param Config_Container                       $cpnRoot (optional) Configuration object
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm(
+        PDO $dbh,
+        Toolkit_UserArea_GatewayFactoryAbstract $factory,
+        Toolkit_FileServer_ImageAdapter $is,
+        Config_Container $memRoot = null,
+        Config_Container $cpnRoot = null
+    ) {
+        $this->configureDefaults($factory, $_GET['id']);
+        $this->configureElements($dbh, $memRoot, $cpnRoot, $_GET['id']);
+        $this->configureRules($is);
+        $this->configureFilters();
+        $this->configureConstants($dbh);
+    }
+
+    //  }}}
+    //  {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * Adds validation rules for the given fields
+     *
+     * @param Toolkit_FileServer_ImageAdapter $is Image Server
+     *
+     * @return void
+     * @access public
+     */
+    public function configureRules(Toolkit_FileServer_ImageAdapter $is)
+    {
+        $r = array();
+
+        //  Form Rules
+        $r[] = array(
+            'element'    => 'short_url',
+            'message'    => 'ERROR: Short URLs may only contain alpha numeric characters plus - (dash) or _ (underscore)!',
+            'type'       => 'ShortUrl',
+            'format'     => null,
+            'validation' => $this->validationType,
+            'reset'      => false,
+            'force'      => false
+        );
+        if (!empty($_FILES['file']['tmp_name'])) {
+            $r[] = array(
+                'element' => 'file',
+                'message'    => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+                'type' => 'mimetype',
+                'format' => $is->getAllowedMimeTypes(),
+                'validation' => 'server',
+                'reset' => false,
+                'force' => false
+            );
+        }
+        $r[] = array(
+            'element' => 'file',
+            'message' => 'ERROR: Error uploading image!',
+            'type' => 'Image',
+            'format' => array(
+                'form' => $this,
+                'fieldName' => 'file',
+                'imageField' => 'image',
+                'is' => $is,
+                'deleteExistingImage' => false,
+                'injectImage' => array('tgtElement' => 'current_image_thumb')
+            ),
+            'validation' => 'server',
+            'reset' => false,
+            'force' => false
+        );
+
+        $this->setupRules($r);
+    }
+
+    //  }}}
+
+    // {{{ getCouponCategories()
+
+    /**
+     * Fetches all coupon categories
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @return array coupon categories
+     */
+    private function _getCouponCategories(PDO $dbh)
+    {
+        $sql = "
+            SELECT *
+              FROM coupon_category
+             ORDER BY name";
+        $couponCats = array();
+        foreach ($dbh->query($sql) as $row) {
+            $couponCats[$row['id']] = $row['name'];
+        }
+        return $couponCats;
+    }
+
+    // }}}
+
+    //  {{{ loadParentPages()
+
+    /**
+     * Load option elements into the parent select list
+     *
+     * These options are loaded via this seperate function vs inline w/ the
+     * element definition b/c we need a little more control defining
+     * the class names for each option so they will render nice when a user
+     * is looking at the list.
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @return void
+     * @throws PDOException throws exception on sql error
+     * @access public
+     */
+    public function loadParentPages(PDO $dbh)
+    {
+        try {
+            $authContainer = new Toolkit_UserArea_Auth_Container(
+                Toolkit_Database::getInstance()
+            );
+
+            $userAuth = new Toolkit_UserArea_Auth(
+                $authContainer,
+                '',
+                false
+            );
+            $userAuth->setIdle();
+            $userAuth->start();
+            $authData = $userAuth->getAuthData();
+            $page = $userAuth->getUserPageId($this->dbh);
+            //  Get a tree list of categories in linear order with
+            //  category keys in the values and their level in the tree
+            //  in the value
+            $c = Toolkit_Common::getHierarchicalTreeStructure(
+                $dbh,
+                'pages',
+                'id',
+                'parent',
+                'pos',
+                $page,
+                $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 id,navigation_name,parent
+                  FROM pages
+                 WHERE id = ?";
+
+            $stmt = $dbh->prepare($sql);
+            //  Get the member categories select list element
+            $e =& $this->getElement('parent');
+            // need to add the main page level to the array for parent pages
+            $stmt->execute(array($page));
+            $mainPage = $stmt->fetch();
+            if ($mainPage['parent'] == 0 && $_REQUEST['id'] == $mainPage['id']) {
+                $e->addOption(
+                    '-- No Parent --',
+                    0,
+                    array('class' => 'level-0')
+                );
+                return false;
+            }
+            if ($_REQUEST['id'] != $mainPage['id']) {
+                $e->addOption(
+                    $mainPage['navigation_name'],
+                    $mainPage['id'],
+                    array('class' => 'level-0')
+                );
+            }
+            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;
+                //  Add the option data to the select list.
+                $e->addOption(
+                    $row['navigation_name'],
+                    $i,
+                    array('class' => "level-$x")
+                );
+            }
+        } catch (PDOException $e) {
+            Toolkit_Logger::logException('DB error', $e);
+            throw new Toolkit_UserArea_Exception(
+                "Error loading parent pages"
+            );
+        }
+    }
+
+    //  }}}
+    //  {{{ loadMemberCategories()
+
+    /**
+     * Loads member categories into the select list
+     *
+     * Gets an array structure of the member categories in a linear tree order
+     * Then walk through the array and load each category into the select list
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @return void
+     * @access public
+     */
+    public function loadMemberCategories(PDO $dbh)
+    {
+        try {
+            //  Get a tree list of categories in linear order with
+            //  category keys in the values and their level in the tree
+            //  in the value
+            $c = Toolkit_Common::getHierarchicalTreeStructure(
+                $dbh,
+                'category',
+                'category_id',
+                'parent_id',
+                'name'
+            );
+
+            //  Get all the data about each category
+            $sql = "
+                SELECT *
+                  FROM category
+                 WHERE category_id = ?";
+
+            $stmt = $dbh->prepare($sql);
+            //  Get the member categories select list element
+            $e =& $this->getElement('member_categories');
+            if (is_array($c)) {
+                foreach ($c as $i => $j) {
+                    $stmt->execute(array($i));
+                    $row = $stmt->fetch();
+                    //  the class level is always 1 less than what is reported
+                    //  from our $c array
+                    $x = $j - 1;
+                    //  Add the option data to the select list.
+                    $e->addOption($row['name'], $i, array('class' => "level-$x"));
+                }
+            }
+        } catch (PDOException $e) {
+            Toolkit_Logger::logException('DB error', $e);
+            throw new Toolkit_UserArea_Exception(
+                "Error loading member categories"
+            );
+        }
+    }
+
+    //  }}}
+    //  {{{ loadMemberRegions()
+
+    /**
+     * Loads member Cities into the select list
+     *
+     * Gets an array structure of the member Cities in a sorted order by name
+     * Then walk through the array and load each category into the select list
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @return void
+     * @access public
+     */
+    public function loadMemberRegions(PDO $dbh)
+    {
+        try {
+            //  Get all the data about each category
+            $sql = "
+               SELECT *
+                FROM region
+            ORDER BY region_name";
+
+            $stmt = $dbh->query($sql);
+            //  Get the member categories select list element
+            $e =& $this->getElement('member_regions');
+            while ($row = $stmt->fetch()) {
+                //  Add the option data to the select list.
+                $e->addOption($row['region_name'], $row['region_id']);
+            }
+        } catch (PDOException $e) {
+            Toolkit_Logger::logException('DB error', $e);
+            throw new Toolkit_UserArea_Exception(
+                "Error loading member regions"
+            );
+        }
+    }
+
+    //  }}}
+
+    //  {{{ setMaxDepth()
+
+    /**
+     * Sets the max depth level that the parent page select list will show
+     *
+     * @param integer $md New max depth
+     *
+     * @return void
+     * @access public
+     */
+    public function setMaxDepth($md)
+    {
+        $this->maxDepth = $md;
+    }
+
+    //  }}}
+    //  {{{ setupRenderers()
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+    protected function setupRenderers()
+    {
+        parent::setupRenderers();
+        $renderer =& $this->defaultRenderer();
+
+        $required  = '<!-- BEGIN required -->';
+        $required .=    '<span class="req"> * </span>';
+        $required .= '<!-- END required -->';
+
+        $error     = '<!-- BEGIN error -->';
+        $error    .=    '<div class="req">{error}</div>';
+        $error    .= '<!-- END error -->';
+
+        $baseUrl =MEDIA_BASE_URL;
+
+        $renderer->setFormTemplate(
+            "<div class=\"webform\">\n
+                <form{attributes}>\n
+                    <div class=\"hiddenElements\">
+                        {hidden}
+                    </div>
+                    {requiredNote}
+                    <table>\n
+                        <tbody id=\"pageContent\" class=\"section\"> {content} </tbody>\n
+                    </table>\n
+                </form>\n
+            </div>"
+        );
+
+        $renderer->setElementTemplate(
+            "<tr>\n
+                <td class=\"labelcell\">$required{label}</td>\n
+                <td class=\"fieldcell\">{$error}{$baseUrl}{element}/</td>\n
+            </tr>\n",
+            'short_url'
+        );
+        $renderer->setElementTemplate(
+            "<tr align=\"center\">\n
+                <td colspan=\"2\">$required{label}$error{element}</td>
+            </tr>",
+            'description'
+        );
+        $renderer->setElementTemplate(
+            "<tr align=\"center\">\n
+                <td colspan=\"2\">$required{label}$error{element}</td>
+            </tr>",
+            'submit_buttons'
+        );
+        $renderer->setElementTemplate(
+            "<tr align=\"center\">\n
+                <td colspan=\"2\">$required{label}$error{element}</td>\n
+            </tr>",
+            'edit'
+        );
+        $renderer->setElementTemplate(
+            "<tr align=\"center\">\n
+                <td colspan=\"2\">$required{label}$error{element}</td>
+            </tr>",
+            'staff_pick'
+        );
+
+        $renderer->setElementTemplate(
+            "<tr align=\"center\">\n
+                <td colspan=\"2\">$required{label}$error{element}</td>\n
+            </tr>\n",
+            'page_layout'
+        );
+        $renderer->setGroupTemplate(
+            "<table id=\"templates\">\n
+                <tr>{content}</tr>\n
+            </table>\n",
+            'page_layout'
+        );
+        $renderer->setGroupElementTemplate(
+            "<td>\n
+                {element}<br>{label}\n
+            </td>\n",
+            'page_layout'
+        );
+    }
+
+    //  }}}
+
+    //  {{{ toHtml()
+
+    /**
+     * Handles how to display the current step the user is at in the form
+     *
+     * @return string rendered html form
+     * @access public
+     */
+    public function toHtml()
+    {
+        $GLOBALS['topScripts'][]
+            = MEDIA_APP_BASE_URL . 'libjs/jquery/jquery-1.4.2.min.js';
+        $GLOBALS['styleSheets'][]
+            = MEDIA_APP_BASE_URL . 'libjs/jqueryui/1.8.13/' .
+            'development-bundle/themes/start/jquery.ui.all.css';
+        $GLOBALS['bottomScripts'][]
+            = MEDIA_APP_BASE_URL . 'libjs/jqueryui/1.8.13/' .
+            'development-bundle/ui/jquery-ui-1.8.13.custom.js';
+        $GLOBALS['bottomScripts'][]
+            = CKEDITOR_JS . '';
+        $GLOBALS['bottomScripts'][]
+            = MEDIA_APP_BASE_URL . 'libjs/plugins/asmselect/1.0.4a/jquery.asmselect.js';
+        $GLOBALS['bottomScripts'][]
+            =MEDIA_BASE_URL . 'Toolkit/UserArea/libjs/edit-page.js?v=1';
+
+        $GLOBALS['styleSheets'][]
+            = MEDIA_APP_BASE_URL . 'libjs/plugins/asmselect/1.0.4a/jquery.asmselect.css';
+        $GLOBALS['styleSheets'][]
+            =MEDIA_BASE_URL . 'css/contactform.css';
+        $GLOBALS['styleSheets'][]
+            =MEDIA_BASE_URL . 'Toolkit/UserArea/styles.css';
+
+        $this->setupRenderers();
+
+        return parent::toHtml();
+    }
+
+    //  }}}
+}
diff --git a/Toolkit/UserArea/Forms/EditParagraph.php b/Toolkit/UserArea/Forms/EditParagraph.php
new file mode 100644 (file)
index 0000000..b530137
--- /dev/null
@@ -0,0 +1,516 @@
+<?php
+//  vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker syntax=php:
+
+/**
+ * Edit a page paragraph form
+ *
+ * PHP version 5
+ *
+ * @category Toolbox
+ * @package  Toolkit_UserArea
+ * @author   Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @version  CVS: $Id: EditParagraph.php,v 1.4 2010/07/20 18:39:40 jamie Exp $
+ * @link     http://demo.gaslightmedia.com
+ */
+
+require_once BASE . 'Toolkit/Forms/Rules/Image.php';
+
+/**
+ * Edit a page paragraph form
+ *
+ * @category  Toolbox
+ * @package   Toolkit_UserArea
+ * @author    Jamie Kahgee <jamie.kahgee@gmail.com>
+ * @copyright 2009 Jamie Kahgee
+ * @license   http://www.gaslightmedia.com Gaslightmedia
+ * @link      http://demo.gaslightmedia.com
+ */
+class Toolkit_UserArea_Forms_EditParagraph extends Toolkit_FormBuilder
+{
+    //  {{{ configureDefaults()
+
+    /**
+     * Initializes default form values
+     *
+     * @param Toolkit_UserArea_GatewayFactoryAbstract $factory Gateway factory
+     * @param integer                                $id      pargraph id (optional)
+     * @return void
+     * @access public
+     */
+    public function configureDefaults(
+        Toolkit_UserArea_GatewayFactoryAbstract $factory,
+        Toolkit_UserArea_FileExtension $fileExtension,
+        $id = null
+    ) {
+        if (!is_null($id)) {
+            $gateway = $factory->createGateway();
+            $paragraph = $gateway->find($id);
+            if (   isset($paragraph['files'])
+                && is_array($paragraph['files'])
+            ) {
+                $files = array();
+                foreach ($paragraph['files'] as $file) {
+                    $linkRenderer
+                        = Toolkit_Template_Page_FileLink_Factory::createLinkRenderer(
+                            $file
+                    );
+                    $fileLink = $linkRenderer->getLink();
+                    $extImg = $fileExtension->getImage($file['filename']);
+                    $id = preg_replace('/[^A-Za-z0-9]/', '', $file['urltext']);
+                    $files[] = '
+                        <li id="pFile-'.$file['id'].'" class="ui-state-default">
+                            <span class="ui-icon ui-icon-arrowthick-2-n-s"></span>
+                            '.$fileLink.'
+                            File Name:
+                            <input type="text" size="35" name="uploaded_files[urltext][]" value="'.htmlspecialchars($file['urltext']).'"><br>
+                            <label>
+                            <input type="checkbox" name="deleteFile[]" value="'.htmlspecialchars($file['filename']).'">
+                            Remove File
+                            </label>
+                            <input type="hidden" value="'.htmlspecialchars($file['filename']).'" name="uploaded_files[filename][]">
+                            <input type="hidden" value="'.htmlspecialchars($file['bytes']).'" name="uploaded_files[bytes][]">
+                            <input type="hidden" value="'.htmlspecialchars($file['type']).'" name="uploaded_files[type][]">
+                        </li>';
+                }
+                $paragraph['uploaded_files'] = '<ul class="files">' . implode('', $files) . '</ul>';
+            }
+        } else {
+            $paragraph = array(
+                'current_image_thumb' => 'Image not yet uploaded',
+                'page' => $_GET['pageid'],
+                'active' => true,
+            );
+        }
+
+        $this->setupDefaults($paragraph);
+    }
+
+    //  }}}
+    //  {{{ configureElements()
+
+    /**
+     * Form element definitions
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @return void
+     * @access public
+     */
+    public function configureElements(PDO $dbh)
+    {
+        $e = array();
+        //  Grouped Elements are defined here.
+        $submitBtns = array();
+
+        $submitBtns[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'saveParagraph',
+            'display' => 'Save Paragraph'
+        );
+        $submitBtns[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'cancel',
+            'display' => 'Cancel'
+        );
+        $submitBtns[] = array(
+            'type'    => 'submit',
+            'req'     => false,
+            'name'    => 'deleteParagraph',
+            'display' => 'Delete Paragraph'
+        );
+
+        //  All Elements are created here.
+        //  This includes group element definitions.
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'id'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'active'
+        );
+        if ($_GET['rt'] == 'Paragraphs') {
+            $e[] = array(
+                'type'    => 'select',
+                'req'     => false,
+                'name'    => 'page',
+                'display' => 'Page',
+                'opts'    => array(),
+            );
+        } else {
+            $e[] = array(
+                'type'    => 'hidden',
+                'req'     => false,
+                'name'    => 'page'
+            );
+        }
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'title',
+            'display' => 'Title',
+            'opts' => array('size' => 40)
+        );
+        $e[] = array(
+            'type'    => 'textarea',
+            'req'     => false,
+            'name'    => 'description',
+            'opts'    => array(
+                'cols' => 60,
+                'rows' => 60,
+                'id' => 'description'
+            ),
+            'noCharLimit' => true
+        );
+        $e[] = array(
+            'type'    => 'file',
+            'req'     => false,
+            'name'    => 'file',
+            'display' => 'New Image'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'caption',
+            'display' => 'Image Caption',
+            'opts' => array('size' => 35)
+        );
+        $e[] = array(
+            'type'    => 'static',
+            'req'     => false,
+            'name'    => 'current_image_thumb',
+            'display' => 'Current Image'
+        );
+        $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'image',
+        );
+        if (!empty($this->_defaultValues['image'])) {
+            $e[] = array(
+                'type'    => 'checkbox',
+                'req'     => false,
+                'name'    => 'remove_image',
+                'display' => 'Remove Current Image'
+            );
+        }
+        $e[] = array(
+            'type' => 'advcheckbox',
+            'req' => false,
+            'name' => 'back_to_top',
+            'display' => "Insert 'Back to Top' link",
+            'opts' => 'Yes',
+            'val' => array(0, 1)
+        );
+
+        $e[] = array(
+            'type'    => 'header',
+            'req'     => false,
+            'name'    => 'templatesHdr',
+            'display' => 'Files'
+        );
+        $e[] = array(
+            'type'    => 'text',
+            'req'     => false,
+            'name'    => 'fileurltext',
+            'display' => 'New File Name',
+            'opts' => array('size' => 35)
+        );
+        $e[] = array(
+            'type' => 'file',
+            'req' => false,
+            'name' => 'filename',
+            'display' => 'New File',
+            'opts' => array('id' => 'filename')
+        );
+        $e[] = array(
+            'type' => 'static',
+            'req' => false,
+            'name' => 'uploaded_files',
+            'display' => 'Uploaded Files',
+            'opts' => '<ul class="files"></ul>'
+        );
+
+        //  If we are editing a page, show three submit buttons
+        //  otherwise, just show one insert button.
+        $e[] = array(
+            'type'       => 'group',
+            'req'        => false,
+            'name'       => 'submit_buttons',
+            'group'      => $submitBtns,
+            'label'      => '',
+            'seperator'  => '',
+            'appendName' => false,
+        );
+
+        $this->setupElements($e);
+        //  Do the same for the pages
+        if ($_GET['rt'] == 'Paragraphs') {
+            $this->loadParagraphPages($dbh);
+        }
+    }
+
+    //  }}}
+    //  {{{ configureFilters()
+
+    /**
+     * Form filter definitions
+     *
+     * Applies a data filter for the given fields when the form is submitted
+     *
+     * @return void
+     * @access public
+     */
+    public function configureFilters()
+    {
+        $f = array();
+
+        $f[] = array(
+            'element' => '__ALL__',
+            'filter'  => 'trim'
+        );
+
+        $this->setupFilters($f);
+    }
+
+    //  }}}
+    //  {{{ configureForm()
+
+    /**
+     * Bundle all form configuration calls into one function call
+     *
+     * @param PDO $dbh Database handler              $dbh     Database handler
+     * @param Toolkit_UserArea_GatewayFactoryAbstract $factory Gateway factory
+     * @param Toolkit_FileServer_ImageAdapter        $is      Image adapter for file server
+     * @param Toolkit_FileServer_FileAdapter         $fs      File adapter for file server
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm(
+        PDO $dbh,
+        Toolkit_UserArea_GatewayFactoryAbstract $factory,
+        Toolkit_FileServer_ImageAdapter $is,
+        Toolkit_FileServer_FileAdapter $fs,
+        Toolkit_UserArea_FileExtension $fileExtension
+    ) {
+        $this->configureDefaults($factory, $fileExtension, $_GET['id']);
+        $this->configureElements($dbh);
+        $this->configureRules($is, $fs);
+        $this->configureFilters();
+    }
+
+    //  }}}
+    //  {{{ configureRules()
+
+    /**
+     * Form rule definitions
+     *
+     * Adds validation rules for the given fields
+     *
+     * @param Toolkit_FileServer_ImageAdapter $is Image adapter for file server
+     * @param Toolkit_FileServer_FileAdapter  $fs File adapter for file server
+     *
+     * @return void
+     * @access public
+     */
+    public function configureRules(
+        Toolkit_FileServer_ImageAdapter $is,
+        Toolkit_FileServer_FileAdapter $fs
+    ) {
+        $r = array();
+        //  Form Rules
+        if (!empty($_FILES['file']['tmp_name'])) {
+            $r[] = array(
+                'element' => 'file',
+                'message' => 'ERROR: Incorrect File Type (.gif, .png, .jpg) only!',
+                'type' => 'mimetype',
+                'format' => $is->getAllowedMimeTypes(),
+                'validation' => 'server',
+                'reset' => false,
+                'force' => false
+            );
+        }
+        $r[] = array(
+            'element' => 'file',
+            'message' => 'ERROR: Error uploading image!',
+            'type' => 'Image',
+            'format' => array(
+                'form' => $this,
+                'fieldName' => 'file',
+                'imageField' => 'image',
+                'is' => $is,
+                'deleteExistingImage' => false,
+                'injectImage' => array('tgtElement' => 'current_image_thumb')
+            ),
+            'validation' => 'server',
+            'reset' => false,
+            'force' => false
+        );
+
+        $this->setupRules($r);
+    }
+
+    //  }}}
+
+    //  {{{ loadParagraphPages()
+
+    /**
+     * Load option elements into the parent select list
+     *
+     * These options are loaded via this seperate function vs inline w/ the
+     * element definition b/c we need a little more control defining
+     * the class names for each option so they will render nice when a user
+     * is looking at the list.
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @return void
+     * @throws PDOException throws exception on sql error
+     * @access public
+     */
+    public function loadParagraphPages(PDO $dbh)
+    {
+        try {
+            $auth = Registry::get('Toolkit_UserArea_Auth');
+            $authData = $auth->getAuthData();
+            //  Get a tree list of categories in linear order with
+            //  category keys in the values and their level in the tree
+            //  in the value
+            $cSub = Toolkit_Common::getHierarchicalTreeStructure(
+                $dbh,
+                'pages',
+                'id',
+                'parent',
+                'pos',
+                AUTH_USER_PAGE_ID,
+                3
+            );
+            // need to add the main level to the $c array for its page
+            $c = array(AUTH_USER_PAGE_ID => 1);
+            function addOne(&$input, &$key) {
+                $input++;
+            }
+            if ($cSub) {
+                array_walk_recursive($cSub, 'addOne');
+            }
+            $c = $c + $cSub;
+
+            //  Get all the data about each category
+            $sql = "
+                SELECT *
+                  FROM pages
+                 WHERE id = ?";
+
+            $stmt = $dbh->prepare($sql);
+            //  Get the member categories select list element
+            $e =& $this->getElement('page');
+            foreach ($c as $i => $j) {
+                $stmt->execute(array($i));
+                $row = $stmt->fetch(PDO::FETCH_ASSOC);
+                //  the class level is always 1 less than what is reported
+                //  from our $c array
+                $x = $j - 1;
+                //  Add the option data to the select list.
+                $e->addOption($row['navigation_name'], $i, array('class' => "level-$x"));
+            }
+        } catch (PDOException $e) {
+            Toolkit_Logger::logException('DB error', $e);
+            throw new Toolkit_UserArea_Exception(
+                "Error loading parent pages for paragraph"
+            );
+        }
+    }
+
+    //  }}}
+
+    //  {{{ setupRenderers()
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+    protected function setupRenderers()
+    {
+        parent::setupRenderers();
+        $renderer =& $this->defaultRenderer();
+
+        $required  = '<!-- BEGIN required -->';
+        $required .=    '<span class="req"> * </span>';
+        $required .= '<!-- END required -->';
+
+        $error     = '<!-- BEGIN error -->';
+        $error    .=    '<div class="req">{error}</div>';
+        $error    .= '<!-- END error -->';
+
+        $renderer->setElementTemplate(
+            "<tr align=\"center\">\n
+                <td colspan=\"2\">$required{label}$error{element}</td>
+            </tr>",
+            'submit_buttons'
+        );
+        $renderer->setElementTemplate(
+            "<tr align=\"center\">\n
+                <td colspan=\"2\">$required{label}$error{element}</td>\n
+            </tr>",
+            'insert'
+        );
+
+        $renderer->setElementTemplate(
+            "<tr align=\"center\">\n
+                <td colspan=\"2\">$required{label}$error{element}</td>
+            </tr>",
+            'description'
+        );
+    }
+
+    //  }}}
+
+    //  {{{ toHtml()
+
+    /**
+     * Handles how to display the current step the user is at in the form
+     *
+     * @param PDO $dbh Database handler
+     *
+     * @return string rendered html form
+     * @access public
+     */
+    public function toHtml(PDO $dbh)
+    {
+        $GLOBALS['topScripts'][]
+            = MEDIA_APP_BASE_URL . 'libjs/jquery/jquery-1.4.2.min.js';
+        $GLOBALS['bottomScripts'][]
+            = MEDIA_APP_BASE_URL . 'ckeditor/current/ckeditor.js';
+        $GLOBALS['bottomScripts'][]
+            = MEDIA_APP_BASE_URL . 'libjs/plugins/ajaxUpload/3.9/ajaxupload.js';
+        $GLOBALS['bottomScripts'][]
+            = MEDIA_APP_BASE_URL . 'libjs/jqueryui/1.8.13/js/jquery-ui-1.8.13.custom.min.js';
+        $GLOBALS['bottomScripts'][]
+            = MEDIA_APP_BASE_URL . 'libjs/jqueryui/1.8.13/development-bundle/ui/minified/jquery.ui.sortable.min.js';
+        $GLOBALS['bottomScripts'][]
+            =MEDIA_BASE_URL . 'Toolkit/UserArea/libjs/edit-paragraph.js?v=1';
+
+        $GLOBALS['styleSheets'][] =MEDIA_BASE_URL . 'css/contactform.css';
+        $GLOBALS['styleSheets'][] =MEDIA_BASE_URL . 'Toolkit/UserArea/styles.css';
+        $GLOBALS['styleSheets'][]
+            = MEDIA_APP_BASE_URL . 'libjs/jqueryui/1.8.13/css/smoothness/jquery-ui-1.8.13.custom.css';
+
+        $this->setupRenderers();
+        $out
+            = ($_REQUEST['g'] == '1')
+            ? '<div class="form-success">Form Submit Successfull!</div>'
+            : '';
+
+        return $out . parent::toHtml();
+    }
+
+    //  }}}
+}
diff --git a/Toolkit/UserArea/Forms/SearchForm.php b/Toolkit/UserArea/Forms/SearchForm.php
new file mode 100644 (file)
index 0000000..92f694a
--- /dev/null
@@ -0,0 +1,174 @@
+<?php
+class Toolkit_UserArea_Forms_SearchForm
+    extends Toolkit_FormBuilder
+{
+    //  {{{ properties
+
+    /**
+     * Don't need to register any rules for this form.
+     * @var    array
+     * @access protected
+     */
+       protected $registeredRules = array();
+
+    //  }}}
+
+       //      {{{     configureConstants()
+
+    /**
+     * Form constant definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureConstants()
+       {
+        $c = array('rt' => 'Search');
+
+               $this->setupConstants($c);
+       }
+
+       //      }}}
+       //      {{{     configureElements()
+
+    /**
+     * Form element definitions
+     *
+     * @return void
+     * @access public
+     */
+       public function configureElements()
+       {
+        $e = array();
+
+               //      All Elements are created here.
+        //  This includes group element definitions.
+               $e[] = array(
+            'type'    => 'hidden',
+            'req'     => false,
+            'name'    => 'rt'
+        );
+
+        $elements = array();
+
+               $elements[] = array(
+                       'type'    => 'text',
+                       'req'     => false,
+                       'name'    => 'q',
+                       'opts' => array(
+                               'size' => 75,
+                               'id' => 'q'
+                       )
+               );
+               $elements[] = array(
+                       'type'    => 'submit',
+                       'req'     => false,
+                       'name'    => 'submit',
+                       'display' => 'Search Page Titles'
+               );
+
+               $e[] = array(
+            'type'       => 'group',
+            'req'        => false,
+            'name'       => 'fields',
+            'group'         => $elements,
+            'seperator'  => '',
+            'appendName' => false
+        );
+               $this->setupElements($e);
+       }
+
+       //      }}}
+       //      {{{     configureFilters()
+
+    /**
+     * Form filter definitions
+     *
+        * Applies a data filter for the given fields when the form is submitted
+     *
+     * @return void
+     * @access public
+     */
+       public function configureFilters()
+       {
+        $f = array();
+
+               $f[] = array(
+            'element' => '__ALL__',
+            'filter'  => 'trim'
+        );
+
+        $this->setupFilters($f);
+       }
+
+       //      }}}
+    //  {{{ configureForm()
+
+    /**
+     * Bundle all form configuration calls into one function call
+     *
+     * @return void
+     * @access public
+     */
+    public function configureForm()
+       {
+               $this->configureConstants();
+               $this->configureElements();
+               $this->configureFilters();
+    }
+
+    //  }}}
+
+       //      {{{     setupRenderers()
+
+    /**
+     * Custom rendering templates for special fields on the form
+     *
+     * @return void
+     * @access protected
+     */
+       protected function setupRenderers()
+       {
+               parent::setupRenderers();
+               $renderer =& $this->defaultRenderer();
+
+               $required  = '<!-- BEGIN required -->';
+               $required .=    '<span class="req"> * </span>';
+               $required .= '<!-- END required -->';
+
+               $error     = '<!-- BEGIN error -->';
+               $error    .=    '<div class="req">{error}</div>';
+               $error    .= '<!-- END error -->';
+
+               $renderer->setElementTemplate(
+                       "<tr>\n
+                               <td colspan=\"2\">$required{label}$error{element}</td>\n
+                       </tr>\n",
+                       'fields'
+               );
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+    /**
+     * Handles how to display the current step the user is at in the form
+     *
+     * @return string rendered html form
+     * @access public
+     */
+       public function toHtml()
+       {
+               $GLOBALS['styleSheets'][]
+                       = MEDIA_BASE_URL . 'css/contactform.css';
+               $GLOBALS['styleSheets'][]
+                       = MEDIA_BASE_URL . 'Toolkit/UserArea/styles.css';
+
+               $this->setupRenderers();
+
+               return parent::toHtml();
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/UserArea/GatewayAbstract.php b/Toolkit/UserArea/GatewayAbstract.php
new file mode 100644 (file)
index 0000000..0a7ccc0
--- /dev/null
@@ -0,0 +1,32 @@
+<?
+abstract class Toolkit_UserArea_GatewayAbstract
+{
+       //      {{{     properties
+
+       protected $dbh;
+
+       //      }}}
+       //      {{{     __construct()
+
+       public function __construct(PDO $dbh)
+       {
+               $this->dbh = $dbh;
+       }
+
+       //      }}}
+       //      {{{     find()
+
+       abstract public function find($id);
+
+       //      }}}
+       //      {{{     update()
+
+       abstract public function update(array $data, $id);
+
+       //      }}}
+       //      {{{     insert()
+
+       abstract public function insert(array $data);
+
+       //      }}}
+}
diff --git a/Toolkit/UserArea/GatewayFactoryAbstract.php b/Toolkit/UserArea/GatewayFactoryAbstract.php
new file mode 100644 (file)
index 0000000..3752254
--- /dev/null
@@ -0,0 +1,12 @@
+<?php
+abstract class Toolkit_UserArea_GatewayFactoryAbstract
+{
+       protected $dbh;
+
+       public function __construct(PDO $dbh)
+       {
+               $this->dbh = $dbh;
+       }
+
+       abstract public function createGateway();
+}
diff --git a/Toolkit/UserArea/IndexController.php b/Toolkit/UserArea/IndexController.php
new file mode 100644 (file)
index 0000000..6a5bb2f
--- /dev/null
@@ -0,0 +1,35 @@
+<?php
+
+class Toolkit_UserArea_IndexController extends Toolkit_BaseControllerAbstract
+       implements Toolkit_IController
+{
+       //      {{{     indexAction()
+
+       public function indexAction()
+       {
+               $searchForm = new Toolkit_UserArea_Forms_SearchForm(
+                       'search_form',
+                       'get',
+               MEDIA_BASE_URL . 'userArea/toolbox.php?rt=search',
+                       null,
+                       null,
+                       true
+               );
+               $searchForm->configureForm();
+
+               $html = $searchForm->toHtml();
+
+               $toolboxConfig = new Config;
+               $toolboxConfigRoot =& $toolboxConfig->parseConfig(
+                       BASE . 'Toolkit/UserArea/config.ini',
+                       'IniFile'
+               );
+               $tree = new Toolkit_UserArea_PagesTree($toolboxConfigRoot);
+               $html .= $tree->toHtml(
+                       new Toolkit_UserArea_PageGatewayPublish($this->registry->dbh)
+               );
+               return $html;
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/UserArea/ListDraftsController.php b/Toolkit/UserArea/ListDraftsController.php
new file mode 100644 (file)
index 0000000..cddea0e
--- /dev/null
@@ -0,0 +1,26 @@
+<?php
+
+class Toolkit_UserArea_ListDraftsController
+       extends Toolkit_UserArea_IndexController implements Toolkit_IController
+{
+       //      {{{     indexAction()
+
+       public function indexAction()
+       {
+
+               $toolboxConfig = new Config;
+               $toolboxConfigRoot =& $toolboxConfig->parseConfig(
+                       BASE . 'Toolkit/UserArea/config.ini',
+                       'IniFile'
+               );
+               $tree = new Toolkit_UserArea_DraftPagesTree($toolboxConfigRoot);
+               $html .= $tree->toHtml(
+                       new Toolkit_UserArea_PageGatewayDraft($this->registry->dbh)
+               );
+
+               return $html;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/Models/App.php b/Toolkit/UserArea/Models/App.php
new file mode 100644 (file)
index 0000000..dc8302b
--- /dev/null
@@ -0,0 +1,162 @@
+<?php
+
+/**
+ * User.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_UserArea_Admin_User
+ *
+ * Description of User
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Models_App
+{
+    private $_id;
+    private $_name;
+    private $_page;
+    private $_config;
+
+    const TABLE_NAME  = 'auth.apps';
+    const PRIMARY_KEY = 'id';
+    const SORT_FIELD  = 'name';
+
+    /**
+     * Creates object of type User
+     *
+     * @param array $values array values for the user fields
+     */
+    private function __construct(array $values)
+    {
+        extract($values);
+        $this->setName($name)
+            ->setPage($page)
+            ->setConfig($config);
+        if ($id) {
+            $this->setId($id);
+        }
+    }
+
+    /**
+     * Create a User from an array of values
+     *
+     * @param array $values Array values for the user fields
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    public static function createByValues(array $values)
+    {
+        return new Toolkit_UserArea_Models_App($values);
+    }
+
+
+    /**
+     * Returns the User's id
+     *
+     * @return int
+     */
+    public function getId()
+    {
+        return (int)$this->_id;
+    }
+
+    /**
+     * Sets the User's id
+     *
+     * @param int $id User's id
+     *
+     * @return Toolkit_UserArea_Admin_User
+     * @throws InvalidArgumentException
+     */
+    public function setId($id)
+    {
+        if (   !is_int($id)
+            && !ctype_digit($id)
+            && $id <= 0
+        ) {
+            throw new InvalidArgumentException(
+                'Id must be a numeric value greater than 0'
+            );
+        }
+        if (!$this->_id) {
+            $this->_id = (int)$id;
+        }
+        return $this;
+    }
+
+    /**
+     * Returns User's Name
+     *
+     * @return string
+     */
+    public function getName()
+    {
+        return $this->_name;
+    }
+
+    /**
+     * Sets the User's name
+     *
+     * @param string $name User's name
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    public function setName($name)
+    {
+        $this->_name = $name;
+        return $this;
+    }
+
+    /**
+     * Returns the User's password
+     *
+     * @return string
+     */
+    public function getPage()
+    {
+        return $this->_page;
+    }
+
+    /**
+     * Sets the User's password
+     *
+     * @param string $page User's password
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    public function setPage($page)
+    {
+        $this->_page = $page;
+        return $this;
+    }
+
+    public function getConfig()
+    {
+        return (bool)$this->_config;
+    }
+
+    public function setConfig($config)
+    {
+        $this->_config = (bool)$config;
+        return $this;
+    }
+
+
+}
diff --git a/Toolkit/UserArea/Models/Log.php b/Toolkit/UserArea/Models/Log.php
new file mode 100644 (file)
index 0000000..f5038bf
--- /dev/null
@@ -0,0 +1,370 @@
+<?php
+
+/**
+ * Log.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Package_Log
+ *
+ * Object representation of the auth.logs table record
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Models_Log
+{
+    private $_id;
+    private $_userId;
+    private $_alterTime;
+    private $_dbTable;
+    private $_alterType;
+    private $_foreignKey;
+    private $_comment;
+
+    const TABLE_NAME  = 'auth.logs';
+    const PRIMARY_KEY = 'id';
+    const SORT_FIELD  = 'alter_time';
+
+    /**
+     * Creates an object of type Log
+     *
+     * @param array $values Log values
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    private function __construct(array $values)
+    {
+        extract($values);
+        $this->setUserId($user_id)
+            ->setAlterTime($alter_time)
+            ->setAlterType($alter_type)
+            ->setDbTable($db_table)
+            ->setForeignKey($foreign_key)
+            ->setComment($comment);
+        if ($id) {
+            $this->setId($id);
+        }
+        return $this;
+    }
+
+    /**
+     * Static method for creating Log objects
+     *
+     * @param array $values Log values
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public static function createLogWithValues(array $values)
+    {
+        return new Toolkit_UserArea_Admin_Log($values);
+    }
+
+    /**
+     * Returns an array of logs for a user
+     *
+     * @param PDO $dbh    Database Connection
+     * @param int $userId User's id
+     *
+     * @return array
+     */
+    public static function fetchLogsByUserId(PDO $dbh, $userId)
+    {
+        $logs = array();
+        try {
+            $sql = "
+              SELECT *
+                FROM auth.logs
+               WHERE user_id = :user_id
+            ORDER BY alter_time DESC";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
+            $stmt->execute();
+            while ($values = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $logs[] = new Toolkit_UserArea_Admin_Log($values);
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $logs;
+    }
+
+    /**
+     * Return the Log id
+     *
+     * @return int
+     */
+    public function getId()
+    {
+        return (int)$this->_id;
+    }
+
+    /**
+     * Sets the Log id
+     *
+     * @param int $id Log id
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     * @throws InvalidArgumentException
+     */
+    public function setId($id)
+    {
+        if (   !is_int($id)
+            && !ctype_digit($id)
+            && $id <= 0
+        ) {
+            throw new InvalidArgumentException('Id must be an integer');
+        }
+        if (!$this->id) {
+            $this->_id = (int)$id;
+        }
+        return $this;
+    }
+
+    /**
+     * Returns Log user_id
+     *
+     * @return int
+     */
+    public function getUserId()
+    {
+        return $this->_userId;
+    }
+
+    /**
+     * Sets the Log user_id
+     *
+     * @param int $userId Log user_id
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     * @throws InvalidArgumentException
+     */
+    public function setUserId($userId)
+    {
+        if (   !is_int($userId)
+            && !ctype_digit($userId)
+            && $userId <= 0
+        ) {
+            throw new InvalidArgumentException('userId must be an integer');
+        }
+        $this->_userId = (int)$userId;
+        return $this;
+    }
+
+    /**
+     * Returns the Logs alter_time
+     *
+     * @return string
+     */
+    public function getAlterTime()
+    {
+        return $this->_alterTime;
+    }
+
+    /**
+     * Sets the Logs alter_time
+     *
+     * @param string $alterTime Logs alter_time
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public function setAlterTime($alterTime)
+    {
+        $this->_alterTime = $alterTime;
+        return $this;
+    }
+
+    /**
+     * Returns the Logs db_table
+     *
+     * @return string
+     */
+    public function getDbTable()
+    {
+        return $this->_dbTable;
+    }
+
+    /**
+     * Sets the Logs db_table
+     *
+     * @param string $dbTable Logs db_table
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public function setDbTable($dbTable)
+    {
+        $this->_dbTable = $dbTable;
+        return $this;
+    }
+
+    /**
+     * Returns Logs alter_type
+     *
+     * @return string
+     */
+    public function getAlterType()
+    {
+        return $this->_alterType;
+    }
+
+    /**
+     * Sets the Logs alter_type
+     *
+     * @param string $alterType Logs alter_type
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public function setAlterType($alterType)
+    {
+        $this->_alterType = $alterType;
+        return $this;
+    }
+
+    /**
+     * Returns the Logs foreign_key
+     *
+     * @return int
+     */
+    public function getForeignKey()
+    {
+        return (int)$this->_foreignKey;
+    }
+
+    /**
+     * Sets the Logs foreign_key
+     *
+     * @param int $foreignKey Logs foreign_key
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     * @throws InvalidArgumentException
+     */
+    public function setForeignKey($foreignKey)
+    {
+        if (!is_int($foreignKey) && !ctype_digit($foreignKey)) {
+            throw new InvalidArgumentException('foreignKey must be an integer');
+        }
+        $this->_foreignKey = (int)$foreignKey;
+        return $this;
+    }
+
+    /**
+     * Returns the Logs comments
+     *
+     * @return string
+     */
+    public function getComment()
+    {
+        return $this->_comment;
+    }
+
+    /**
+     * Sets the Logs comment
+     *
+     * @param string $comment Comment for the log
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public function setComment($comment)
+    {
+        $this->_comment = $comment;
+        return $this;
+    }
+
+
+    /**
+     * if $this->_id is set then it will run update.
+     * if $this->_id is not set then it will run insert.
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return Toolkit_UserArea_Admin_Log
+     */
+    public function save(PDO $dbh)
+    {
+        if ($this->_id) {
+            $this->_update($dbh);
+        } else {
+            $this->_insert($dbh);
+        }
+        return $this;
+    }
+
+    /**
+     * Insert the record into the database
+     *
+     * @param PDO $dbh Database connection
+     *
+     * @return void
+     */
+    private function _insert(PDO $dbh)
+    {
+        try {
+            $sql = "
+            INSERT INTO
+            auth.logs
+            (user_id,alter_time,db_table,alter_type,foreign_key,comment)
+            VALUES
+            (:user_id,:alter_time,:db_table,:alter_type,:foreign_key,:comment)
+            RETURNING id";
+            $insert = $dbh->prepare($sql);
+            $insert->bindParam(':user_id', $this->_userId, PDO::PARAM_INT);
+            $insert->bindParam(':foreign_key', $this->_foreignKey, PDO::PARAM_INT);
+            $insert->bindParam(':alter_time', $this->_alterTime);
+            $insert->bindParam(':db_table', $this->_dbTable);
+            $insert->bindParam(':alter_type', $this->_alterType);
+            $insert->bindParam(':comment', $this->_comment);
+            $insert->execute();
+            $this->setId($insert->fetchColumn());
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Update the Log in the database
+     *
+     * @param PDO $dbh Database connection
+     *
+     * @return void
+     */
+    private function _update(PDO $dbh)
+    {
+        try {
+            $sql = "
+            UPDATE auth.log
+               SET user_id = :user_id,
+                   alter_time = :alter_time,
+                   db_table = :db_table,
+                   alter_type = :alter_type,
+                   foreign_key = :foreign_key,
+                   comment = :comment
+             WHERE id = :id";
+            $update = $dbh->prepare($sql);
+            $update->bindParam(':user_id', $this->_userId, PDO::PARAM_INT);
+            $update->bindParam(':foreign_key', $this->_foreignKey, PDO::PARAM_INT);
+            $update->bindParam(':id', $this->_id, PDO::PARAM_INT);
+            $update->bindParam(':alter_time', $this->_alterTime);
+            $update->bindParam(':db_table', $this->_dbTable);
+            $update->bindParam(':alter_type', $this->_alterType);
+            $update->bindParam(':comment', $this->_comment);
+            $update->execute();
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+}
diff --git a/Toolkit/UserArea/Models/Mapper.php b/Toolkit/UserArea/Models/Mapper.php
new file mode 100644 (file)
index 0000000..d5e4721
--- /dev/null
@@ -0,0 +1,310 @@
+<?php
+
+/**
+ * Mapper.php
+ *
+ * PHP version 5.3
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2013 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Package_Mapper
+ *
+ * Description of Mapper
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2013 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Models_Mapper
+{
+    public function saveUserAppData(
+        PDO $dbh,
+        Toolkit_UserArea_Models_User $user,
+        $data,
+        $pages = null,
+        $categories = null
+    ) {
+        $sql = "
+        DELETE
+          FROM " . Toolkit_UserArea_Models_UserApp::TABLE_NAME . "
+         WHERE user_id = :user_id";
+        $stmt = $dbh->prepare($sql);
+        $stmt->bindParam(':user_id', $user->getId(), PDO::PARAM_INT);
+        $stmt->execute();
+        $sql = "
+        INSERT
+          INTO " . Toolkit_UserArea_Models_UserApp::TABLE_NAME . "
+        (user_id, app_id, config)
+        VALUES
+        (:user_id, :app_id, :config)";
+        $addUserApp = $dbh->prepare($sql);
+        if (is_array($data) && !empty($data)) {
+            foreach ($data as $appId => $approved) {
+                if (filter_var($approved, FILTER_VALIDATE_BOOLEAN)) {
+                    $config = '';
+                    $addUserApp->bindParam(':user_id', $user->getId(), PDO::PARAM_INT);
+                    $addUserApp->bindParam(':app_id', $appId, PDO::PARAM_INT);
+                    $addUserApp->bindParam(':config', $config);
+                    $addUserApp->execute();
+                }
+            }
+        }
+        if (isset($pages) && !empty($pages)) {
+            $appId = Toolkit_UserArea_Admin_IndexController::TOOLBOX_APP_ID;
+            foreach ($pages as $config) {
+                $addUserApp->bindParam(':user_id', $user->getId(), PDO::PARAM_INT);
+                $addUserApp->bindParam(':app_id', $appId, PDO::PARAM_INT);
+                $addUserApp->bindParam(':config', $config);
+                $addUserApp->execute();
+            }
+        }
+        if (isset($categories) && !empty($categories)) {
+            $appId = Toolkit_UserArea_Admin_IndexController::EVENT_APP_ID;
+            $config = serialize($categories);
+            $addUserApp->bindParam(':user_id', $user->getId(), PDO::PARAM_INT);
+            $addUserApp->bindParam(':app_id', $appId, PDO::PARAM_INT);
+            $addUserApp->bindParam(':config', $config);
+            $addUserApp->execute();
+        }
+    }
+
+    public function fetchAllApps(PDO $dbh)
+    {
+        $apps = new ArrayObject();
+        try {
+            $sql = "
+              SELECT " . Toolkit_UserArea_Models_App::PRIMARY_KEY . "
+                FROM " . Toolkit_UserArea_Models_App::TABLE_NAME . "
+            ORDER BY " . Toolkit_UserArea_Models_App::SORT_FIELD . " ASC";
+            $stmt = $dbh->query($sql);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $app = $this->fetchAppById($dbh, $row['id']);
+                if ($app) {
+                    $apps->offsetSet($app->getId(), $app);
+                }
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $apps;
+    }
+
+    public static function fetchAppById(PDO $dbh, $id)
+    {
+        if (   !filter_var($id, FILTER_VALIDATE_INT)
+            && $id <= 0
+        ) {
+            throw new InvalidArgumentException(
+                'Id must be a numeric value greater than 0'
+            );
+        }
+        try {
+            $sql = "
+            SELECT *
+              FROM " . Toolkit_UserArea_Models_App::TABLE_NAME . "
+             WHERE " . Toolkit_UserArea_Models_App::PRIMARY_KEY . " = :id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+            $stmt->execute();
+            $values = $stmt->fetch(PDO::FETCH_ASSOC);
+            if ($values) {
+                return Toolkit_UserArea_Models_App::createByValues(
+                    $values
+                );
+            } else {
+                return null;
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    public function fetchAllUserApps(
+        PDO $dbh,
+        Toolkit_UserArea_Models_User $user
+    ) {
+        $userApps = new ArrayObject();
+        try {
+            $sql = "
+              SELECT " . Toolkit_UserArea_Models_UserApp::PRIMARY_KEY . "
+                FROM " . Toolkit_UserArea_Models_UserApp::TABLE_NAME . "
+               WHERE user_id = :user_id
+            ORDER BY " . Toolkit_UserArea_Models_UserApp::SORT_FIELD . " ASC";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':user_id', $user->getId(), PDO::PARAM_INT);
+            $stmt->execute();
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $userApp = $this->fetchUserAppById($dbh, $row['id']);
+                if ($userApp) {
+                    $userApps->offsetSet($userApp->getId(), $userApp);
+                }
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $userApps;
+    }
+
+    public static function fetchUserAppById(PDO $dbh, $id)
+    {
+        if (   !filter_var($id, FILTER_VALIDATE_INT)
+            && $id <= 0
+        ) {
+            throw new InvalidArgumentException(
+                'Id must be a numeric value greater than 0'
+            );
+        }
+        try {
+            $sql = "
+            SELECT *
+              FROM " . Toolkit_UserArea_Models_UserApp::TABLE_NAME . "
+             WHERE " . Toolkit_UserArea_Models_UserApp::PRIMARY_KEY . " = :id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+            $stmt->execute();
+            $values = $stmt->fetch(PDO::FETCH_ASSOC);
+            if ($values) {
+                return Toolkit_UserArea_Models_UserApp::createUserFromValues(
+                    $values
+                );
+            } else {
+                return null;
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    public function fetchAllUsers(PDO $dbh)
+    {
+        $users = new ArrayObject();
+        try {
+            $sql = "
+              SELECT " . Toolkit_UserArea_Models_User::PRIMARY_KEY . "
+                FROM " . Toolkit_UserArea_Models_User::TABLE_NAME . "
+            ORDER BY " . Toolkit_UserArea_Models_User::SORT_FIELD . " ASC";
+            $stmt = $dbh->query($sql);
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $user = $this->fetchUserById($dbh, $row['id']);
+                if ($user) {
+                    $users->offsetSet($user->getId(), $user);
+                }
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $users;
+    }
+
+    public static function fetchUserById(PDO $dbh, $id)
+    {
+        if (   !filter_var($id, FILTER_VALIDATE_INT)
+            && $id <= 0
+        ) {
+            throw new InvalidArgumentException(
+                'Id must be a numeric value greater than 0'
+            );
+        }
+        try {
+            $sql = "
+            SELECT *
+              FROM " . Toolkit_UserArea_Models_User::TABLE_NAME . "
+             WHERE " . Toolkit_UserArea_Models_User::PRIMARY_KEY . " = :id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+            $stmt->execute();
+            $values = $stmt->fetch(PDO::FETCH_ASSOC);
+            if ($values) {
+                return Toolkit_UserArea_Models_User::createUserFromValues(
+                    $values
+                );
+            } else {
+                return null;
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    public function saveUser(
+        PDO $dbh,
+        Toolkit_UserArea_Models_User $user
+    ) {
+        if ($user->getId()) {
+            $sql = "
+            UPDATE " . Toolkit_UserArea_Models_User::TABLE_NAME . "
+               SET name = :name,
+                   page = :page,
+                   password = :password,
+                   username = :username,
+                   active = :active,
+                   toolbox = :toolbox
+             WHERE " . Toolkit_UserArea_Models_User::PRIMARY_KEY . " = :id";
+        } else {
+            $sql = "
+            INSERT INTO " . Toolkit_UserArea_Models_User::TABLE_NAME . "
+            (name, page, username, password, active, toolbox)
+            VALUES
+            (:name, :page, :username, :password, :active, :toolbox)
+            RETURNING " . Toolkit_UserArea_Models_User::PRIMARY_KEY;
+        }
+        try {
+            $stmt = $dbh->prepare($sql);
+
+            $stmt->bindParam(':page', $this->getPage(), PDO::PARAM_INT);
+            $stmt->bindParam(':name', $this->getName());
+            $stmt->bindParam(':username', $this->getUsername());
+            $stmt->bindParam(':password', $this->getPassword());
+            $stmt->bindParam(':active', $this->getActive(), PDO::PARAM_BOOL);
+            $stmt->bindParam(':toolbox', $this->getToolbox(), PDO::PARAM_BOOL);
+            if ($user->getId()) {
+                $stmt->bindParam(':id', $this->getId(), PDO::PARAM_INT);
+            }
+            $stmt->execute();
+            if (!$user->getId()) {
+                $user->setId($stmt->fetchColumn());
+            }
+            return $user;
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+
+    }
+
+    public function deleteUser(
+        PDO $dbh,
+        Toolkit_UserArea_Models_User $user
+    ) {
+        try {
+            $sql = "
+            DELETE
+              FROM " . Toolkit_UserArea_Models_User::TABLE_NAME . "
+             WHERE " . Toolkit_UserArea_Models_User::PRIMARY_KEY . " = :id";
+            $delete = $dbh->prepare($sql);
+            $delete->bindParam(':id', $user->getId(), PDO::PARAM_INT);
+            $delete->execute();
+            $sql = "
+            DELETE
+              FROM " . Toolkit_UserArea_Models_User::TABLE_NAME . "
+             WHERE user_id = :id";
+            $delete = $dbh->prepare($sql);
+            $delete->bindParam(':id', $user->getId(), PDO::PARAM_INT);
+            $delete->execute();
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+}
diff --git a/Toolkit/UserArea/Models/User.php b/Toolkit/UserArea/Models/User.php
new file mode 100644 (file)
index 0000000..994064a
--- /dev/null
@@ -0,0 +1,340 @@
+<?php
+
+/**
+ * User.php
+ *
+ * PHP version 5.2
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_UserArea_Admin_User
+ *
+ * Description of User
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2012 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Models_User
+{
+    private $_id;
+    private $_name;
+    private $_username;
+    private $_password;
+    private $_active;
+
+    const TABLE_NAME  = 'auth.users';
+    const PRIMARY_KEY = 'id';
+    const SORT_FIELD  = 'name';
+
+    /**
+     * Creates object of type User
+     *
+     * @param array $values array values for the user fields
+     */
+    private function __construct(array $values)
+    {
+        extract($values);
+        $this->setName($name)
+            ->setPassword($password)
+            ->setUsername($username)
+            ->setActive($active);
+        if ($id) {
+            $this->setId($id);
+        }
+    }
+
+    /**
+     * Create a User from an array of values
+     *
+     * @param array $values Array values for the user fields
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    public static function createUserFromValues(array $values)
+    {
+        return new Toolkit_UserArea_Models_User($values);
+    }
+
+    /**
+     * Fetches the database record for an id and returns an User Object
+     *
+     * @param PDO $dbh Databes Connection
+     * @param int $id  Id for record
+     *
+     * @return Toolkit_UserArea_Admin_User|null
+     * @throws InvalidArgumentException
+     */
+    public static function fetchUserById(PDO $dbh, $id)
+    {
+        if (   !is_int($id)
+            && !ctype_digit($id)
+            && $id <= 0
+        ) {
+            throw new InvalidArgumentException(
+                'Id must be a numeric value greater than 0'
+            );
+        }
+        try {
+            $sql = "
+            SELECT *
+              FROM auth.users
+             WHERE id = :id";
+            $stmt = $dbh->prepare($sql);
+            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+            $stmt->execute();
+            $values = $stmt->fetch(PDO::FETCH_ASSOC);
+            if ($values) {
+                return new Toolkit_UserArea_Models_User($values);
+            } else {
+                return null;
+            }
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+    /**
+     * Returns the User's id
+     *
+     * @return int
+     */
+    public function getId()
+    {
+        return (int)$this->_id;
+    }
+
+    /**
+     * Sets the User's id
+     *
+     * @param int $id User's id
+     *
+     * @return Toolkit_UserArea_Admin_User
+     * @throws InvalidArgumentException
+     */
+    public function setId($id)
+    {
+        if (   !is_int($id)
+            && !ctype_digit($id)
+            && $id <= 0
+        ) {
+            throw new InvalidArgumentException(
+                'Id must be a numeric value greater than 0'
+            );
+        }
+        if (!$this->_id) {
+            $this->_id = (int)$id;
+        }
+        return $this;
+    }
+
+    /**
+     * Returns User's Name
+     *
+     * @return string
+     */
+    public function getName()
+    {
+        return $this->_name;
+    }
+
+    /**
+     * Sets the User's name
+     *
+     * @param string $name User's name
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    public function setName($name)
+    {
+        $this->_name = $name;
+        return $this;
+    }
+
+    /**
+     * Returns the User's username
+     *
+     * @return string
+     */
+    public function getUsername()
+    {
+        return $this->_username;
+    }
+
+    /**
+     * Sets the User's username
+     *
+     * @param string $username User's username
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    public function setUsername($username)
+    {
+        $this->_username = $username;
+        return $this;
+    }
+
+    /**
+     * Returns the User's password
+     *
+     * @return string
+     */
+    public function getPassword()
+    {
+        return $this->_password;
+    }
+
+    /**
+     * Sets the User's password
+     *
+     * @param string $password User's password
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    public function setPassword($password)
+    {
+        $this->_password = $password;
+        return $this;
+    }
+
+    /**
+     * Returns the active state of the User
+     *
+     * @return bool
+     */
+    public function getActive()
+    {
+        return (bool)$this->_active;
+    }
+
+    /**
+     * Sets the User's Active state
+     *
+     * @param bool $active User's active state
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    public function setActive($active)
+    {
+        $this->_active = (bool)$active;
+        return $this;
+    }
+
+    /**
+     * If the id is set then it will update else it inserts record into database
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    public function save(PDO $dbh)
+    {
+        if ($this->_id) {
+            $this->_update($dbh);
+        } else {
+            $this->_insert($dbh);
+        }
+        return $this;
+    }
+
+    /**
+     * Updates the record in the databas
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    private function _update(PDO $dbh)
+    {
+        try {
+            $sql = "
+            UPDATE auth.users
+               SET name = :name,
+                   password = :password,
+                   username = :username,
+                   active = :active
+             WHERE id = :id";
+            $update = $dbh->prepare($sql);
+            $update->bindParam(':id', $this->getId(), PDO::PARAM_INT);
+            $update->bindParam(':name', $this->getName());
+            $update->bindParam(':username', $this->getUsername());
+            $update->bindParam(':password', $this->getPassword());
+            $update->bindParam(':active', $this->getActive(), PDO::PARAM_BOOL);
+            $update->execute();
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $this;
+    }
+
+    /**
+     * Insert the record into the database
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    private function _insert(PDO $dbh)
+    {
+        try {
+            $sql = "
+            INSERT INTO auth.users
+            (name, username, password, active)
+            VALUES
+            (:name, :username, :password, :active)
+            RETURNING id";
+            $insert = $dbh->prepare($sql);
+            $insert->bindParam(':name', $this->getName());
+            $insert->bindParam(':username', $this->getUsername());
+            $insert->bindParam(':password', $this->getPassword());
+            $insert->bindParam(':active', $this->getActive(), PDO::PARAM_BOOL);
+            $insert->execute();
+            $this->setId($insert->fetchColumn());
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+        return $this;
+    }
+
+    /**
+     * Delete the record from the databas
+     *
+     * @param PDO $dbh Database Connection
+     *
+     * @return void
+     */
+    public function delete(PDO $dbh)
+    {
+        try {
+            $sql = "
+            DELETE
+              FROM auth.users
+             WHERE id = :id";
+            $delete = $dbh->prepare($sql);
+            $delete->bindParam(':id', $this->getId(), PDO::PARAM_INT);
+            $delete->execute();
+//            $sql = "
+//            DELETE
+//              FROM auth.logs
+//             WHERE user_id = :id";
+//            $delete = $dbh->prepare($sql);
+//            $delete->bindParam(':id', $this->getId(), PDO::PARAM_INT);
+//            $delete->execute();
+        } catch (PDOException $e) {
+            Toolkit_Common::handleError($e);
+        }
+    }
+
+}
diff --git a/Toolkit/UserArea/Models/UserApp.php b/Toolkit/UserArea/Models/UserApp.php
new file mode 100644 (file)
index 0000000..faa2070
--- /dev/null
@@ -0,0 +1,129 @@
+<?php
+
+/**
+ * UserApp.php
+ *
+ * PHP version 5.3
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2013 Gaslight Media
+ * @license   Gaslight Media
+ * @version   SVN: (0.1)
+ * @link      <>
+ */
+
+/**
+ * Toolkit_Package_UserApp
+ *
+ * Description of UserApp
+ *
+ * @category  Toolkit
+ * @package   UserArea
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2013 Gaslight Media
+ * @license   Gaslight Media
+ * @release   Release: (0.1)
+ * @link      <>
+ */
+class Toolkit_UserArea_Models_UserApp
+{
+    private $id;
+    private $userId;
+    private $appId;
+    private $config;
+
+    const TABLE_NAME  = 'auth.userapps';
+    const PRIMARY_KEY = 'id';
+    const SORT_FIELD  = 'id';
+
+    /**
+     * Creates object of type User
+     *
+     * @param array $values array values for the user fields
+     */
+    private function __construct(array $values)
+    {
+        extract($values);
+        $this->setAppId($app_id)
+            ->setConfig($config)
+            ->setUserId($user_id);
+        if ($id) {
+            $this->setId($id);
+        }
+    }
+
+    /**
+     * Create a User from an array of values
+     *
+     * @param array $values Array values for the user fields
+     *
+     * @return Toolkit_UserArea_Admin_User
+     */
+    public static function createUserFromValues(array $values)
+    {
+        return new Toolkit_UserArea_Models_UserApp($values);
+    }
+
+    public function getId()
+    {
+        return (int)$this->id;
+    }
+
+    public function setId($id)
+    {
+        if (!filter_var($id, FILTER_VALIDATE_INT)) {
+            throw new InvalidArgumentException(
+                'Id must be a numeric value'
+            );
+        }
+        $this->id = (int)$id;
+        return $this;
+    }
+
+    public function getUserId()
+    {
+        return (int)$this->userId;
+    }
+
+    public function setUserId($userId)
+    {
+        if (!filter_var($userId, FILTER_VALIDATE_INT)) {
+            throw new InvalidArgumentException(
+                'userId must be a numeric value'
+            );
+        }
+        $this->userId = (int)$userId;
+        return $this;
+    }
+
+    public function getAppId()
+    {
+        return (int)$this->appId;
+    }
+
+    public function setAppId($appId)
+    {
+        if (!filter_var($appId, FILTER_VALIDATE_INT)) {
+            throw new InvalidArgumentException(
+                'appId must be a numeric value'
+            );
+        }
+        $this->appId = (int)$appId;
+        return $this;
+    }
+
+    public function getConfig()
+    {
+        return $this->config;
+    }
+
+    public function setConfig($config)
+    {
+        $this->config = $config;
+        return $this;
+    }
+
+
+}
diff --git a/Toolkit/UserArea/Navigation.php b/Toolkit/UserArea/Navigation.php
new file mode 100644 (file)
index 0000000..68ef6e5
--- /dev/null
@@ -0,0 +1,105 @@
+<?php
+
+class Toolkit_UserArea_Navigation extends Toolkit_NavigationAbstract
+       implements Toolkit_INavigation
+{
+       //      {{{     __construct()
+
+       public function __construct(
+               HTML_Menu $menu,
+               HTML_Menu_Renderer $rEngine
+       ) {
+               $this->menu      = $menu;
+               $this->rEngine   = $rEngine;
+               $this->currIndex = 'listToolbox';
+       }
+
+       //      }}}
+       //      {{{     setNavTemplates()
+
+       protected function setNavTemplates()
+       {
+               $tpl = '<li><a href="%s" title="%s">{Title}</a></li>';
+               $this->rEngine->setEntryTemplate(
+                       HTML_MENU_ENTRY_INACTIVE,
+                       sprintf($tpl, '{url}', '{desc}', '{Title}')
+               );
+               $this->rEngine->setEntryTemplate(
+                       HTML_MENU_ENTRY_ACTIVE,
+                       sprintf($tpl, '{url}', '{desc}', '{Title}')
+               );
+               $this->rEngine->setEntryTemplate(
+                       HTML_MENU_ENTRY_ACTIVEPATH,
+                       sprintf($tpl, '{url}', '{desc}', '{Title}')
+               );
+               $this->rEngine->setMenuTemplate('', '');
+               $this->rEngine->setRowTemplate('<ul class="admin_nav">', '</ul>');
+       }
+
+       //      }}}
+       //      {{{     setCurrentIndex()
+
+       protected function setCurrentIndex()
+       {
+               $this->menu->forceCurrentIndex($_GET['rt']);
+       }
+
+       //      }}}
+       //      {{{     getNavSructure()
+       //      @codeCoverageIgnoreStart
+
+    /**
+     * Sets up a multi dimensional array used for the nav structure
+        *
+        * @param Config_Container $c Application configuration
+     *
+     * @return array navigational array hash
+     * @access public
+     */
+       public function getNavStructure(Config_Container $c)
+       {
+        //  get reference to [listing type] section of config file
+        $appName = $c->getItem('section', 'conf')
+                         ->getItem('directive', 'applicationName')
+                         ->getContent();
+
+               $nav = array(
+                       'publishedPages' => array(
+                               'Title' => "Published Pages",
+                               'url' =>MEDIA_BASE_URL . 'userArea/toolbox.php',
+                               'desc' => "Display all the published pages",
+                       ),
+                       'draftPages' => array(
+                               'Title' => 'Page Drafts',
+                               'url' =>MEDIA_BASE_URL . 'userArea/toolbox.php?rt=ListDrafts',
+                               'desc' => 'Display all the page drafts'
+
+                       ),
+                       'editPage' => array(
+                               'Title' => "Create New Page",
+                               'url' =>MEDIA_BASE_URL . 'userArea/toolbox.php?rt=EditPage',
+                               'desc' => "Create a new {$appName} Page"
+                       ),
+               );
+
+               if (isset($_GET['rt']) && $_GET['rt'] == 'Paragraphs') {
+                       $nav['editParagraph'] = array(
+                               'Title' => "Create Page Paragraph",
+                               'url' =>MEDIA_BASE_URL . "userArea/toolbox.php?rt=Paragraphs&ac=edit&pageid={$_GET['pageid']}",
+                               'desc' => "Edit a Page Paragraph"
+                       );
+               } elseif (isset($_GET['rt']) && $_GET['rt'] == 'ParagraphsDraft') {
+                       $nav['editParagraph'] = array(
+                               'Title' => "Create Page Paragraph",
+                               'url' =>MEDIA_BASE_URL . "userArea/toolbox.php?rt=ParagraphsDraft&ac=edit&pageid={$_GET['pageid']}",
+                               'desc' => "Edit a Page Paragraph"
+                       );
+               }
+
+               return $nav;
+       }
+
+       //      @codeCoverageIgnoreEnd
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/Page.php b/Toolkit/UserArea/Page.php
new file mode 100644 (file)
index 0000000..485e285
--- /dev/null
@@ -0,0 +1,322 @@
+<?php
+class Toolkit_UserArea_Page
+{
+       //      {{{     properties
+       public $content;
+       public $members;
+       public $coupons;
+       public $attributes;
+       public $headlines;
+       public $metaData;
+
+       private $_createDate;
+       private $_lastModifiedDate;
+       private $_revisions;
+       private $_active;
+
+       //      }}}
+
+       //      {{{     __construct()
+       public function __construct(
+               Toolkit_UserArea_ComponentFactory $cf,
+               array $data,
+               $id = null
+       ) {
+               if (!empty($id)) {
+                       if (ctype_digit($id)) {
+                               $this->_id = (int) $id;
+                       } else {
+                               throw new Toolkit_UserArea_Exception("Invalid page id `$id`");
+                       }
+               }
+
+               $this->content           = $cf->getComponent('content', $data);
+               $this->members           = $cf->getComponent('members', $data);
+               $this->coupons           = $cf->getComponent('coupons', $data);
+               $this->attributes        = $cf->getComponent('attributes', $data);
+               $this->headlines         = $cf->getComponent('headlines', $data);
+               $this->metaData          = $cf->getComponent('metadata', $data);
+               $this->_createDate       = $data['createDate'];
+               $this->_lastModifiedDate = $data['lastModifiedDate'];
+               $this->_revisions        = $data['revisions'];
+       }
+
+       //      }}}
+
+       //      {{{     delete()
+
+       /**
+        * Delete a toolbox page
+        *
+        * @param PDO $dbh Database handler
+        * @param integer $id Toolbox page id to delete
+        *
+        * @return boolean Result of delete query
+        * @access public
+        * @throws Toolkit_UserArea_Exception
+        */
+       public static function delete(PDO $dbh, $id)
+       {
+               try {
+                       $sql = "
+                DELETE FROM bus_category
+                 WHERE id = :id";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       return $stmt->execute();
+               } catch(PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Error deleting the toolbox page `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     fetch()
+
+       public static function fetch(PDO $dbh, $id)
+       {
+               if (!ctype_digit((string)$id)) {
+                       throw new Toolkit_UserArea_Exception("Invalid page id `$id`");
+               }
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM bus_category
+                                WHERE id = :id";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $d = $stmt->fetch();
+
+                       $sql = "
+                               SELECT *
+                                 FROM bus_cat_member
+                                WHERE catid = :id";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       $d['memberCat'] = array();
+                       while ($row = $stmt->fetch()) {
+                               $d['memberCat'][] = $row['memb_type'];
+                       }
+
+                       $sql = "
+                               SELECT *
+                                 FROM coupon_categories2toolbox_pages
+                                WHERE toolbox_catid = :id";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       $d['couponCat'] = array();
+                       while ($row = $stmt->fetch()) {
+                               $d['couponCat'][] = $row['category_id'];
+                       }
+
+                       $sql = "
+                SELECT CASE
+                       WHEN active THEN 'Active'
+                       ELSE 'In-Active'
+                       END AS active
+                  FROM bus_category
+                 WHERE id = :id";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch();
+                       $d['active'] = $row['active'];
+
+                       $sql = "
+                               SELECT to_char(min(revision_timestamp), 'FMDay, DD Month FMHH12:MIpm') AS created,
+                                      to_char(max(revision_timestamp), 'FMDay, DD Month FMHH12:MIpm') AS last_modified,
+                                          count(*) AS total
+                  FROM bus_category_history
+                 WHERE id = :id";
+
+                       $stmt = $dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $stmt->execute();
+                       $row = $stmt->fetch();
+                       $d['revisions'] = $row['total'];
+                       $d['createDate'] = $row['created'];
+                       $d['lastModifiedDate'] = $row['last_modified'];
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Error retrieving defaults for page `$id`"
+                       );
+               }
+
+               return new self(new Toolkit_UserArea_ComponentFactory(), $d, $id);
+       }
+
+       //      }}}
+       //      {{{     getBusCategoryData()
+       public function getBusCategoryData()
+       {
+               if ($this->content->getRemoveImage()) {
+                       $this->content->setImage(Toolkit_UserArea_ImageFactory::getImage());
+                       $this->content->setImageName(null);
+               }
+               return array(
+                       'intro' => $this->content->getIntro(),
+                       'description' => $this->content->getDescription(),
+                       'image' => $this->content->getImage()->getSrc(),
+                       'imagename' => $this->content->getImageName(),
+                       'parent' => $this->attributes->getParent(),
+                       'category' => $this->attributes->getCategory(),
+                       'keyword' => $this->attributes->getKeyword(),
+                       'template' => $this->attributes->getTemplate(),
+                       'section_links' => $this->attributes->getSectionLinks(),
+                       'short_url' => $this->attributes->getShortUrl(),
+                       'featured' => $this->headlines->getFeatured(),
+                       'feature_intro' => $this->headlines->getFeatureIntro(),
+                       'no_search_form' => $this->members->getSearch(),
+                       'include_member_map' => $this->members->getMap(),
+                       'meta_descr' => $this->metaData->getDescription(),
+                       'title' => $this->metaData->getTitle(),
+               );
+       }
+
+       //      }}}
+
+       //      {{{     save()
+       public function save(PDO $dbh)
+       {
+               try {
+                       $dbh->beginTransaction();
+
+                       $busCategoryData = $this->getBusCategoryData();
+
+                       $busCategorySql = Toolkit_Common::createSQLInsert(
+                               'bus_category',
+                               array_keys($busCategoryData)
+                       );
+
+                       $stmt = Toolkit_Common::prepareQuery(
+                               $dbh,
+                               'bus_category',
+                               $busCategorySql,
+                               $busCategoryData
+                       );
+
+                       $stmt->execute();
+                       $catidSql = "
+                               SELECT *
+                                 FROM bus_category
+                                ORDER BY id DESC LIMIT 1";
+
+                       $row = $dbh->query($catidSql)->fetch(PDO::FETCH_ASSOC);
+                       $this->_id = (int) $row['id'];
+
+                       $this->coupons->saveCategories($dbh, $this->_id);
+                       $this->members->saveCategories($dbh, $this->_id);
+
+                       return $dbh->commit();
+               } catch (PDOException $e) {
+                       $dbh->rollback();
+                       Toolkit_Logger::logException('db error', $e);
+                       throw new Toolkit_UserArea_Exception('Error saving page in Database');
+               }
+       }
+
+       //      }}}
+
+       //      {{{     update()
+       public function update(PDO $dbh)
+       {
+               try {
+                       if (!isset($this->_id)) {
+                               throw new RuntimeException('Page does not exist yet');
+                       }
+                       $dbh->beginTransaction();
+
+                       $busCategoryData = $this->getBusCategoryData();
+
+                       $busCategorySql = Toolkit_Common::createSQLUpdate(
+                               'bus_category',
+                               array_keys($busCategoryData),
+                               array("id = {$this->_id}")
+                       );
+
+                       $stmt = Toolkit_Common::prepareQuery(
+                               $dbh,
+                               'bus_category',
+                               $busCategorySql,
+                               $busCategoryData
+                       );
+
+                       $stmt->execute();
+
+                       $this->coupons->updateCategories($dbh, $this->_id);
+                       $this->members->updateCategories($dbh, $this->_id);
+
+                       return $dbh->commit();
+
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('db error', $e);
+                       throw new Toolkit_UserArea_Exception('Error updating page in Database');
+               } catch (RuntimeException $e) {
+                       Toolkit_Logger::logException('Runtime Error', $e);
+                       throw new Toolkit_UserArea_Exception($e->getMessage());
+               }
+       }
+
+       //      }}}
+
+       //      {{{     getCreateDate()
+
+       public function getCreateDate()
+       {
+               return $this->_createDate;
+       }
+
+       //      }}}
+       //      {{{     getLastModificationDate()
+
+       public function getLastModificationDate()
+       {
+               return $this->_lastModifiedDate;
+       }
+
+       //      }}}
+       //      {{{     getNumberOfRevisions()
+
+       public function getNumberOfRevisions()
+       {
+               return $this->_revisions;
+       }
+
+       //      }}}
+       //      {{{     getActive()
+
+       public function getActive()
+       {
+               return $this->_active;
+       }
+
+       //      }}}
+       //      {{{     getActiveText()
+
+       public function getActiveText()
+       {
+               return $this->_active ? 'Active' : 'In-Active';
+       }
+
+       //      }}}
+
+       public function getId()
+       {
+           return $this->_id;
+       }
+}
+?>
diff --git a/Toolkit/UserArea/PageBreadCrumbs.php b/Toolkit/UserArea/PageBreadCrumbs.php
new file mode 100644 (file)
index 0000000..5cb3942
--- /dev/null
@@ -0,0 +1,12 @@
+<?php
+
+class Toolkit_UserArea_PageBreadCrumbs
+       extends Toolkit_UserArea_BreadCrumbsAbstract
+{
+       protected function getPageUri(array $page)
+       {
+           $uri = BASE_URL . "userArea/toolbox.php?rt=EditPage&amp;id={$page['id']}";
+           return "<a href=\"{$uri}\">{$page['navigation_name']}</a>";
+       }
+}
+?>
diff --git a/Toolkit/UserArea/PageDraftBreadCrumbs.php b/Toolkit/UserArea/PageDraftBreadCrumbs.php
new file mode 100644 (file)
index 0000000..914ddaa
--- /dev/null
@@ -0,0 +1,72 @@
+<?php
+
+class Toolkit_UserArea_PageDraftBreadCrumbs
+       extends Toolkit_UserArea_BreadCrumbsAbstract
+{
+       //      {{{     getPageUri()
+
+       protected function getPageUri(array $page)
+       {
+           $uri =MEDIA_BASE_URL . "userArea/toolbox.php?rt=EditPage&id={$page['id']}";
+           return "<a href=\"{$uri}\">{$page['navigation_name']}</a>";
+       }
+
+       //      }}}
+       //      {{{     getDraft()
+
+    protected function getDraft($id)
+    {
+        try {
+            $sql = "
+                SELECT *
+                  FROM pages_draft
+                 WHERE id = :id";
+
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+            $stmt->execute();
+
+            return $stmt->fetch(PDO::FETCH_ASSOC);
+        } catch (PDOException $e) {
+            Toolkit_Logger::logException('DB Error', $e);
+            throw new Toolkit_UserArea_Exception(
+                "Could not fetch parent for page `$id`"
+            );
+        }
+    }
+
+       //      }}}
+       //      {{{     getPath()
+
+       /**
+        * @return the $path
+        */
+       public function getPath()
+       {
+               if ($this->id == HOME_ID) {
+                       return;
+               }
+
+               $draft = $this->getDraft($this->id);
+               $stack = array($draft['navigation_name']);
+
+               $publishedPage = $this->getPage($draft['published_page']);
+               $id = $publishedPage['parent'];
+               while ($id != 0) {
+               $page = $this->getPage($id);
+
+               $navigationName = $this->getPageUri($page);
+
+               $stack[] = $navigationName;
+               $id = $page['parent'];
+           }
+
+           $reverse = array_reverse($stack);
+        $this->path = implode(' > ', $reverse);
+
+               return $this->path;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/PageGatewayAbstract.php b/Toolkit/UserArea/PageGatewayAbstract.php
new file mode 100644 (file)
index 0000000..defb275
--- /dev/null
@@ -0,0 +1,280 @@
+<?php
+abstract class Toolkit_UserArea_PageGatewayAbstract
+       extends Toolkit_UserArea_GatewayAbstract
+{
+       protected $page;
+
+       //      {{{     hasMemberDb()
+
+       protected function hasMemberDb()
+       {
+               return (defined('MEMBERS_DB') && MEMBERS_DB);
+       }
+
+       //      }}}
+       //      {{{     hasCouponDb()
+
+       protected function hasCouponDb()
+       {
+               return (defined('COUPONS') && COUPONS);
+       }
+
+       //      }}}
+       //      {{{     hasHeadlines()
+
+       protected function hasHeadlines()
+       {
+               return (defined('HOME_HEADLINES') && HOME_HEADLINES);
+       }
+
+       //      }}}
+       //      {{{     hasPhotoGallery()
+
+       protected function hasPhotoGallery()
+       {
+               return (defined('PHOTO_GALLERY') && PHOTO_GALLERY);
+       }
+
+       //      }}}
+
+       //      {{{     findAll()
+
+       abstract public function findAll();
+
+       //      }}}
+       //      {{{     findAllByParent()
+
+       public function findAllByParent($parent)
+       {
+               try {
+                       $sql = "
+                               SELECT id,navigation_name,parent,active
+                                 FROM pages
+                                WHERE parent = :parent
+                                ORDER by parent, pos";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':parent', $parent, PDO::PARAM_INT);
+                       $stmt->execute();
+                       return $stmt->fetchAll(PDO::FETCH_ASSOC);
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Error fetching all pages by parent `$parent`"
+                       );
+               }
+       }
+
+       //      }}}
+       //      {{{     findByKeyword()
+
+       abstract public function findByKeyword($keyword);
+
+       //      }}}
+       //      {{{     findTopParent()
+
+       abstract public function findTopParent($pageId);
+
+       //      }}}
+       //      {{{     findPage()
+
+       protected function findPage($id, $pageSql)
+       {
+        //     if the page has already been fetched, just return it.
+               if (is_array($this->page) && $this->page['id'] == $id) {
+                       return $this->page;
+               }
+
+               $pageStatsSql = "
+                       SELECT count(*) AS revised,
+                               MIN(revision_timestamp) AS created,
+                           MAX(revision_timestamp) AS last_modified
+              FROM pages_history
+             WHERE id = :id";
+
+               $pageStmt = $this->dbh->prepare($pageSql);
+               $pageStmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $pageStmt->execute();
+
+               $page = $pageStmt->fetch(PDO::FETCH_ASSOC);
+
+               if ($page === false) { // Page doesn't exist
+                       return false;
+               }
+
+               if ($this->hasMemberDb()) {
+                       $page['member_categories']
+                               = $this->getMemberCategoriesForPage($id);
+                       $page['member_regions']
+                               = $this->getMemberRegionsForPage($id);
+               }
+
+               if ($this->hasCouponDb()) {
+                       $page['coupon_categories']
+                               = $this->getCouponCategoriesForPage($id);
+               }
+
+               if ($this->hasPhotoGallery()) {
+                       $page['photo_galleries']
+                               = $this->getPhotoGalleriesForPage($id);
+               }
+
+               $pageStatsStmt = $this->dbh->prepare($pageStatsSql);
+               $pageStatsStmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $pageStatsStmt->execute();
+
+               $pageStats = $pageStatsStmt->fetch(PDO::FETCH_ASSOC);
+
+               $date = new Date();
+               $date->setDate(strtotime($pageStats['created']), DATE_FORMAT_UNIXTIME);
+               $pageStats['created'] = $date->format('%D %r');
+               $date->setDate(strtotime($pageStats['last_modified']), DATE_FORMAT_UNIXTIME);
+               $pageStats['last_modified'] = $date->format('%D %r');
+               $page = array_merge($page, $pageStats);
+
+               if (!empty($page['image'])) {
+                       $imgFormat = "<img alt=\"%s\" src=\"%s\">";
+                       $page['current_image_original'] = sprintf(
+                               $imgFormat,
+                               $page['image'],
+                               TOOLBOX_ORIGINAL . $page['image']
+                       );
+                       $page['current_image_resized'] = sprintf(
+                               $imgFormat,
+                               $page['image'],
+                               TOOLBOX_RESIZED . $page['image']
+                       );
+                       $page['current_image_midsized'] = sprintf(
+                               $imgFormat,
+                               $page['image'],
+                               TOOLBOX_MIDSIZED . $page['image']
+                       );
+                       $page['current_image_thumb'] = sprintf(
+                               $imgFormat,
+                               $page['image'],
+                               TOOLBOX_THUMB . $page['image']
+                       );
+               } else {
+                       $page['current_image_original'] = 'Image not yet uploaded';
+                       $page['current_image_resized']  = 'Image not yet uploaded';
+                       $page['current_image_midsized'] = 'Image not yet uploaded';
+                       $page['current_image_thumb']    = 'Image not yet uploaded';
+               }
+
+               $this->page = $page;
+               return $this->page;
+       }
+
+       //      }}}
+
+       //      {{{     getCurrentPage()
+
+       /**
+        * Gets the current page for the template if it exists
+        *
+        * @return mixed array of current page or false if no current page is set
+        * @access public
+        */
+       public function getCurrentPage()
+       {
+               return is_array($this->page) ? $this->page : false;
+       }
+
+       //      }}}
+       //      {{{     getHomePageHeadlines()
+
+       public function getHomePageHeadlines()
+       {
+        $wordCounter = array(
+            1 => 'one',
+            2 => 'two',
+            3 => 'three',
+            4 => 'four'
+        );
+               $headlines = array();
+               $sql = "
+                         SELECT p1.id, p1.navigation_name, p1.headline_intro, p2.image
+                               FROM pages p1 join paragraphs p2 on (p1.id = p2.page)
+                          WHERE p1.headline = true
+                                AND p1.active = true
+                                AND p2.pos = 1
+                       ORDER BY p1.parent, p1.pos";
+
+               $count = 1;
+               foreach ($this->dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) {
+                       $headlines[] = array(
+                               'count'  => $wordCounter[$count],
+                               'href'   => Toolkit_Template_Page::getSeoUrl($this, $row['id']),
+                               'img'    => ($row['image'])
+                                       ? HOMEPAGE_HEADLINE_THUMB . $row['image']
+                                       : '',
+                               'header' => $row['navigation_name'],
+                               'descr'  => $row['headline_intro'],
+                       );
+                       if (++$count > 4) {
+                               $count = 1;
+                       }
+               }
+
+               return $headlines;
+       }
+
+       //      }}}
+
+       //      {{{     setPageVars()
+
+       protected function setPageVars(PDOStatement &$stmt, $data)
+       {
+               if ($this->hasHeadlines()) {
+                       $data['headline'] = (bool)$data['headline'];
+                       $stmt->bindParam(
+                               ':headline',
+                               $data['headline'],
+                               PDO::PARAM_BOOL
+                       );
+                       $stmt->bindParam(':headline_intro', $data['headline_intro']);
+               }
+
+               if ($this->hasMemberDb()) {
+                       $data['include_member_map'] = (bool)$data['include_member_map'];
+                       $data['search_form'] = (bool)$data['search_form'];
+                       $stmt->bindParam(
+                               ':include_member_map',
+                               $data['include_member_map'],
+                               PDO::PARAM_BOOL
+                       );
+                       $stmt->bindParam(
+                               ':search_form',
+                               $data['search_form'],
+                               PDO::PARAM_BOOL
+                       );
+               }
+
+               $stmt->bindParam(':keyword', $data['keyword']);
+               $stmt->bindParam(':meta_title', $data['meta_title']);
+               $stmt->bindParam(':meta_description', $data['meta_description']);
+               $stmt->bindParam(':navigation_name', $data['navigation_name']);
+               $stmt->bindParam(':parent', $data['parent']);
+               $stmt->bindParam(':paragraph_links', $data['paragraph_links']);
+               $stmt->bindParam(':short_url', $data['short_url']);
+               $stmt->bindParam(':template', $data['template']);
+               $stmt->bindParam(':include_members', $data['include_members']);
+               $stmt->bindParam(':include_coupons', $data['include_coupons']);
+       }
+
+       //      }}}
+       //      {{{     setParagraphVars()
+
+       protected function setParagraphVars(PDOStatement &$stmt, $data)
+       {
+               if ($data['remove_image']) {
+                       $data['image'] = '';
+               }
+               $stmt->bindParam(':title', $data['title']);
+               $stmt->bindParam(':description', $data['description']);
+               $stmt->bindParam(':image', $data['image']);
+               $stmt->bindParam(':caption', $data['caption']);
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/UserArea/PageGatewayDraft.php b/Toolkit/UserArea/PageGatewayDraft.php
new file mode 100644 (file)
index 0000000..3fe3af4
--- /dev/null
@@ -0,0 +1,562 @@
+<?php
+class Toolkit_UserArea_PageGatewayDraft
+       extends Toolkit_UserArea_PageGatewayAbstract
+{
+       //      {{{     delete()
+
+       public function delete($id)
+       {
+               $pageSql = "
+            DELETE
+              FROM pages_draft
+             WHERE id = :id";
+
+               try {
+                       $stmt = $this->dbh->prepare($pageSql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+            $stmt->execute();
+            // delete from staff
+            $deleteSql = "
+            DELETE
+              FROM staff.staff
+             WHERE page = :page";
+            $delete = $this->dbh->prepare($deleteSql);
+            $delete->bindParam(':page', $id, PDO::PARAM_INT);
+            $delete->execute();
+            return true;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to delete page draft `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+    public function findNavItem($id)
+    {
+        $sql = "
+            SELECT id,navigation_name,parent,short_url
+              FROM pages
+             WHERE id = :id";
+
+               try {
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':id',
+                $id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+                       return $stmt->fetch(PDO::FETCH_ASSOC);
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception("Unable to find page `$id`");
+               }
+    }
+       //      {{{     find()
+
+       public function find($id)
+       {
+               $pageSql = "
+            SELECT p1.*, p1.id AS page_id,
+                   CASE p1.active
+                   WHEN true THEN 'active'
+                   ELSE 'In-Active'
+                   END AS active, p2.title, p2.description, p2.image, p2.caption
+              FROM pages_draft p1
+              LEFT JOIN paragraphs_draft p2
+                ON p1.id  = p2.page
+             WHERE p1.id  = :id
+               AND (p2.pos = 1 OR p2.pos IS NULL)";
+
+               try {
+                       return $this->findPage($id, $pageSql);
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to find page draft `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+       //      {{{     findAll()
+
+       public function findAll()
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM pages_draft
+                                ORDER by parent, pos";
+
+                       return $this->dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               'Error fetching all draft pages'
+                       );
+               }
+       }
+
+       //      }}}
+       //      {{{     findByKeyword()
+
+       public function findByKeyword($keyword)
+       {
+               try {
+                       $pageSql = "
+                               SELECT id
+                                 FROM pages_draft
+                                WHERE keyword = :keyword";
+
+                       $stmt = $this->dbh->prepare($pageSql);
+                       $stmt->bindParam(':keyword', $keyword);
+                       $stmt->execute();
+
+                       // Bind by column number
+                       $stmt->bindColumn(1, $id);
+
+                       $stmt->fetch(PDO::FETCH_ASSOC);
+
+                       return $this->find($id);
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to find page draft `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+       //      {{{     findTopParent()
+
+       public function findTopParent($pageId, $useDraftTable = true)
+       {
+               if (!ctype_digit((string)$pageId)) {
+                       throw new runtimeException("Invalid pageId `$pageId` to fetch");
+               }
+
+               try {
+                       if ($useDraftTable) {
+                               $sql = "
+                                       SELECT *
+                                         FROM pages_draft
+                                        WHERE id = :id";
+                       } else {
+                               $sql = "
+                                       SELECT *
+                                         FROM pages
+                                        WHERE id = :id";
+                       }
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $pageId, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+
+                       if ($row['parent'] == '0') {
+                               return $row['id'];
+                       } else {
+                               return $this->findTopParent($row['parent'], false);
+                       }
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to find parent for page `$pageId`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     insert()
+
+       public function insert(array $data)
+       {
+               if (empty($data['published_page'])) {
+                       settype($data['published_page'], 'null');
+               }
+
+               if ($this->hasHeadlines()) {
+                       $headlineColumns = 'headline, headline_intro,';
+                       $headlineParams  = ':headline, :headline_intro,';
+               }
+
+               if ($this->hasMemberDb()) {
+                       $memberColumns = 'include_member_map, search_form, ';
+                       $memberParams  = ':include_member_map, :search_form, ';
+               }
+
+               $pageSql = "
+                       INSERT INTO pages_draft (
+                               $headlineColumns $memberColumns keyword, meta_title,
+                               meta_description, navigation_name, parent, paragraph_links,
+                               short_url, template, published_page, include_members, include_coupons)
+                       VALUES (
+                               $headlineParams $memberParams :keyword, :meta_title,
+                           :meta_description, :navigation_name, :parent,
+                           :paragraph_links, :short_url, :template, :published_page, :include_members, :include_coupons)";
+
+               $paragraphSql = "
+                       INSERT INTO paragraphs_draft (
+                               active, title, description, image, caption, page)
+                       VALUES (
+                               true, :title, :description, :image, :caption, :page)";
+
+               try {
+                       $this->dbh->beginTransaction();
+
+                       $pageStmt = $this->dbh->prepare($pageSql);
+                       $this->setPageVars($pageStmt, $data);
+                       $pageStmt->bindParam(':published_page', $data['published_page']);
+                       $pageStmt->execute();
+
+                       $row = $this->dbh
+                               ->query('select id from pages_draft order by id desc limit 1')
+                               ->fetch(PDO::FETCH_ASSOC);
+
+                       if (defined('MEMBERS_DB') && MEMBERS_DB) {
+                               $this->_updateMemberCategories(
+                                       $data['member_categories'],
+                                       $row['id']
+                               );
+                       }
+
+                       if (defined('COUPONS') && COUPONS) {
+                               $this->_updateCouponCategories(
+                                       $data['coupon_categories'],
+                                       $row['id']
+                               );
+                $this->_updateMemberCities(
+                    $data['member_regions'],
+                    $row['id']
+                );
+                       }
+
+                       $paragraphStmt = $this->dbh->prepare($paragraphSql);
+                       $this->setParagraphVars($paragraphStmt, $data);
+                       $paragraphStmt->bindParam(':page', $row['id']);
+                       $paragraphStmt->execute();
+
+                       $this->dbh->commit();
+
+                       return $row['id'];
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       Toolkit_Logger::logException('DB Error', $e);
+                       $content = serialize($data);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to insert page draft [$content]"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     update()
+
+       public function update(array $data, $id)
+       {
+               if ($this->hasHeadlines()) {
+                       $headlineColumns = '
+                               headline = :headline,
+                               headline_intro = :headline_intro, ';
+               }
+
+               if ($this->hasMemberDb()) {
+                       $memberColumns = '
+                               include_member_map = :include_member_map,
+                               search_form = :search_form, ';
+               }
+
+               $pageSql = "
+            UPDATE pages_draft
+                          SET $headlineColumns
+                              $memberColumns
+                                  keyword = :keyword,
+                              meta_title = :meta_title,
+                              meta_description = :meta_description,
+                              navigation_name = :navigation_name,
+                              parent = :parent,
+                              paragraph_links = :paragraph_links,
+                              short_url = :short_url,
+                              template = :template,
+                   include_members = :include_members,
+                   include_coupons = :include_coupons
+             WHERE id = :id";
+
+               $paragraphSql = "
+                       UPDATE paragraphs_draft
+                          SET title = :title,
+                                  description = :description,
+                                  image = :image,
+                                  caption = :caption
+                        WHERE page = :page
+                          AND pos = 1";
+
+               try {
+                       $this->dbh->beginTransaction();
+
+                       $pageStmt = $this->dbh->prepare($pageSql);
+                       $this->setPageVars($pageStmt, $data);
+                       $pageStmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $pageStmt->execute();
+
+                       if (defined('MEMBERS_DB') && MEMBERS_DB) {
+                               $this->_updateMemberCategories($data['member_categories'], $id);
+                               $this->_updateMemberCities($data['member_regions'], $id);
+                       }
+                       if (defined('COUPONS') && COUPONS) {
+                               $this->_updateCouponCategories($data['coupon_categories'], $id);
+                       }
+
+                       $paragraphStmt = $this->dbh->prepare($paragraphSql);
+                       $this->setParagraphVars($paragraphStmt, $data);
+                       $paragraphStmt->bindParam(':page', $id);
+                       $paragraphStmt->execute();
+
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       Toolkit_Logger::logException('DB Error', $e);
+                       $content = serialize($data);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to update page draft [$content]"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     _updateMemberCategories()
+
+       private function _updateMemberCategories(array $data = null, $id)
+       {
+               $deleteCatsSql = "
+            DELETE FROM member_categories2toolbox_pages_draft
+             WHERE page = :id";
+               $delStmt = $this->dbh->prepare($deleteCatsSql);
+               $delStmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $delStmt->execute();
+
+               if (is_array($data)) {
+                       $insertCatsSql = "
+                               INSERT INTO member_categories2toolbox_pages_draft (page, category)
+                               VALUES (:page, :category)";
+                       $insStmt = $this->dbh->prepare($insertCatsSql);
+                       $insStmt->bindParam(':page', $id, PDO::PARAM_INT);
+                       foreach ($data as $category) {
+                               $insStmt->bindParam(':category', $category, PDO::PARAM_INT);
+                               $insStmt->execute();
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{     getMemberCategoriesForPage()
+
+       protected function getMemberCategoriesForPage($id)
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM member_categories2toolbox_pages_draft
+                 WHERE page = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id);
+                       $stmt->execute();
+
+                       $categories = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $categories[] = $row['category'];
+                       }
+
+                       return $categories;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to fetch member categories for page draft `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     _updateMemberCities()
+
+       private function _updateMemberCities(array $data = null, $id)
+       {
+               $deleteCitiesSql = "
+            DELETE FROM member_regions2toolbox_pages_draft
+             WHERE page = :id";
+               $delStmt = $this->dbh->prepare($deleteCitiesSql);
+               $delStmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $delStmt->execute();
+
+               if (is_array($data)) {
+                       $insertCitiesSql = "
+                               INSERT INTO member_regions2toolbox_pages_draft (page, region)
+                               VALUES (:page, :region)";
+                       $insStmt = $this->dbh->prepare($insertCitiesSql);
+                       $insStmt->bindParam(':page', $id, PDO::PARAM_INT);
+                       foreach ($data as $region) {
+                               $insStmt->bindParam(':region', $region, PDO::PARAM_INT);
+                               $insStmt->execute();
+                       }
+               }
+       }
+
+       //      }}}
+    // //      {{{     getMemberRegionsForPage()
+
+       protected function getMemberRegionsForPage($id)
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM member_regions2toolbox_pages_draft
+                 WHERE page = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id);
+                       $stmt->execute();
+
+                       $regions = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $regions[] = $row['region'];
+                       }
+
+                       return $regions;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to fetch member regions for page `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+       //      {{{     getMemberCitiesForPage()
+
+       protected function getMemberCitiesForPage($id)
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM member_regions2toolbox_pages_draft
+                 WHERE page = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id);
+                       $stmt->execute();
+
+                       $regions = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $regions[] = $row['region'];
+                       }
+
+                       return $regions;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to fetch member regions for page `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     _updateCouponCategories()
+
+       private function _updateCouponCategories(array $data = null, $id)
+       {
+               $deleteCatsSql = "
+            DELETE FROM coupon_categories2toolbox_pages_draft
+             WHERE page = :id";
+               $delStmt = $this->dbh->prepare($deleteCatsSql);
+               $delStmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $delStmt->execute();
+
+               if (is_array($data)) {
+                       $insertCatsSql = "
+                               INSERT INTO coupon_categories2toolbox_pages_draft (page, category)
+                               VALUES (:page, :category)";
+                       $insStmt = $this->dbh->prepare($insertCatsSql);
+                       $insStmt->bindParam(':page', $id, PDO::PARAM_INT);
+                       foreach ($data as $category) {
+                               $insStmt->bindParam(':category', $category, PDO::PARAM_INT);
+                               $insStmt->execute();
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{     getCouponCategoriesForPage()
+
+       protected function getCouponCategoriesForPage($id)
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM coupon_categories2toolbox_pages_draft
+                 WHERE page = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id);
+                       $stmt->execute();
+
+                       $categories = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $categories[] = $row['category'];
+                       }
+
+                       return $categories;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to fetch coupon categories for page draft `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     getPhotoGalleriesForPage()
+
+       protected function getPhotoGalleriesForPage($id)
+       {
+               try {
+                       $sql = "
+                SELECT pc.*
+                  FROM photo_category pc
+                  JOIN photo_category_bus pcb
+                    ON (pc.id             = pcb.photocat_id)
+                  JOIN pages_draft pd
+                    ON (pd.published_page = pcb.buscat_id)
+                 WHERE pcb.buscat_id      = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id);
+                       $stmt->execute();
+
+                       $photoGalleries = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $photoGalleries[$row['id']] = $row['category'];
+                       }
+
+                       return $photoGalleries;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to fetch member categories for page `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/PageGatewayDraftFactory.php b/Toolkit/UserArea/PageGatewayDraftFactory.php
new file mode 100644 (file)
index 0000000..68237e6
--- /dev/null
@@ -0,0 +1,10 @@
+<?php
+class Toolkit_UserArea_PageGatewayDraftFactory
+       extends Toolkit_UserArea_GatewayFactoryAbstract
+{
+       public function createGateway()
+       {
+               return new Toolkit_UserArea_PageGatewayDraft($this->dbh);
+       }
+}
+?>
diff --git a/Toolkit/UserArea/PageGatewayPublish.php b/Toolkit/UserArea/PageGatewayPublish.php
new file mode 100644 (file)
index 0000000..643f8e1
--- /dev/null
@@ -0,0 +1,758 @@
+<?php
+class Toolkit_UserArea_PageGatewayPublish
+       extends Toolkit_UserArea_PageGatewayAbstract
+{
+       //      {{{     delete()
+
+       public function delete($id)
+       {
+               $pageSql = "SELECT delete_subtree(:id)";
+
+               $createTableSql = "
+                       CREATE LOCAL TEMPORARY TABLE WorkingTable
+                       (id INTEGER NOT NULL)
+                       ON COMMIT DELETE ROWS";
+
+               try {
+
+                       $this->dbh->beginTransaction();
+
+                       $this->dbh->query($createTableSql);
+
+                       $stmt = $this->dbh->prepare($pageSql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $stmt->execute();
+
+            // delete from staff
+            $deleteSql = "
+            DELETE
+              FROM staff.staff
+             WHERE page = :page";
+            $delete = $this->dbh->prepare($deleteSql);
+            $delete->bindParam(':page', $id, PDO::PARAM_INT);
+            $delete->execute();
+            // delete from staff contacts
+            $deleteSql = "
+            DELETE
+              FROM staff.contacts
+             WHERE page = :page";
+            $delete = $this->dbh->prepare($deleteSql);
+            $delete->bindParam(':page', $id, PDO::PARAM_INT);
+            $delete->execute();
+
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to delete subtree `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     find()
+
+       public function find($id)
+       {
+               $pageSql = "
+            SELECT p1.*, p1.id AS page_id, p1.id AS published_page,
+                   CASE p1.active
+                   WHEN CAST(1 AS BOOLEAN) THEN 'active'
+                   ELSE 'In-Active'
+                   END AS active_alt, p2.title, p2.description, p2.image, p2.caption
+              FROM pages p1
+              LEFT JOIN paragraphs p2
+                ON p1.id  = p2.page
+             WHERE p1.id  = :id
+               AND (p2.pos = 1 OR p2.pos IS NULL)";
+
+               try {
+                       return $this->findPage($id, $pageSql);
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception("Unable to find page `$id`");
+               }
+       }
+
+       //      }}}
+    public function findNavItem($id)
+    {
+        $sql = "
+            SELECT id,navigation_name,parent,short_url
+              FROM pages
+             WHERE id = :id";
+
+               try {
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ':id',
+                $id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+                       return $stmt->fetch(PDO::FETCH_ASSOC);
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception("Unable to find page `$id`");
+               }
+    }
+       //      {{{     findAll()
+
+       public function findAll()
+       {
+        $authContainer = new Toolkit_UserArea_Auth_Container(
+            Toolkit_Database::getInstance()
+        );
+
+        $userAuth = new Toolkit_UserArea_Auth(
+            $authContainer,
+            '',
+            false
+        );
+        $userAuth->setIdle();
+        $userAuth->start();
+        if ($userAuth->checkAuth()) {
+            $page = $userAuth->getUserPageId($this->dbh);
+            $categories = Toolkit_Common::getHierarchicalTreeStructure(
+                $this->dbh,
+                'pages',
+                'id',
+                'parent',
+                'pos',
+                $page
+            );
+            $categories[$page] = 1;
+        } else {
+            return array();
+        }
+               try {
+            $sql = "
+                SELECT *
+                  FROM pages
+                 WHERE id IN (".implode(',', array_keys($categories)).")
+                 ORDER by parent, pos";
+                       return $this->dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               'Error fetching all published pages'
+                       );
+               }
+       }
+
+       //      }}}
+       //      {{{     findByKeyword()
+
+       public function findByKeyword($keyword)
+       {
+               try {
+                       $pageSql = "
+                               SELECT id
+                                 FROM pages
+                                WHERE keyword = :keyword";
+
+                       $stmt = $this->dbh->prepare($pageSql);
+                       $stmt->bindParam(':keyword', $keyword);
+                       $stmt->execute();
+
+                       // Bind by column number
+                       $stmt->bindColumn(1, $id);
+
+                       $stmt->fetch(PDO::FETCH_ASSOC);
+
+                       return $this->findNavItem($id);
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to find keyword `$keyword`"
+                       );
+               }
+       }
+
+       //      }}}
+       //      {{{     findTopParent()
+
+       public function findTopParent($pageId)
+       {
+               if (!filter_var($pageId, FILTER_VALIDATE_INT)) {
+                       throw new runtimeException("Invalid pageId `$pageId` to fetch");
+               }
+
+               try {
+                       $sql = "
+                               SELECT parent,id
+                                 FROM pages
+                                WHERE id  = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $pageId, PDO::PARAM_INT);
+                       $stmt->execute();
+
+                       $row = $stmt->fetch(PDO::FETCH_ASSOC);
+            if (!$stmt->rowCount()) {
+                return false;
+            }
+
+                       if ($row['parent'] == '0') {
+                               return $row['id'];
+                       } else {
+                               return $this->findTopParent($row['parent']);
+                       }
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to find parent for page `$pageId`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     insert()
+
+       public function insert(array $data)
+       {
+               if ($this->hasHeadlines()) {
+                       $headlineColumns = 'headline, headline_intro,';
+                       $headlineParams  = ':headline, :headline_intro,';
+               }
+
+               if ($this->hasMemberDb()) {
+                       $memberColumns = 'include_member_map, search_form, ';
+                       $memberParams  = ':include_member_map, :search_form, ';
+               }
+
+               $pageSql = "
+                       INSERT INTO pages (
+                               $headlineColumns $memberColumns keyword, meta_title,
+                               meta_description, navigation_name, parent, paragraph_links,
+                               short_url, template, include_members, include_coupons)
+                       VALUES (
+                               $headlineParams $memberParams :keyword, :meta_title,
+                           :meta_description, :navigation_name, :parent,
+                :paragraph_links, :short_url, :template, :include_members, :include_coupons)
+        RETURNING id";
+
+               $paragraphSql = "
+                       INSERT INTO paragraphs (
+                               active, title, description, image, caption, page)
+                       VALUES (
+                               true, :title, :description, :image, :caption, :page)";
+
+               try {
+                       $this->dbh->beginTransaction();
+
+                       $pageStmt = $this->dbh->prepare($pageSql);
+                       $this->setPageVars($pageStmt, $data);
+                       $pageStmt->execute();
+
+            $pageId = $pageStmt->fetchColumn();
+
+                       if (defined('MEMBERS_DB') && MEMBERS_DB) {
+                               $this->_updateMemberCategories(
+                                       $data['member_categories'],
+                    $pageId
+                               );
+                $this->_updateMemberRegions(
+                    $data['member_regions'],
+                    $pageId
+                );
+                       }
+
+                       if (defined('COUPONS') && COUPONS) {
+                               $this->_updateCouponCategories(
+                                       $data['coupon_categories'],
+                    $pageId
+                               );
+                       }
+            $this->_updateStaff($data, $pageId);
+
+                       $paragraphStmt = $this->dbh->prepare($paragraphSql);
+                       $this->setParagraphVars($paragraphStmt, $data);
+            $paragraphStmt->bindParam(':page', $pageId);
+                       $paragraphStmt->execute();
+
+            // for some reason when Jodie is adding new pages the page position
+            // get messed up maybe more than one person it adding or updating
+            // pages I don't know either way when adding in new pages
+            // we'll have to go through all pages that have the same
+            // parent and redo the page positions so they don't get off order
+            $sql = "
+              SELECT id,pos
+                FROM pages
+               WHERE parent = :parent
+            ORDER BY pos";
+            $stmt = $this->dbh->prepare($sql);
+            $sql = "
+            UPDATE pages
+               SET pos = :pos
+             WHERE id = :id";
+            $updatePositionOfPage = $this->dbh->prepare($sql);
+            $stmt->bindParam(':parent', $data['parent'], PDO::PARAM_INT);
+            $stmt->execute();
+            $pos = 1;
+            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                $updatePositionOfPage->bindParam(
+                    ':id',
+                    $row['id'],
+                    PDO::PARAM_INT
+                );
+                $updatePositionOfPage->bindParam(
+                    ':pos',
+                    $pos,
+                    PDO::PARAM_INT
+                );
+                $updatePositionOfPage->execute();
+                ++$pos;
+            }
+
+                       $this->dbh->commit();
+
+                       return $pageId;
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       Toolkit_Logger::logException('DB Error', $e);
+                       $content = serialize($data);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to insert page [$content]"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     update()
+
+       public function update(array $data, $id)
+       {
+        $deleteContacts = array();
+        foreach ($data as $key => $value) {
+            if (preg_match('%deleteStaff-([0-9]*)%', $key, $matches)) {
+                $deleteContacts[] = $matches[1];
+            }
+        }
+               if ($this->hasHeadlines()) {
+                       $headlineColumns = '
+                               headline = :headline,
+                               headline_intro = :headline_intro, ';
+               }
+
+               if ($this->hasMemberDb()) {
+                       $memberColumns = '
+                               include_member_map = :include_member_map,
+                               search_form = :search_form, ';
+        }
+
+               try {
+            $this->dbh->beginTransaction();
+            // need to know if we're moving this to another parent
+            $sql = "
+                SELECT parent, pos
+                  FROM pages
+                 WHERE id = :id";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(
+                ":id",
+                $id,
+                PDO::PARAM_INT
+            );
+            $stmt->execute();
+
+            // the old parent of the page
+            $oldData   = $stmt->fetch(PDO::FETCH_ASSOC);
+            $oldParent = $oldData['parent'];
+            $oldPos    = $oldData['pos'];
+            if ($data['parent'] != $oldParent) {
+                // adjust the old level to normal
+                $sql = "
+                UPDATE pages
+                   SET pos = pos - 1
+                 WHERE pos > :pos
+                  AND parent = :parent
+                    ";
+                $preStmt = $this->dbh->prepare($sql);
+                $preStmt->bindParam(
+                    ":parent",
+                    $oldParent,
+                    PDO::PARAM_INT
+                );
+                $preStmt->bindParam(
+                    ":pos",
+                    $oldPos,
+                    PDO::PARAM_INT
+                );
+                $preStmt->execute();
+                // if it is then get next position number for new parent
+                $sql = "
+                    SELECT max(pos) + 1
+                      FROM pages
+                     WHERE parent = :parent";
+                $stmt = $this->dbh->prepare($sql);
+                $stmt->bindParam(
+                    ":parent",
+                    $data['parent'],
+                    PDO::PARAM_INT
+                );
+                $stmt->execute();
+                $pos = $stmt->fetchColumn();
+            }
+
+            $pageSql = "
+                UPDATE pages
+                   SET $headlineColumns
+                       $memberColumns
+                       keyword = :keyword,
+                       meta_title = :meta_title,
+                       meta_description = :meta_description,
+                       navigation_name = :navigation_name,
+                       parent = :parent,
+                       paragraph_links = :paragraph_links,
+                       short_url = :short_url,
+                       template = :template ,
+                       include_members = :include_members,
+                       include_coupons = :include_coupons";
+            if ($pos) {
+                $pageSql .= ", pos = $pos ";
+            }
+
+            $pageSql .= "
+                 WHERE id = :id";
+
+            $paragraphSql = "
+                UPDATE paragraphs
+                   SET title = :title,
+                       description = :description,
+                       image = :image,
+                       caption = :caption
+                 WHERE page = :page
+                   AND pos = 1";
+
+                       $pageStmt = $this->dbh->prepare($pageSql);
+                       $this->setPageVars($pageStmt, $data);
+                       $pageStmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $pageStmt->execute();
+
+                       if (defined('MEMBERS_DB') && MEMBERS_DB) {
+                               $this->_updateMemberCategories($data['member_categories'], $id);
+                               $this->_updateMemberRegions($data['member_regions'], $id);
+                       }
+                       if (defined('COUPONS') && COUPONS) {
+                               $this->_updateCouponCategories($data['coupon_categories'], $id);
+                       }
+            $this->_updateStaff($data, $id, $deleteContacts);
+
+                       $paragraphStmt = $this->dbh->prepare($paragraphSql);
+                       $this->setParagraphVars($paragraphStmt, $data);
+                       $paragraphStmt->bindParam(':page', $id);
+                       $paragraphStmt->execute();
+
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       Toolkit_Logger::logException('DB Error', $e);
+                       $content = serialize($data);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to update page [$content]"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     _updateMemberCategories()
+
+       private function _updateMemberCategories(array $data = null, $id)
+       {
+               $deleteCatsSql = "
+            DELETE FROM member_categories2toolbox_pages
+             WHERE page = :id";
+               $delStmt = $this->dbh->prepare($deleteCatsSql);
+               $delStmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $delStmt->execute();
+
+               if (is_array($data)) {
+                       $insertCatsSql = "
+                               INSERT INTO member_categories2toolbox_pages (page, category)
+                               VALUES (:page, :category)";
+                       $insStmt = $this->dbh->prepare($insertCatsSql);
+                       $insStmt->bindParam(':page', $id, PDO::PARAM_INT);
+                       foreach ($data as $category) {
+                               $insStmt->bindParam(':category', $category, PDO::PARAM_INT);
+                               $insStmt->execute();
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{     getMemberCategoriesForPage()
+
+       protected function getMemberCategoriesForPage($id)
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM member_categories2toolbox_pages
+                 WHERE page = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id);
+                       $stmt->execute();
+
+                       $categories = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $categories[] = $row['category'];
+                       }
+
+                       return $categories;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to fetch member categories for page `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     _updateMemberRegions()
+
+       private function _updateMemberRegions(array $data = null, $id)
+       {
+               $deleteRegionsSql = "
+            DELETE FROM member_regions2toolbox_pages
+             WHERE page = :id";
+               $delStmt = $this->dbh->prepare($deleteRegionsSql);
+               $delStmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $delStmt->execute();
+
+               if (is_array($data)) {
+                       $insertRegionsSql = "
+                               INSERT INTO member_regions2toolbox_pages (page, region)
+                               VALUES (:page, :region)";
+                       $insStmt = $this->dbh->prepare($insertRegionsSql);
+                       $insStmt->bindParam(':page', $id, PDO::PARAM_INT);
+                       foreach ($data as $region) {
+                               $insStmt->bindParam(':region', $region, PDO::PARAM_INT);
+                               $insStmt->execute();
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{     getMemberRegionsForPage()
+
+       protected function getMemberRegionsForPage($id)
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM member_regions2toolbox_pages
+                 WHERE page = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id);
+                       $stmt->execute();
+
+                       $regions = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $regions[] = $row['region'];
+                       }
+
+                       return $regions;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to fetch member regions for page `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     _updateCouponCategories()
+
+       private function _updateCouponCategories(array $data = null, $id)
+       {
+               $deleteCatsSql = "
+            DELETE FROM coupon_categories2toolbox_pages
+             WHERE page = :id";
+               $delStmt = $this->dbh->prepare($deleteCatsSql);
+               $delStmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $delStmt->execute();
+
+               if (is_array($data)) {
+                       $insertCatsSql = "
+                               INSERT INTO coupon_categories2toolbox_pages (page, category)
+                               VALUES (:page, :category)";
+                       $insStmt = $this->dbh->prepare($insertCatsSql);
+                       $insStmt->bindParam(':page', $id, PDO::PARAM_INT);
+                       foreach ($data as $category) {
+                               $insStmt->bindParam(':category', $category, PDO::PARAM_INT);
+                               $insStmt->execute();
+                       }
+               }
+       }
+
+       //      }}}
+       //      {{{     getCouponCategoriesForPage()
+
+       protected function getCouponCategoriesForPage($id)
+       {
+               try {
+                       $sql = "
+                SELECT *
+                  FROM coupon_categories2toolbox_pages
+                 WHERE page = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id);
+                       $stmt->execute();
+
+                       $categories = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $categories[] = $row['category'];
+                       }
+
+                       return $categories;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to fetch coupon categories for page `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     getPhotoGalleriesForPage()
+
+       protected function getPhotoGalleriesForPage($id)
+       {
+               try {
+                       $sql = "
+                SELECT pc.*
+                  FROM photo_category pc
+                  JOIN photo_category_bus pcb
+                    ON (pc.id        = pcb.photocat_id)
+                 WHERE pcb.buscat_id = :id";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':id', $id);
+                       $stmt->execute();
+
+                       $photoGalleries = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $photoGalleries[$row['id']] = $row['category'];
+                       }
+
+                       return $photoGalleries;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to fetch member categories for page `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+
+    protected function _updateStaff(
+        $data  = null,
+        $pageId = null,
+        $deletedContacts = null
+    ) {
+        // does this page have a staff already
+        $staffModel = new Toolkit_Staff_Models_Staff();
+        if ($pageId) {
+            $sql = "
+            SELECT id
+              FROM staff.staff
+             WHERE page = :page";
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':page', $pageId, PDO::FETCH_ASSOC);
+            $stmt->execute();
+            $staffId = $stmt->fetchColumn();
+        }
+        $staffData = $data['staff'];
+        $staff     = $staffModel->createByValues(
+            array(
+                'id'              => (($staffId) ? $staffId : null),
+                'page'            => $pageId,
+                'department'      => $staffData['department'],
+                'name'            => $staffData['name'],
+                'email'           => $staffData['email'],
+                'phone'           => $staffData['phone'],
+                'office_address'  => $staffData['office_address'],
+                'office_address2' => $staffData['office_address2'],
+                'office_city'     => $staffData['office_city'],
+                'office_state'    => $staffData['office_state'],
+                'office_zip'      => $staffData['office_zip'],
+                'office_email'    => $staffData['office_email'],
+                'office_phone'    => $staffData['office_phone'],
+                'office_fax'      => $staffData['office_fax'],
+                'office_hours'    => $staffData['office_hours']
+            )
+        );
+        $staff->save($this->dbh);
+
+        $contacts     = $data['staff_contacts'];
+        $newContacts  = $data['staff_contacts']['new'];
+        $pos = 1;
+        if (!empty($contacts)) {
+            unset($contacts['new']);
+            foreach ($contacts as $contactId => $contactData) {
+                if (filter_var($contactId, FILTER_VALIDATE_INT)) {
+                    $contactModel = new Toolkit_Staff_Models_Contact();
+                    $contact      = $contactModel->createByValues(
+                        $contactData
+                    );
+                    $contact->setId($contactId);
+                    $contact->setPage($pageId);
+                    $contact->setPos($pos);
+                    $contact->save($this->dbh);
+                    ++$pos;
+                }
+            }
+        }
+        if (!empty($newContacts)) {
+            foreach ($newContacts as $contactData) {
+                if (   !$contactData['title']
+                    && !$contactData['name']
+                    && !$contactData['email']
+                    && !$contactData['phone']
+                ) {
+                    continue;
+                }
+                $contactModel = new Toolkit_Staff_Models_Contact();
+                $contact      = $contactModel->createByValues(
+                    array(
+                        'page'  => $pageId,
+                        'title' => $contactData['title'],
+                        'name'  => $contactData['name'],
+                        'email' => $contactData['email'],
+                        'phone' => $contactData['phone'],
+                        'pos'   => $pos
+                    )
+                );
+                $contact->save($this->dbh);
+                ++$pos;
+            }
+        }
+        if (   is_array($deletedContacts)
+            && !empty($deletedContacts)
+        ) {
+            foreach ($deletedContacts as $deleteId) {
+                if (filter_var($deleteId, FILTER_VALIDATE_INT)) {
+                    $contactModel = new Toolkit_Staff_Models_Contact();
+                    $contact      = $contactModel->fetchById(
+                        $this->dbh,
+                        $deleteId
+                    );
+                    $contact->delete($this->dbh);
+                }
+            }
+        }
+    }
+}
diff --git a/Toolkit/UserArea/PageGatewayPublishFactory.php b/Toolkit/UserArea/PageGatewayPublishFactory.php
new file mode 100644 (file)
index 0000000..118218d
--- /dev/null
@@ -0,0 +1,9 @@
+<?php
+class Toolkit_UserArea_PageGatewayPublishFactory
+       extends Toolkit_UserArea_GatewayFactoryAbstract
+{
+       public function createGateway()
+       {
+               return new Toolkit_UserArea_PageGatewayPublish($this->dbh);
+       }
+}
diff --git a/Toolkit/UserArea/PagesTree.php b/Toolkit/UserArea/PagesTree.php
new file mode 100644 (file)
index 0000000..9244f10
--- /dev/null
@@ -0,0 +1,292 @@
+<?php
+class Toolkit_UserArea_PagesTree extends Toolkit_UserArea_TreeAbstract
+{
+       //      {{{     properties
+
+       protected $rootNodeStart = "<ul id=\"toolbox\">\n";
+       protected $leafStart = "\n\t<li id=\"cat_%s\" %s>\n";
+
+       protected $toolbox;
+
+       //      }}}
+       //      {{{     getActiveBall()
+
+       protected function getActiveBall(array $branch)
+       {
+               $key = array_key_exists('published_page', $branch)
+                       ? 'published_page'
+                       : 'id';
+               $homePage = ($branch[$key] == HOME_ID);
+               $memberDbHomePage = (defined('MEMBERS_DB')
+                                                        && MEMBERS_DB
+                                                        && $branch[$key] == MEMBERS_ONLY_HOME_PAGE);
+
+               if ($homePage || $memberDbHomePage) {
+                       return '<a class="tOff"><img src="'.MEDIA_BASE_URL . 'Toolkit/UserArea/assets/grnball.gif" alt="Active Ball"></a>';
+               }
+
+               $activeFormat  = '<a class="active-ball" rel="%s" href="%s" title="%s">';
+               $activeFormat .=        $this->getActiveBallImage($branch);
+               $activeFormat .= '</a>';
+
+               return sprintf(
+                       $activeFormat,
+                       $branch['id'],
+               MEDIA_BASE_URL . "userArea/toolbox.php?id={$branch['id']}",
+                       $branch['active_alt']
+               );
+       }
+
+    // }}}
+       //      {{{     getActiveMobileBall()
+
+       protected function getActiveMobileBall(array $branch)
+       {
+               $key = array_key_exists('published_page', $branch)
+                       ? 'published_page'
+                       : 'id';
+        $nonMobilePages
+            = (defined('NON_MOBILE_PAGES'))
+            ? unserialize(NON_MOBILE_PAGES)
+            : array();
+        $nonMobilePages[] = HOME_ID;
+        if (defined('MEMBERS_DB') && MEMBERS_DB) {
+            $nonMobilePages[] = MEMBERS_ONLY_HOME_PAGE;
+            $nonMobilePages[] = MEMBERS_CATEGORY;
+        }
+
+               if (in_array($branch[$key], $nonMobilePages)) {
+                       return '<a class="tOff"><img src="'.MEDIA_BASE_URL . 'Toolkit/UserArea/assets/grnball.gif" alt="Active Ball"></a>';
+               }
+
+               $activeFormat  = '<a class="mobile-active-ball" rel="%s" href="%s" title="%s">';
+               $activeFormat .=        $this->getActiveMobileBallImage($branch);
+               $activeFormat .= '</a>';
+
+               return sprintf(
+                       $activeFormat,
+                       $branch['id'],
+               MEDIA_BASE_URL . "userArea/toolbox.php?id={$branch['id']}",
+                       $branch['active_alt']
+               );
+       }
+
+    // }}}
+       //      {{{     _getMoveArrows()
+
+       private function _getMoveArrows($branch)
+       {
+               $homePage = ($branch['id'] == HOME_ID);
+               $memberDbHomePage = (defined('MEMBERS_DB')
+                                                        && MEMBERS_DB
+                                                        && $branch['id'] == MEMBERS_ONLY_HOME_PAGE);
+
+               if ($homePage || $memberDbHomePage) {
+                       $format = '<img src="%s" class="tOff" alt="%s">';
+
+                       $up = sprintf(
+                               $format,
+                               MEDIA_APP_BASE_URL . "assets/icons/arrow_up.png",
+                               'Move Up Arrow'
+                       );
+
+                       $down = sprintf(
+                               $format,
+                               MEDIA_APP_BASE_URL . "assets/icons/arrow_down.png",
+                               'Move Down Arrow'
+                       );
+               } else {
+                       $format = '<img src="%s" alt="Move %s Arrow" class="move%s">';
+
+                       $up = sprintf(
+                               $format,
+                               MEDIA_APP_BASE_URL . "assets/icons/arrow_up.png",
+                               'Up',
+                               'Up'
+                       );
+
+                       $down = sprintf(
+                               $format,
+                               MEDIA_APP_BASE_URL . "assets/icons/arrow_down.png",
+                               'Down',
+                               'Down'
+                       );
+               }
+
+
+               return $up . $down;
+       }
+
+       //      }}}
+
+    private function _getPositionSelect($branch)/*{{{*/
+    {
+               $homePage = ($branch['id'] == HOME_ID);
+               $memberDbHomePage = (defined('MEMBERS_DB')
+                                                        && MEMBERS_DB
+                                                        && $branch['id'] == MEMBERS_ONLY_HOME_PAGE);
+        $authUser   = Registry::get('Toolkit_UserArea_Auth');
+        $mainPageId = $authUser->getAuthData('page');
+        $isMainPage = ($mainPageId == $branch['id']);
+               if ($homePage || $memberDbHomePage || $isMainPage) {
+            return '';
+        } else {
+            $addClass
+                = ($branch['parent'] == 0 || $branch['parent'] == MEMBERS_CATEGORY)
+                ? 'pos-select parent-level-sel'
+                : 'pos-select';
+            $showOn
+                = ($_GET['showpos'])
+                ? 'display:'
+                : 'display:none;';
+            return '<select style="'.$showOn.'" class="'.$addClass.'" name="pos'.$branch['id'].'" rel="'.$branch['pos'].'"></select>';
+        }
+    }/*}}}*/
+
+       //      {{{     createTree()
+
+       protected function createTree(array $tree, $leaf, $level = 0)
+       {
+               $html = !$level ? $this->rootNodeStart : $this->subTreeStart;
+
+               if ($level == 0) {
+                       $lockMainNavPages = $this->config
+                               ->getItem('section', 'conf')
+                               ->getItem('directive', 'lockMainNavPages')
+                               ->getContent();
+               } else {
+                       $lockMainNavPages = false;
+               }
+
+               if (is_array($leaf) && !empty($leaf)) {
+                       while (list($parent, $branch) = each($leaf)) {
+                               if ($branch['id'] == HOME_ID) {
+                                       $html .= sprintf($this->leafStart, $branch['id'], 'rel="root"');
+                               } else {
+                                       $html .= sprintf($this->leafStart, $branch['id'], null);
+                               }
+                if (   defined('MEMBERS_CATEGORY')
+                    && MEMBERS_CATEGORY
+                    && $branch['parent'] == MEMBERS_CATEGORY
+                ) {
+                    $memberOnlyBase =MEDIA_BASE_URL . "members-only-area/";
+                    switch ($branch['id']) {
+                    case MEMBERS_PROFILE_FORM_PAGE :
+                        $previewUrl = $memberOnlyBase
+                            . "?rt=EditProfile&tab=info";
+                        break;
+                    case MEMBERS_COUPONS_PAGE :
+                        $previewUrl = $memberOnlyBase
+                            . "?rt=Coupons&page_id={$branch['id']}";
+                        break;
+                    case MEMBERS_EVENTS_PAGE :
+                        $previewUrl = $memberOnlyBase
+                            . "?rt=Events&page_id={$branch['id']}";
+                        break;
+                    case MEMBERS_LEADS_PAGE :
+                        $previewUrl = $memberOnlyBase
+                            . "?rt=Leads&page_id={$branch['id']}";
+                        break;
+                    case MEMBERS_REPORTS_PAGE :
+                        $previewUrl = $memberOnlyBase
+                            . "?rt=Reports&page_id={$branch['id']}";
+                        break;
+                    case MEMBERS_ADD_JOB_PAGE :
+                        $previewUrl = $memberOnlyBase
+                            . "?rt=Jobs&ac=addJob&page_id={$branch['id']}";
+                        break;
+                    case MEMBERS_SHOW_JOBS_PAGE :
+                        $previewUrl = $memberOnlyBase
+                            . "?rt=Jobs&page_id={$branch['id']}";
+                        break;
+                    default:
+                        $previewUrl = $memberOnlyBase
+                            . "?page_id={$branch['id']}";
+                        break;
+                    }
+
+                } else {
+                    $previewUrl = BASE_URL . "index.php?catid={$branch['id']}&preview=1";
+                }
+
+                               $html .= '<div class="right-element">';
+
+                               $html .= '<a href="'.MEDIA_BASE_URL.'userArea/toolbox.php?rt=EditPage&amp;id='.$branch['id'].'" class="editPage" title="Edit Page">Top
+Section </a> ';
+                               $html .= '<a href="'.MEDIA_BASE_URL.'userArea/toolbox.php?rt=Paragraphs&amp;pageid='.$branch['id'].'" class="editParagraphs" title="Page
+Paragraphs">Paragraphs</a> ';
+                               $html .= '<a href="'.$previewUrl.'" class="pagePreview" title="Preview Page">[Preview]</a> ';
+                               if (!$lockMainNavPages) {
+                                       $html .= $this->getActiveBall($branch);
+                    if (defined("MOBILE_SITE") && MOBILE_SITE) {
+                                           $html .= $this->getActiveMobileBall($branch);
+                    }
+                                       $html .= $this->_getPositionSelect($branch);
+                               }
+
+                               $html .= '</div>';
+                               $html .= "<strong>{$branch['navigation_name']}</strong>";
+
+                               if ($tree[$parent]) {
+                                       $html .= $this->createTree($tree, $tree[$parent], $level + 1);
+                               } else {
+                                       $html .= $this->leafEnd;
+                               }
+                       }
+               }
+
+               $html .= $this->treeEnd;
+               if ($level) {
+                       $html .= $this->leafEnd;
+               }
+               return $html;
+       }
+
+       //      }}}
+
+       //      {{{     fetchContent()
+
+       protected function fetchContent(Toolkit_UserArea_GatewayAbstract $gateway)
+       {
+               $pages = $gateway->findAll();
+               if (is_array($pages)) {
+                       $threads = array();
+                       foreach ($pages as $page) {
+                               if (!empty($page['keyword'])) {
+                                       $page['navigation_name'] .= ' {' . $page['keyword'] . '}';
+                               }
+                               $page['active_alt'] = $page['active'] ? 'On' : 'Off';
+                               $page['children'] = array();
+                               $threads[] = $page;
+                       }
+
+                       $children = array();
+                       while (list($key, $value) = each ($threads)) {
+                               $children[$value['parent']][$value['id']] = $value;
+                       }
+
+                       $this->tree = $children;
+               } else {
+                       $this->tree = array();
+               }
+       }
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+       public function toHtml(Toolkit_UserArea_GatewayAbstract $gateway)
+       {
+               $GLOBALS['bottomScripts'][] = MEDIA_BASE_URL . 'Toolkit/UserArea/libjs/pagesTree.js';
+               $GLOBALS['bottomScripts'][] = MEDIA_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/jquery.tree.js';
+               $GLOBALS['bottomScripts'][] = MEDIA_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/lib/jquery.cookie.js';
+               $GLOBALS['bottomScripts'][] = MEDIA_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/plugins/jquery.tree.cookie.js';
+
+               $this->fetchContent($gateway);
+               $html = parent::toHtml();
+
+               return "<div id=\"tree\">$html</div>";
+       }
+
+       //      }}}
+}
diff --git a/Toolkit/UserArea/ParagraphBreadCrumbs.php b/Toolkit/UserArea/ParagraphBreadCrumbs.php
new file mode 100644 (file)
index 0000000..e3d1609
--- /dev/null
@@ -0,0 +1,51 @@
+<?php
+
+class Toolkit_UserArea_ParagraphBreadCrumbs
+       extends Toolkit_UserArea_BreadCrumbsAbstract
+{
+       //      {{{     getPageUri()
+
+       protected function getPageUri(array $page)
+       {
+               //      go to parent edit page form
+           $uri = MEDIA_BASE_URL . "userArea/toolbox.php?rt=EditPage&amp;id={$page['id']}";
+           return "<a href=\"{$uri}\">{$page['navigation_name']}</a>";
+       }
+
+       //      }}}
+       //      {{{     getPath()
+
+       /**
+        * @return the $path
+        */
+       public function getPath()
+       {
+           $id = $this->id;
+        $authData = $this->getAuthData();
+           $stack = array();
+           do {
+               $page = $this->getPage($id);
+
+               $stack[] = $this->getPageUri($page);
+            if (AUTH_USER_PAGE_ID && $id == AUTH_USER_PAGE_ID) {
+                $id = 0;
+            } else {
+                $id = $page['parent'];
+            }
+           } while ($id != 0);
+
+           $reverse = array_reverse($stack);
+
+               if (filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+                       $uri = MEDIA_BASE_URL . "userArea/toolbox.php?rt=Paragraphs&amp;pageid={$this->id}";
+                       $reverse[] = "<a href=\"{$uri}\">Paragraphs</a>";
+               }
+
+        $this->path = implode(' > ', $reverse);
+
+               return $this->path;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/ParagraphDraftBreadCrumbs.php b/Toolkit/UserArea/ParagraphDraftBreadCrumbs.php
new file mode 100644 (file)
index 0000000..fc7092b
--- /dev/null
@@ -0,0 +1,80 @@
+<?php
+
+class Toolkit_UserArea_ParagraphDraftBreadCrumbs
+       extends Toolkit_UserArea_BreadCrumbsAbstract
+{
+       //      {{{     getPageUri()
+
+       protected function getPageUri(array $page)
+       {
+               //      go to parent paragraphs
+           $uri = MEDIA_BASE_URL . "userArea/toolbox.php?rt=Paragraphs&pageid={$page['id']}";
+               //      go to parent edit page form
+           $uri = MEDIA_BASE_URL . "userArea/toolbox.php?rt=EditPage&id={$page['id']}";
+           return "<a href=\"{$uri}\">{$page['navigation_name']}</a>";
+       }
+
+       //      }}}
+       //      {{{     getDraft()
+
+    protected function getDraft($id)
+    {
+        try {
+            $sql = "
+                SELECT *
+                  FROM pages_draft
+                 WHERE id = :id";
+
+            $stmt = $this->dbh->prepare($sql);
+            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+            $stmt->execute();
+
+            return $stmt->fetch(PDO::FETCH_ASSOC);
+        } catch (PDOException $e) {
+            Toolkit_Logger::logException('DB Error', $e);
+            throw new Toolkit_UserArea_Exception(
+                "Could not fetch parent for page `$id`"
+            );
+        }
+    }
+
+       //      }}}
+       //      {{{     getPath()
+
+       /**
+        * @return the $path
+        */
+       public function getPath()
+       {
+               $draft = $this->getDraft($this->id);
+
+               if (filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
+                       $uri = MEDIA_BASE_URL . "userArea/toolbox.php?rt=ParagraphsDraft&amp;pageid={$this->id}";
+                       $stack = array("<a href=\"{$uri}\">Paragraphs</a>");
+               }
+
+               if (is_array($stack)) {
+                       $stack[] = $this->getPageUri($draft);
+               } else {
+                       $stack = array($draft['navigation_name']);
+               }
+
+               $publishedPage = $this->getPage($draft['published_page']);
+               $id = $publishedPage['parent'];
+           while ($id != 0) {
+               $page = $this->getPage($id);
+
+               $stack[] = $this->getPageUri($page);
+               $id = $page['parent'];
+           }
+
+           $reverse = array_reverse($stack);
+
+        $this->path = implode(' > ', $reverse);
+
+               return $this->path;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/ParagraphGatewayAbstract.php b/Toolkit/UserArea/ParagraphGatewayAbstract.php
new file mode 100644 (file)
index 0000000..c0b5d18
--- /dev/null
@@ -0,0 +1,49 @@
+<?
+abstract class Toolkit_UserArea_ParagraphGatewayAbstract
+       extends Toolkit_UserArea_GatewayAbstract
+{
+       //      {{{     findAll()
+
+       abstract public function findAll($page);
+
+       //      }}}
+
+       //      {{{     setParagraphVars()
+
+       protected function setParagraphVars(PDOStatement &$stmt, $data)
+       {
+               $data['active'] = (bool) $data['active'];
+               $data['back_to_top'] = (bool) $data['back_to_top'];
+               if ($data['remove_image']) {
+                       $data['image'] = '';
+               }
+
+               $stmt->bindParam(':active', $data['active'], PDO::PARAM_BOOL);
+               $stmt->bindParam(':title', $data['title']);
+               $stmt->bindParam(':description', $data['description']);
+               $stmt->bindParam(':image', $data['image']);
+               $stmt->bindParam(':caption', $data['caption']);
+               $stmt->bindParam(':page', $data['page']);
+               $stmt->bindParam(':back_to_top', $data['back_to_top'], PDO::PARAM_BOOL);
+       }
+
+       //      }}}
+       //      {{{     setFileVars()
+
+       protected function setFileVars(PDOStatement &$stmt, $data, $key)
+       {
+               $stmt->bindParam(':filename', $data['filename'][$key]);
+               $stmt->bindParam(':bytes', $data['bytes'][$key]);
+               $stmt->bindParam(':urltext', $data['urltext'][$key]);
+               if ($data['type'][$key] != DIRECTORY_SEPARATOR) {
+                       $stmt->bindParam(':type', $data['type'][$key]);
+               } else {
+                       $pieces = explode('.', $data['filename'][$key]);
+                       $extension = end($pieces);
+                       $stmt->bindParam(':type', $extension);
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/ParagraphGatewayDraft.php b/Toolkit/UserArea/ParagraphGatewayDraft.php
new file mode 100644 (file)
index 0000000..baa08c5
--- /dev/null
@@ -0,0 +1,225 @@
+<?php
+class Toolkit_UserArea_ParagraphGatewayDraft
+       extends Toolkit_UserArea_ParagraphGatewayAbstract
+{
+       //      {{{     delete()
+
+       public function delete($id)
+       {
+               $pageSql = "
+            DELETE
+              FROM paragraphs_draft
+             WHERE id = :id";
+
+               try {
+                       $stmt = $this->dbh->prepare($pageSql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to delete paragraph draft `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     find()
+
+       public function find($id)
+       {
+               $paragraphSql = "
+            SELECT *
+              FROM paragraphs_draft
+             WHERE id  = :id ";
+
+               $fileSql = "
+                       SELECT *
+                         FROM files_draft
+                        WHERE paragraph = :paragraph
+                        ORDER BY pos";
+
+               try {
+                       $paragraphStmt = $this->dbh->prepare($paragraphSql);
+                       $paragraphStmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $paragraphStmt->execute();
+
+                       $paragraph = $paragraphStmt->fetch(PDO::FETCH_ASSOC);
+
+                       if (!empty($paragraph['image'])) {
+                               $imgFormat = "<img src=\"%s{$paragraph['image']}\">";
+                               $paragraph['current_image_original']
+                                       = sprintf($imgFormat, TOOLBOX_ORIGINAL);
+                               $paragraph['current_image_resized']
+                                       = sprintf($imgFormat, TOOLBOX_RESIZED);
+                               $paragraph['current_image_midsized']
+                                       = sprintf($imgFormat, TOOLBOX_MIDSIZED);
+                               $paragraph['current_image_thumb']
+                                       = sprintf($imgFormat, TOOLBOX_THUMB);
+                       } else {
+                               $paragraph['current_image_original'] = 'Image not yet uploaded';
+                               $paragraph['current_image_resized']  = 'Image not yet uploaded';
+                               $paragraph['current_image_midsized'] = 'Image not yet uploaded';
+                               $paragraph['current_image_thumb']    = 'Image not yet uploaded';
+                       }
+
+                       $fileStmt = $this->dbh->prepare($fileSql);
+                       $fileStmt->bindParam(':paragraph', $id, PDO::PARAM_INT);
+                       $fileStmt->execute();
+
+                       $paragraph['files'] = $fileStmt->fetchAll(PDO::FETCH_ASSOC);
+
+                       return $paragraph;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to find paragraph draft `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+       //      {{{     findAll()
+
+       public function findAll($page)
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM paragraphs_draft
+                                WHERE page = :page
+                                  AND pos > 1
+                                ORDER BY pos";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':page', $page);
+                       $stmt->execute();
+
+                       $paragraphs = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $paragraphs[] = $this->find($row['id']);
+                       }
+
+                       return $paragraphs;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Error fetching all paragraph drafts for page `$page`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     insert()
+
+       public function insert(array $data)
+       {
+               $paragraphSql = "
+                       INSERT INTO paragraphs_draft (active, back_to_top, title,
+                       description, image, caption, page)
+                       VALUES (:active, :back_to_top, :title, :description, :image,
+                              :caption, :page)";
+
+               $filesInsertSql = "
+                       INSERT INTO files_draft (filename, bytes, type, urltext, paragraph)
+                       VALUES (:filename, :bytes, :type, :urltext, :paragraph)";
+
+               try {
+                       $this->dbh->beginTransaction();
+
+                       $paragraphStmt = $this->dbh->prepare($paragraphSql);
+                       $this->setParagraphVars($paragraphStmt, $data);
+                       $paragraphStmt->execute();
+
+                       $row = $this->dbh
+                               ->query('select id from paragraphs_draft order by id desc limit 1')
+                               ->fetch(PDO::FETCH_ASSOC);
+
+                       if (   isset($data['uploaded_files'])
+                               && is_array($data['uploaded_files'])
+                       ) {
+                               $fileInsertStmt = $this->dbh->prepare($filesInsertSql);
+                               $fileInsertStmt->bindParam(':paragraph', $row['id']);
+                               $length = count($data['uploaded_files']['type']);
+                               for ($i = 0; $i < $length; ++$i) {
+                                       $this->setFileVars($fileInsertStmt, $data['uploaded_files'], $i);
+                                       $fileInsertStmt->execute();
+                               }
+                       }
+
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       Toolkit_Logger::logException('DB Error', $e);
+                       $content = serialize($data);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to insert paragraph draft [$content]"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     update()
+
+       public function update(array $data, $id)
+       {
+               $paragraphSql = "
+                       UPDATE paragraphs_draft
+                          SET back_to_top = :back_to_top,
+                                  active = :active,
+                                  title = :title,
+                                  description = :description,
+                                  image = :image,
+                                  caption = :caption,
+                                  page = :page
+                        WHERE id = :id";
+
+               $filesDeleteSql = "
+            DELETE FROM files_draft
+             WHERE paragraph = :id";
+
+               $filesInsertSql = "
+                       INSERT INTO files_draft (filename, bytes, type, urltext, paragraph)
+                       VALUES (:filename, :bytes, :type, :urltext, :paragraph)";
+
+               try {
+                       $this->dbh->beginTransaction();
+
+                       $paragraphStmt = $this->dbh->prepare($paragraphSql);
+                       $this->setParagraphVars($paragraphStmt, $data);
+                       $paragraphStmt->bindParam(':id', $id);
+                       $paragraphStmt->execute();
+
+                       $filesDeleteStmt = $this->dbh->prepare($filesDeleteSql);
+                       $filesDeleteStmt->bindParam(':id', $id);
+                       $filesDeleteStmt->execute();
+
+                       if (   isset($data['uploaded_files'])
+                               && is_array($data['uploaded_files'])
+                       ) {
+                               $fileInsertStmt = $this->dbh->prepare($filesInsertSql);
+                               $fileInsertStmt->bindParam(':paragraph', $id);
+                               $length = count($data['uploaded_files']['type']);
+                               for ($i = 0; $i < $length; ++$i) {
+                                       $this->setFileVars($fileInsertStmt, $data['uploaded_files'], $i);
+                                       $fileInsertStmt->execute();
+                               }
+                       }
+
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       Toolkit_Logger::logException('DB Error', $e);
+                       $content = serialize($data);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to update paragraph draft [$content]"
+                       );
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/ParagraphGatewayDraftFactory.php b/Toolkit/UserArea/ParagraphGatewayDraftFactory.php
new file mode 100644 (file)
index 0000000..b8fbe4e
--- /dev/null
@@ -0,0 +1,10 @@
+<?php
+class Toolkit_UserArea_ParagraphGatewayDraftFactory
+       extends Toolkit_UserArea_GatewayFactoryAbstract
+{
+       public function createGateway()
+       {
+               return new Toolkit_UserArea_ParagraphGatewayDraft($this->dbh);
+       }
+}
+?>
diff --git a/Toolkit/UserArea/ParagraphGatewayPublish.php b/Toolkit/UserArea/ParagraphGatewayPublish.php
new file mode 100644 (file)
index 0000000..14ab5d4
--- /dev/null
@@ -0,0 +1,293 @@
+<?php
+class Toolkit_UserArea_ParagraphGatewayPublish
+       extends Toolkit_UserArea_ParagraphGatewayAbstract
+{
+       //      {{{     delete()
+
+       public function delete($id)
+       {
+               $pageSql = "
+            DELETE
+              FROM paragraphs
+             WHERE id = :id";
+
+               try {
+                       $stmt = $this->dbh->prepare($pageSql);
+                       $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       return $stmt->execute();
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to delete paragraph `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     find()
+
+       public function find($id)
+       {
+               $paragraphSql = "
+            SELECT *
+              FROM paragraphs
+             WHERE id  = :id ";
+
+               $fileSql = "
+                       SELECT id,filename,bytes,type,
+                   coalesce(urltext,filename,'empty') as urltext,
+                   paragraph,pos
+                         FROM files
+                        WHERE paragraph = :paragraph
+                        ORDER BY pos";
+
+               try {
+                       $paragraphStmt = $this->dbh->prepare($paragraphSql);
+                       $paragraphStmt->bindParam(':id', $id, PDO::PARAM_INT);
+                       $paragraphStmt->execute();
+
+                       $paragraph = $paragraphStmt->fetch(PDO::FETCH_ASSOC);
+
+                       if (!empty($paragraph['image'])) {
+                               $imgFormat = "<img src=\"%s{$paragraph['image']}\">";
+                               $paragraph['current_image_original']
+                                       = sprintf($imgFormat, TOOLBOX_ORIGINAL);
+                               $paragraph['current_image_resized']
+                                       = sprintf($imgFormat, TOOLBOX_RESIZED);
+                               $paragraph['current_image_midsized']
+                                       = sprintf($imgFormat, TOOLBOX_MIDSIZED);
+                               $paragraph['current_image_thumb']
+                                       = sprintf($imgFormat, TOOLBOX_THUMB);
+                       } else {
+                               $paragraph['current_image_original'] = 'Image not yet uploaded';
+                               $paragraph['current_image_resized']  = 'Image not yet uploaded';
+                               $paragraph['current_image_midsized'] = 'Image not yet uploaded';
+                               $paragraph['current_image_thumb']    = 'Image not yet uploaded';
+                       }
+
+                       $fileStmt = $this->dbh->prepare($fileSql);
+                       $fileStmt->bindParam(':paragraph', $id, PDO::PARAM_INT);
+                       $fileStmt->execute();
+
+                       $paragraph['files'] = $fileStmt->fetchAll(PDO::FETCH_ASSOC);
+
+                       return $paragraph;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to find paragraph `$id`"
+                       );
+               }
+       }
+
+       //      }}}
+       //      {{{     findAll()
+
+       public function findAll($page)
+       {
+               try {
+                       $sql = "
+                               SELECT *
+                                 FROM paragraphs
+                                WHERE page = :page
+                                  AND pos > 1
+                                ORDER BY pos";
+
+                       $stmt = $this->dbh->prepare($sql);
+                       $stmt->bindParam(':page', $page);
+                       $stmt->execute();
+
+                       $paragraphs = array();
+                       while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+                               $paragraphs[] = $this->find($row['id']);
+                       }
+
+                       return $paragraphs;
+               } catch (PDOException $e) {
+                       Toolkit_Logger::logException('DB Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               "Error fetching all paragraphs for page `$page`"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     insert()
+
+       public function insert(array $data)
+       {
+        // add the part where it throw the file to the server
+        // and returns the data for it
+        if (is_array($_FILES['filename']) && $_FILES['filename']['error'] == 0) {
+            $fs = new Toolkit_FileServer_FileAdapter();
+            try {
+                if ($res = $fs->upload('filename')) {
+                    $data['uploaded_files']['filename'][] = $res['name'];
+                    $data['uploaded_files']['urltext'][] 
+                        = ($data['fileurltext']) 
+                        ? $data['fileurltext']
+                        : $_FILES['filename']['name'];
+                    $data['uploaded_files']['bytes'][] = $res['size'];
+                    $data['uploaded_files']['type'][] = $res['type'];
+                }
+
+            } catch (Toolkit_FileServer_Exception $e) {
+                Toolkit_Logger::logException('File Server', $e);
+                echo -1; // Don't return "false", it will mess up the JS plugin.
+                return;
+            }
+        }
+               $paragraphSql = "
+                       INSERT INTO paragraphs (active, back_to_top, title, description,
+                       image, caption, page)
+                       VALUES (:active, :back_to_top, :title, :description, :image,
+                              :caption, :page)";
+
+               $filesInsertSql = "
+                       INSERT INTO files (filename, bytes, type, urltext, paragraph)
+                       VALUES (:filename, :bytes, :type, :urltext, :paragraph)";
+
+               try {
+                       $this->dbh->beginTransaction();
+
+                       $paragraphStmt = $this->dbh->prepare($paragraphSql);
+                       $this->setParagraphVars($paragraphStmt, $data);
+                       $paragraphStmt->execute();
+
+                       $row = $this->dbh
+                               ->query('select id from paragraphs order by id desc limit 1')
+                               ->fetch(PDO::FETCH_ASSOC);
+
+                       if (   isset($data['uploaded_files'])
+                               && is_array($data['uploaded_files'])
+                       ) {
+                               $fileInsertStmt = $this->dbh->prepare($filesInsertSql);
+                               $fileInsertStmt->bindParam(':paragraph', $row['id']);
+                               $length = count($data['uploaded_files']['type']);
+                               for ($i = 0; $i < $length; ++$i) {
+                                       $this->setFileVars($fileInsertStmt, $data['uploaded_files'], $i);
+                                       $fileInsertStmt->execute();
+                               }
+                       }
+
+            $this->dbh->commit();
+                       return $row['id'];
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       Toolkit_Logger::logException('DB Error', $e);
+                       $content = serialize($data);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to insert paragraph [$content]"
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     update()
+
+       public function update(array $data, $id)
+       {
+        if (is_array($data['deleteFile'])) {
+            foreach ($data['deleteFile'] as $fileNameToDelete) {
+                $delKey = array_search(
+                    $fileNameToDelete, 
+                    $data['uploaded_files']['filename']
+                );
+                unset(
+                    $data['uploaded_files']['urltext'][$delKey],
+                    $data['uploaded_files']['filename'][$delKey],
+                    $data['uploaded_files']['bytes'][$delKey],
+                    $data['uploaded_files']['type'][$delKey]
+                );
+            }
+        }
+
+        // add the part where it throw the file to the server
+        // and returns the data for it
+        if (is_array($_FILES['filename']) && $_FILES['filename']['error'] == 0) {
+            $fs = new Toolkit_FileServer_FileAdapter();
+            try {
+                if ($res = $fs->upload('filename')) {
+                    $data['uploaded_files']['filename'][] = $res['name'];
+                    $data['uploaded_files']['urltext'][] 
+                        = ($data['fileurltext']) 
+                        ? $data['fileurltext']
+                        : $_FILES['filename']['name'];
+                    $data['uploaded_files']['bytes'][] = $res['size'];
+                    $data['uploaded_files']['type'][] = $res['type'];
+                }
+
+            } catch (Toolkit_FileServer_Exception $e) {
+                Toolkit_Logger::logException('File Server', $e);
+                echo -1; // Don't return "false", it will mess up the JS plugin.
+                return;
+            }
+        }
+        //echo '<pre>'.print_r($data, true).'</pre>';
+        //exit;
+        unset(
+            $data['deleteFile'],
+            $data['fileurltext']
+        );
+
+               $paragraphSql = "
+                       UPDATE paragraphs
+                          SET back_to_top = :back_to_top,
+                                  active = :active,
+                                  title = :title,
+                                  description = :description,
+                                  image = :image,
+                                  caption = :caption,
+                                  page = :page
+                        WHERE id = :id";
+
+               $filesDeleteSql = "
+            DELETE FROM files
+             WHERE paragraph = :id";
+
+               $filesInsertSql = "
+                       INSERT INTO files (filename, bytes, type, urltext, paragraph)
+                       VALUES (:filename, :bytes, :type, :urltext, :paragraph)";
+
+               try {
+                       $this->dbh->beginTransaction();
+
+                       $paragraphStmt = $this->dbh->prepare($paragraphSql);
+                       $this->setParagraphVars($paragraphStmt, $data);
+                       $paragraphStmt->bindParam(':id', $id);
+                       $paragraphStmt->execute();
+
+                       $filesDeleteStmt = $this->dbh->prepare($filesDeleteSql);
+                       $filesDeleteStmt->bindParam(':id', $id);
+                       $filesDeleteStmt->execute();
+
+                       if (   isset($data['uploaded_files'])
+                               && is_array($data['uploaded_files'])
+                       ) {
+                               $fileInsertStmt = $this->dbh->prepare($filesInsertSql);
+                               $fileInsertStmt->bindParam(':paragraph', $id);
+                               $length = count($data['uploaded_files']['type']);
+                $fileArrayKeys = array_keys($data['uploaded_files']['type']);
+                foreach ($fileArrayKeys as $i) {
+                                       $this->setFileVars($fileInsertStmt, $data['uploaded_files'], $i);
+                                       $fileInsertStmt->execute();
+                               }
+                       }
+
+                       return $this->dbh->commit();
+               } catch (PDOException $e) {
+                       $this->dbh->rollback();
+                       Toolkit_Logger::logException('DB Error', $e);
+                       $content = serialize($data);
+                       throw new Toolkit_UserArea_Exception(
+                               "Unable to update paragraph [$content]"
+                       );
+               }
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/ParagraphGatewayPublishFactory.php b/Toolkit/UserArea/ParagraphGatewayPublishFactory.php
new file mode 100644 (file)
index 0000000..71a90b3
--- /dev/null
@@ -0,0 +1,10 @@
+<?php
+class Toolkit_UserArea_ParagraphGatewayPublishFactory
+       extends Toolkit_UserArea_GatewayFactoryAbstract
+{
+       public function createGateway()
+       {
+               return new Toolkit_UserArea_ParagraphGatewayPublish($this->dbh);
+       }
+}
+?>
diff --git a/Toolkit/UserArea/ParagraphsController.php b/Toolkit/UserArea/ParagraphsController.php
new file mode 100644 (file)
index 0000000..57b9df4
--- /dev/null
@@ -0,0 +1,348 @@
+<?php
+/**
+ * ParagraphsController.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Toolbox
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_UserArea_ParagraphsController
+ *
+ * Description for Toolkit_UserArea_ParagraphsController
+ *
+ * @category Toolkit
+ * @package  Toolbox
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+class Toolkit_UserArea_ParagraphsController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     _getForm()
+
+    /**
+     * Description for _getForm()
+     *
+     * @return \Toolkit_UserArea_Forms_EditParagraph
+     * @access private
+     */
+    private function _getForm()
+    {
+        //  Need three separate objects otherwise, new parses overwrite existing
+        //  root variable data.
+        $tlbConf = new Config;
+        $memConf = new Config;
+        $cpnConf = new Config;
+
+        $memRoot =& $memConf->parseConfig(
+            BASE . 'Toolkit/Members/config.ini',
+            'IniFile'
+        );
+        $cpnRoot =& $cpnConf->parseConfig(
+            BASE . 'Toolkit/Coupons/config.ini',
+            'IniFile'
+        );
+        $tbxRoot =& $tlbConf->parseConfig(
+            BASE . 'Toolkit/UserArea/config.ini',
+            'IniFile'
+        );
+
+        $form = new Toolkit_UserArea_Forms_EditParagraph(
+            'edit_paragraph',
+            'post',
+           MEDIA_BASE_URL . 'userArea/toolbox.php?rt=Paragraphs&ac=process'
+        );
+               $form->configureForm(
+                       $this->registry->dbh,
+                       new Toolkit_UserArea_ParagraphGatewayPublishFactory($this->registry->dbh),
+                       new Toolkit_FileServer_ImageAdapter(),
+                       new Toolkit_FileServer_FileAdapter(),
+                       new Toolkit_UserArea_FileExtension
+               );
+
+        return $form;
+    }
+
+       //      }}}
+
+       //      {{{     editAction()
+
+    /**
+     * Description for editAction()
+     *
+     * @return string
+     * @access public
+     */
+       public function editAction()
+       {
+           if (ctype_digit($_GET['pageid'])) {
+                       $breadCrumbs = new Toolkit_UserArea_ParagraphBreadCrumbs(
+                           $this->registry->dbh,
+                           $_GET['pageid']
+                       );
+                       $html = (string) $breadCrumbs;
+           }
+
+           $form = $this->_getForm();
+               $html .= $form->toHtml($this->registry->dbh);
+
+               return $html;
+       }
+
+       //      }}}
+
+       //      {{{     indexAction()
+
+    /**
+     * Description for indexAction()
+     *
+     * @return string
+     * @throws Toolkit_UserArea_Exception
+     * @throws RuntimeException
+     * @access public
+     */
+       public function indexAction()
+       {
+           if (ctype_digit($_GET['pageid'])) {
+                       $breadCrumbs = new Toolkit_UserArea_ParagraphBreadCrumbs(
+                               $this->registry->dbh,
+                               $_GET['pageid']
+                       );
+                       $html = (string) $breadCrumbs;
+           }
+
+               try {
+                       if (!ctype_digit($_GET['pageid'])) {
+                               throw new RuntimeException(
+                                       "Category id `{$_GET['pageid']}` is not an integer"
+                               );
+                       }
+
+                       $toolboxConfig = new Config;
+                       $toolboxConfigRoot =& $toolboxConfig->parseConfig(
+                               BASE . 'Toolkit/UserArea/config.ini',
+                               'IniFile'
+                       );
+                       $tree = new Toolkit_UserArea_ParagraphsTree($toolboxConfigRoot);
+                       $html .= $tree->toHtml(
+                               new Toolkit_UserArea_ParagraphGatewayPublish($this->registry->dbh)
+                       );
+
+                       return $html;
+               } catch (RuntimeException $e) {
+                       Toolkit_Logger::logException('Runtime Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               'Category id must be an integer'
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     processAction()
+
+    /**
+     * Description for processAction()
+     *
+     * @return string
+     * @access public
+     */
+       public function processAction()
+       {
+        $form = $this->_getForm();
+
+               if ($form->isSubmitted()) {
+                       if ($form->getSubmitValue('cancel')) {
+                               //      do nothing
+                               $pageid = $form->getSubmitValue('page');
+                               header('Location: ' .MEDIA_BASE_URL . "userArea/toolbox.php?rt=Paragraphs&pageid=$pageid");
+                               exit();
+                       } elseif ($form->getSubmitValue('previewParagraph')) {
+                       } elseif ($form->getSubmitValue('saveParagraph')) {
+                               //      save paragraph
+                               $gateway = new Toolkit_UserArea_ParagraphGatewayPublish($this->registry->dbh);
+
+                               if ($form->validate()) {
+                                       $paragraphId = $form->getSubmitValue('id');
+                                       if ($paragraphId) {
+                                               $gateway->update($form->getSubmitValues(), $paragraphId);
+                                       } else {
+                                               $paragraphId = $gateway->insert($form->getSubmitValues());
+                                       }
+                                       $pageid = $form->getSubmitValue('page');
+                    // try to get AuthUser from registry
+                    $authUser = Registry::get('Toolkit_UserArea_Auth');
+                    $userId   = $authUser->getAuthData('id');
+                    $sql = "
+                    SELECT id,navigation_name
+                      FROM pages
+                     WHERE id = {$form->getSubmitValue('page')}";
+                    $page
+                        = $this->registry->dbh
+                        ->query($sql)->fetch(PDO::FETCH_ASSOC);
+                    $logData = array(
+                        'user_id'     => $userId,
+                        'alter_time'  => date('m/d/Y H:i:s'),
+                        'db_table'    => 'paragraph',
+                        'alter_type'  => 'update',
+                        'foreign_key' => $paragraphId,
+                        'comment'     => 'Paragraph From ' . $page['navigation_name']
+                    );
+
+                    try {
+                        $log = Toolkit_UserArea_Admin_Log::createLogWithValues($logData);
+                        $log->save($this->registry->dbh);
+                    } catch(InvalidArgumentException $e) {
+                        echo $e->getTraceAsString();
+                        echo $e->getMessage();
+                        exit;
+                    }
+                    try {
+                        $deleteFile = $form->getSubmitValue('deleteFile');
+                        if (is_array($deleteFile) && !empty($deleteFile)) {
+                            $fs = new Toolkit_FileServer_FileAdapter();
+                            foreach ($deleteFile as $delFile) {
+                                $fs->delete($delFile);
+                            }
+                        }
+                        $image = $form->getSubmitValue('image');
+                        if ($form->getSubmitValue('remove_image') == '1'
+                            && $image
+                        ) {
+                            $is = new Toolkit_FileServer_ImageAdapter();
+                            $is->delete($image);
+                        }
+                    } catch(Toolkit_FileServer_Exception $fileError) {
+                        Toolkit_Common::handleError($fileError);
+                    }
+
+                                       $cache = new Cache_Lite($GLOBALS['cacheOptions']);
+                                       $cache->remove("page-$pageid", 'Toolbox');
+                                       $cache->remove("paragraphs-$pageid", 'Toolbox');
+                                       $cache->remove("sectionLinks-$pageid", 'Toolbox');
+
+                    header(
+                        'Location: '
+                        .MEDIA_BASE_URL
+                        . "userArea/toolbox.php?rt=Paragraphs"
+                        . "&ac=edit&id={$paragraphId}&pageid={$pageid}&g=1"
+                    );
+                                       exit();
+                               } else {
+                                       $return  = $form->getErrorMessage();
+                                       $return .= $form->toHtml($this->registry->dbh);
+                               }
+                       } elseif ($form->getSubmitValue('deleteParagraph')) {
+                try {
+                    $files = $form->getSubmitValue('uploaded_files');
+                    $deleteFile = $files['filename'];
+                    if (is_array($deleteFile) && !empty($deleteFile)) {
+                        $fs = new Toolkit_FileServer_FileAdapter();
+                        foreach ($deleteFile as $delFile) {
+                            $fs->delete($delFile);
+                        }
+                    }
+                    $image = $form->getSubmitValue('image');
+                    if ($image) {
+                        $is = new Toolkit_FileServer_ImageAdapter();
+                        $is->delete($image);
+                    }
+                } catch(Toolkit_FileServer_Exception $fileError) {
+                        Toolkit_Common::handleError($fileError);
+                }
+                               //      delete paragraph
+                               $gateway = new Toolkit_UserArea_ParagraphGatewayPublish($this->registry->dbh);
+                               $gateway->delete($form->getSubmitValue('id'));
+
+                // try to get AuthUser from registry
+                $authUser = Registry::get('Toolkit_UserArea_Auth');
+                $userId   = $authUser->getAuthData('id');
+                $sql = "
+                SELECT id,navigation_name
+                  FROM pages
+                 WHERE id = {$form->getSubmitValue('page')}";
+                $page
+                    = $this->registry->dbh
+                    ->query($sql)->fetch(PDO::FETCH_ASSOC);
+                $logData = array(
+                    'user_id'     => $userId,
+                    'alter_time'  => date('m/d/Y H:i:s'),
+                    'db_table'    => 'paragraph',
+                    'alter_type'  => 'delete',
+                    'foreign_key' => $form->getSubmitValue('id'),
+                    'comment'     => 'Paragraph From ' . $page['navigation_name']
+                );
+
+                try {
+                    $log = Toolkit_UserArea_Admin_Log::createLogWithValues($logData);
+                    $log->save($this->registry->dbh);
+                } catch(InvalidArgumentException $e) {
+                    echo $e->getTraceAsString();
+                    echo $e->getMessage();
+                    exit;
+                }
+
+                               $pageid = $form->getSubmitValue('page');
+
+                               $cache = new Cache_Lite($GLOBALS['cacheOptions']);
+                               $cache->remove("page-$pageid", 'Toolbox');
+                               $cache->remove("paragraphs-$pageid", 'Toolbox');
+                               $cache->remove("sectionLinks-$pageid", 'Toolbox');
+
+                               $paragraphTitle = $form->getSubmitValue('title');
+                               $return = "[<b>$paragraphTitle</b>] successfully deleted.";
+                try {
+                    $dbh = Toolkit_Database::getInstance();
+                    $sql = "
+                    UPDATE paragraphs
+                       SET pos = :pos
+                     WHERE id = :id";
+                    $updateParagraphPos = $dbh->prepare($sql);
+                    $sql = "
+                    SELECT id,page,pos
+                      FROM paragraphs
+                     WHERE page = :page
+                     ORDER BY page,pos";
+                    $res = $dbh->prepare($sql);
+                    $res->bindParam(':page', $pageid, PDO::PARAM_INT);
+                    $res->execute();
+                    while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
+                        $paragraphData[$row['page']][] = $row['id'];
+                    }
+                    if (is_array($paragraphData)) {
+                        $curPage = 0;
+                        $pos = 1;
+                        foreach ($paragraphData as $page => $paragraphs) {
+                            if ($curPage != $page) {
+                                $curPage = $page;
+                                $pos = 1;
+                            }
+                            foreach ($paragraphs as $paragraphId) {
+                                $updateParagraphPos->bindParam(":pos", $pos, PDO::PARAM_INT);
+                                $updateParagraphPos->bindParam(":id", $paragraphId, PDO::PARAM_INT);
+                                $updateParagraphPos->execute();
+                                ++$pos;
+                            }
+                        }
+                    }
+                } catch(PDOException $e) {
+                    die($e->getMessage());
+                }
+                       }
+               } else {
+                       $return = $form->toHtml($this->registry->dbh);
+               }
+
+        return $return;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/ParagraphsDraftController.php b/Toolkit/UserArea/ParagraphsDraftController.php
new file mode 100644 (file)
index 0000000..07695b3
--- /dev/null
@@ -0,0 +1,154 @@
+<?php
+
+class Toolkit_UserArea_ParagraphsDraftController
+       extends Toolkit_BaseControllerAbstract implements Toolkit_IController
+{
+       //      {{{     _getForm()
+
+    private function _getForm()
+    {
+        //  Need three separate objects otherwise, new parses overwrite existing
+        //  root variable data.
+        $tlbConf = new Config;
+        $memConf = new Config;
+        $cpnConf = new Config;
+
+        $memRoot =& $memConf->parseConfig(
+            BASE . 'Toolkit/Members/config.ini',
+            'IniFile'
+        );
+        $cpnRoot =& $cpnConf->parseConfig(
+            BASE . 'Toolkit/Coupons/config.ini',
+            'IniFile'
+        );
+        $tbxRoot =& $tlbConf->parseConfig(
+            BASE . 'Toolkit/UserArea/config.ini',
+            'IniFile'
+        );
+
+        $form = new Toolkit_UserArea_Forms_EditParagraph(
+            'edit_paragraph',
+            'post',
+           MEDIA_BASE_URL . 'userArea/toolbox.php?rt=ParagraphsDraft&ac=process'
+        );
+               $form->configureForm(
+                       $this->registry->dbh,
+                       new Toolkit_UserArea_ParagraphGatewayDraftFactory($this->registry->dbh),
+                       new Toolkit_FileServer_ImageAdapter(),
+                       new Toolkit_FileServer_FileAdapter(),
+                       new Toolkit_UserArea_FileExtension
+               );
+
+        return $form;
+    }
+
+       //      }}}
+
+       //      {{{     editAction()
+
+       public function editAction()
+       {
+           if (ctype_digit($_GET['pageid'])) {
+                       $breadCrumbs = new Toolkit_UserArea_ParagraphDraftBreadCrumbs(
+                               $this->registry->dbh,
+                               $_GET['pageid']
+                       );
+                       $html = (string) $breadCrumbs;
+               }
+
+           $form = $this->_getForm();
+               $html .= $form->toHtml($this->registry->dbh);
+
+               return $html;
+       }
+
+       //      }}}
+
+       //      {{{     indexAction()
+
+       public function indexAction()
+       {
+           if (ctype_digit($_GET['pageid'])) {
+                       $breadCrumbs = new Toolkit_UserArea_ParagraphDraftBreadCrumbs(
+                               $this->registry->dbh,
+                               $_GET['pageid']
+                       );
+                       $html = (string) $breadCrumbs;
+               }
+
+               try {
+                       if (!ctype_digit($_GET['pageid'])) {
+                               throw new RuntimeException(
+                                       "Category id `{$_GET['pageid']}` is not an integer"
+                               );
+                       }
+
+                       $toolboxConfig = new Config;
+                       $toolboxConfigRoot =& $toolboxConfig->parseConfig(
+                               BASE . 'Toolkit/UserArea/config.ini',
+                               'IniFile'
+                       );
+                       $tree = new Toolkit_UserArea_ParagraphsDraftTree($toolboxConfigRoot);
+                       $html .= $tree->toHtml(
+                               new Toolkit_UserArea_ParagraphGatewayDraft($this->registry->dbh)
+                       );
+
+                       return $html;
+               } catch (RuntimeException $e) {
+                       Toolkit_Logger::logException('Runtime Error', $e);
+                       throw new Toolkit_UserArea_Exception(
+                               'Category id must be an integer'
+                       );
+               }
+       }
+
+       //      }}}
+
+       //      {{{     processAction()
+
+       public function processAction()
+       {
+        $form = $this->_getForm();
+
+               if ($form->isSubmitted()) {
+                       if ($form->getSubmitValue('cancel')) {
+                               //      do nothing
+                               $pageid = $form->getSubmitValue('page');
+                               header('Location: ' .MEDIA_BASE_URL . "userArea/toolbox.php?rt=ParagraphsDraft&pageid=$pageid");
+                               exit();
+                       } elseif ($form->getSubmitValue('previewParagraph')) {
+                       } elseif ($form->getSubmitValue('saveParagraph')) {
+                               //      save paragraph
+                               $gateway = new Toolkit_UserArea_ParagraphGatewayDraft($this->registry->dbh);
+                               if ($form->validate()) {
+                                       $paragraphId = $form->getSubmitValue('id');
+                                       if ($paragraphId) {
+                                               $gateway->update($form->getSubmitValues(), $paragraphId);
+                                       } else {
+                                               $gateway->insert($form->getSubmitValues());
+                                       }
+                                       $pageid = $form->getSubmitValue('page');
+                                       header('Location: ' .MEDIA_BASE_URL . "userArea/toolbox.php?rt=ParagraphsDraft&pageid=$pageid");
+                                       exit();
+                               } else {
+                                       $return  = $form->getErrorMessage();
+                                       $return .= $form->toHtml();
+                               }
+                       } elseif ($form->getSubmitValue('deleteParagraph')) {
+                               //      delete paragraph
+                               $gateway = new Toolkit_UserArea_ParagraphGatewayDraft($this->registry->dbh);
+                               $gateway->delete($form->getSubmitValue('id'));
+
+                               $paragraphTitle = $form->getSubmitValue('title');
+                               $return = "[<b>$paragraphTitle</b>] successfully deleted.";
+                       }
+               } else {
+                       $return = $form->toHtml();
+               }
+
+        return $return;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/ParagraphsDraftTree.php b/Toolkit/UserArea/ParagraphsDraftTree.php
new file mode 100644 (file)
index 0000000..78c8c7e
--- /dev/null
@@ -0,0 +1,86 @@
+<?php
+class Toolkit_UserArea_ParagraphsDraftTree extends Toolkit_UserArea_TreeAbstract
+{
+       //      {{{     getActiveBall()
+
+       protected function getActiveBall(array $branch)
+       {
+               $activeFormat  = '<a href="%s" title="%s">';
+               $activeFormat .=        $this->getActiveBallImage($branch);
+               $activeFormat .= '</a>';
+
+               return sprintf(
+                       $activeFormat,
+               MEDIA_BASE_URL . "userArea/toolbox.php?rt=ParagraphsDraft&id={$_GET['id']}",
+                       $branch['active_alt']
+               );
+       }
+
+       //      }}}
+
+       //      {{{     createTree()
+
+       protected function createTree(array $tree, $leaf, $level = 0)
+       {
+               if (empty($leaf)) {
+                       return '<h2>No paragraph drafts created for this page yet</h2>'; // page has no paragraphs
+               }
+
+               $html = $this->rootNodeStart;
+
+               while (list($parent, $branch) = each($leaf)) {
+                       $html .= sprintf($this->leafStart, $branch['id'], null);
+
+                       $html .= "<strong>{$branch['title']}</strong>";
+                       $html .= '<div class="right-element">';
+                       $html .= '<a href="'.MEDIA_BASE_URL.'userArea/toolbox.php?rt=ParagraphsDraft&ac=edit&id='.$branch['id'].'&pageid='.$_GET['pageid'].'">[Edit]</a> ';
+                       $html .= $this->getActiveBall($branch);
+                       $html .= '</div>';
+                       $html .= $this->leafEnd;
+               }
+
+               $html .= $this->treeEnd;
+               return $html;
+       }
+
+       //      }}}
+
+       //      {{{     fetchContent()
+
+       protected function fetchContent(Toolkit_UserArea_GatewayAbstract $gateway)
+       {
+               $paragraphs = $gateway->findAll($_GET['pageid']);
+               if (is_array($paragraphs)) {
+                       $threads = array();
+                       foreach ($paragraphs as $paragraph) {
+                               $threads[] = $paragraph;
+                       }
+
+                       $children = array();
+                       while (list($key, $value) = each ($threads)) {
+                               $children[0][$value['id']] = $value;
+                       }
+
+                       $this->tree = $children;
+               } else {
+                       $this->tree = array();
+               }
+       }
+
+       //      }}}
+       //      {{{     toHtml()
+
+       public function toHtml(Toolkit_UserArea_GatewayAbstract $gateway)
+       {
+               $GLOBALS['bottomScripts'][] = MEDIA_BASE_URL . 'Toolkit/UserArea/libjs/paragraph-tree.js';
+               $GLOBALS['bottomScripts'][] = MEDIA_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/jquery.tree.js';
+
+               $this->fetchContent($gateway);
+               $html = parent::toHtml();
+
+               return "<div id=\"tree\">$html</div>";
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/ParagraphsTree.php b/Toolkit/UserArea/ParagraphsTree.php
new file mode 100644 (file)
index 0000000..df5901b
--- /dev/null
@@ -0,0 +1,120 @@
+<?php
+class Toolkit_UserArea_ParagraphsTree extends Toolkit_UserArea_TreeAbstract
+{
+       protected $leafStart = "\n\t<li id=\"cat_%s\" %s>\n";
+       //      {{{     getActiveBall()
+
+       protected function getActiveBall(array $branch)
+       {
+               $activeFormat  = '<a class="active-ball" rel="%s" href="%s" title="%s">';
+               $activeFormat .=        $this->getActiveBallImage($branch);
+               $activeFormat .= '</a>';
+
+               return sprintf(
+                       $activeFormat,
+                       $branch['id'],
+               MEDIA_BASE_URL . "userArea/toolbox.php?rt=Paragraphs&amp;id={$branch['id']}",
+                       $branch['active_alt']
+               );
+       }
+
+       //      }}}
+       //      {{{     _getMoveArrows()
+
+       private function _getMoveArrows()
+       {
+               $format = '<img src="%s" alt="Move %s Arrow" class="move%s">';
+
+               $up = sprintf(
+                       $format,
+                       MEDIA_APP_BASE_URL . "assets/icons/arrow_up.png",
+                       'Up',
+                       'Up'
+               );
+
+               $down = sprintf(
+                       $format,
+                       MEDIA_APP_BASE_URL . "assets/icons/arrow_down.png",
+                       'Down',
+                       'Down'
+               );
+
+               return $up . $down;
+       }
+
+       //      }}}
+
+    private function _getPositionSelect($branch)/*{{{*/
+    {
+        return '<select class="pos-select" name="pos'.$branch['id'].'" rel="'.$branch['pos'].'"></select>';
+    }/*}}}*/
+       //      {{{     createTree()
+
+       protected function createTree(array $tree, $leaf, $level = 0)
+       {
+               if (empty($leaf)) {
+                       return '<h2>No paragraphs created for this page yet</h2>'; // page has no paragraphs
+               }
+
+               $html = $this->rootNodeStart;
+
+               while (list($parent, $branch) = each($leaf)) {
+                       $html .= sprintf($this->leafStart, $branch['id'], null);
+
+                       $html .= '<div class="right-element paragraph-line">';
+                       $html .= '<a class="editPage" href="'.MEDIA_BASE_URL.'userArea/toolbox.php?rt=Paragraphs&amp;ac=edit&amp;id='.$branch['id'].'&amp;pageid='.$_GET['pageid'].'">[Edit]</a> ';
+                       $html .= $this->getActiveBall($branch);
+                       if (count($leaf) > 1) {
+                           $html .= $this->_getPositionSelect($branch);
+                       }
+                       $html .= "<strong>{$branch['title']}</strong>";
+                       $html .= '</div>';
+
+                       $html .= $this->leafEnd;
+               }
+
+               $html .= $this->treeEnd;
+               return $html;
+       }
+
+       //      }}}
+
+       //      {{{     fetchContent()
+
+       protected function fetchContent(Toolkit_UserArea_GatewayAbstract $gateway)
+       {
+               $paragraphs = $gateway->findAll($_GET['pageid']);
+               if (is_array($paragraphs)) {
+                       $threads = array();
+                       foreach ($paragraphs as $paragraph) {
+                               $threads[] = $paragraph;
+                       }
+
+                       $children = array();
+                       while (list($key, $value) = each ($threads)) {
+                               $children[0][$value['id']] = $value;
+                       }
+
+                       $this->tree = $children;
+               } else {
+                       $this->tree = array();
+               }
+       }
+
+       //      }}}
+       //      {{{     toHtml()
+
+       public function toHtml(Toolkit_UserArea_GatewayAbstract $gateway)
+       {
+               $GLOBALS['bottomScripts'][] = MEDIA_BASE_URL . 'Toolkit/UserArea/libjs/paragraph-tree.js';
+               $GLOBALS['bottomScripts'][] = MEDIA_APP_BASE_URL . 'libjs/plugins/jsTree/0.9.9a2/jquery.tree.js';
+
+               $this->fetchContent($gateway);
+               $html = parent::toHtml();
+
+               return "<div id=\"tree\">$html</div>";
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/SearchController.php b/Toolkit/UserArea/SearchController.php
new file mode 100644 (file)
index 0000000..ab35b4c
--- /dev/null
@@ -0,0 +1,50 @@
+<?php
+
+class Toolkit_UserArea_SearchController extends Toolkit_BaseControllerAbstract
+       implements Toolkit_IController
+{
+       //      {{{     index()
+
+       public function indexAction()
+       {
+               $searchForm = new Toolkit_UserArea_PageSearchForm(
+                       'search_form',
+                       'get',
+               MEDIA_BASE_URL . 'userArea/toolbox.php?rt=search',
+                       null,
+                       null,
+                       true
+               );
+               $searchForm->configureForm();
+
+               $html = $searchForm->toHtml();
+
+        $toolbox = new GLM_TEMPLATE( NULL );
+               $sql = "
+                       SELECT id, parent, pos, active,
+                                  CASE WHEN keyword IS NOT NULL AND keyword <> ''
+                                               THEN category || ' {' || keyword || '}'
+                                               ELSE category
+                                       END AS category,
+                                  CASE WHEN active THEN 'Display'
+                                               ELSE 'Don\'t Display'
+                                       END AS active_alt
+                         FROM bus_category
+             WHERE lower(category) LIKE :search";
+
+               $stmt = $this->registry->dbh->prepare($sql);
+               $stmt->bindParam(':search', strtolower("%{$_GET['q']}%"), PDO::PARAM_STR);
+               $stmt->execute();
+
+               $threads = $stmt->fetchAll(PDO::FETCH_ASSOC);
+
+               $tree = new Toolkit_UserArea_SearchTree(new GLM_TEMPLATE(null));
+               $sortedLeafs = $tree->sortChildren($threads, true);
+               $html .= $tree->toHtml($sortedLeafs, $sortedLeafs[0]);
+
+               return $html;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/SearchTree.php b/Toolkit/UserArea/SearchTree.php
new file mode 100644 (file)
index 0000000..12b6dd5
--- /dev/null
@@ -0,0 +1,35 @@
+<?php
+class Toolkit_UserArea_SearchTree extends Toolkit_UserArea_PagesTree
+{
+       //      {{{     getActiveBall()
+
+       protected function getActiveBall(array $branch)
+       {
+               $activeFormat = '<a href="%s" title="%s"><img src="%s" alt="%s"></a>';
+               $img = $branch['active'] ? 'grnball.gif' : 'redball.gif';
+               $q = urlencode(stripslashes($_GET['q']));
+               return sprintf(
+                       $activeFormat,
+               MEDIA_BASE_URL . "userArea/toolbox.php?id={$branch['id']}&amp;_qf__search_form=&amp;rt=Search&amp;q=$q",
+                       $branch['active_alt'],
+               MEDIA_BASE_URL . "Toolkit/UserArea/assets/$img",
+                       $branch['active_alt']
+               );
+       }
+
+       //      }}}
+       //      {{{     sortChildren()
+
+       public function sortChildren(array $threads)
+       {
+               $children = array();
+               while (list($key, $value) = each ($threads)) {
+                       $children[0][$value['id']] = $value;
+               }
+
+               return $children;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/TreeAbstract.php b/Toolkit/UserArea/TreeAbstract.php
new file mode 100644 (file)
index 0000000..da78d74
--- /dev/null
@@ -0,0 +1,230 @@
+<?php
+/**
+ * TreeAbstract.php
+ *
+ * PHP version 5
+ *
+ * @category Toolkit
+ * @package  Toolbox
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+
+/**
+ * Toolkit_UserArea_TreeAbstract
+ *
+ * Description for Toolkit_UserArea_TreeAbstract
+ *
+ * @category Toolkit
+ * @package  Toolbox
+ * @author   Jamie Kahgee <steve@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @link     <>
+ */
+abstract class Toolkit_UserArea_TreeAbstract
+{
+       //      {{{     properties
+
+
+    /**
+     * Description for $rootNodeStart
+     * @var string
+     * @access protected
+     */
+       protected $rootNodeStart = "<ul>\n";
+
+    /**
+     * Description for $subTreeStart
+     * @var string
+     * @access protected
+     */
+       protected $subTreeStart = "\n<ul>\n";
+
+    /**
+     * Description for $treeEnd
+     * @var string
+     * @access protected
+     */
+       protected $treeEnd = "\n</ul>\n";
+
+    /**
+     * Description for $leafStart
+     * @var string
+     * @access protected
+     */
+       protected $leafStart = "\n\t<li>\n";
+
+    /**
+     * Description for $leafEnd
+     * @var string
+     * @access protected
+     */
+       protected $leafEnd = "\n\t</li>\n";
+
+    /**
+     * Description for $config
+     * @var Config_Container
+     * @access protected
+     */
+       protected $config;
+
+    /**
+     * Description for $tree
+     * @var array
+     * @access protected
+     */
+       protected $tree;
+
+       //      }}}
+       //      {{{     __construct()
+
+    /**
+     * Class constructor
+     *
+     * @param Config_Container $config Config container
+     *
+     * @return void
+     * @access public
+     */
+       public function __construct(Config_Container $config)
+       {
+               $this->config = $config;
+       }
+
+       //      }}}
+
+       //      {{{     getActiveBallImage()
+
+    /**
+     * Description for getActiveBallImage()
+     *
+     * @param array $branch Branch array
+     *
+     * @return string
+     * @access protected
+     */
+       protected function getActiveBallImage(array $branch)
+       {
+               $imgFormat = '<img %s src="%s" alt="%s" border="0">';
+
+               $show = sprintf(
+                       $imgFormat,
+                       ($branch['active']) ? '' : 'style="display: none;"',
+               MEDIA_BASE_URL . "Toolkit/UserArea/assets/grnball.gif",
+                       'Active Ball'
+               );
+
+               $hide = sprintf(
+                       $imgFormat,
+                       ($branch['active']) ? 'style="display: none;"' : '',
+               MEDIA_BASE_URL . "Toolkit/UserArea/assets/redball.gif",
+                       "In-active Ball"
+               );
+
+               return $show . $hide;
+       }
+
+    // }}}
+       //      {{{     getActiveMobileBallImage()
+
+    /**
+     * Description for getActiveMobileBallImage()
+     *
+     * @param array $branch Branch array
+     *
+     * @return string
+     * @access protected
+     */
+       protected function getActiveMobileBallImage(array $branch)
+       {
+               $imgFormat = '<img %s src="%s" alt="%s" border="0">';
+
+               $show = sprintf(
+                       $imgFormat,
+                       ($branch['mobile_active']) ? '' : 'style="display: none;"',
+               MEDIA_BASE_URL . "Toolkit/UserArea/assets/mobilemgreen.jpg",
+                       'Active Ball'
+               );
+
+               $hide = sprintf(
+                       $imgFormat,
+                       ($branch['mobile_active']) ? 'style="display: none;"' : '',
+               MEDIA_BASE_URL . "Toolkit/UserArea/assets/mobilemred.jpg",
+                       "In-active Ball"
+               );
+
+               return $show . $hide;
+       }
+
+    // }}}
+       //      {{{     getActiveBall()
+
+    /**
+     * Description for getActiveBall()
+     *
+     * @param array $branch Branch array
+     *
+     * @access protected
+     * @return void
+     */
+       abstract protected function getActiveBall(array $branch);
+
+       //      }}}
+
+       //      {{{     createTree()
+
+    /**
+     * Description for createTree
+     *
+     * @param array   $tree  Description for $tree ...
+     * @param unknown $leaf  Description for $leaf ...
+     * @param int     $level Description for $level ...
+     *
+     * @return void
+     * @access protected
+     */
+       abstract protected function createTree(array $tree, $leaf, $level = 0);
+
+       //      }}}
+       //      {{{     fetchContent()
+
+    /**
+     * Description for fetchContent
+     *
+     * @param Toolkit_UserArea_GatewayAbstract $gateway Toolbox Gateway
+     *
+     * @return void
+     * @access protected
+     */
+       abstract protected function fetchContent(
+               Toolkit_UserArea_GatewayAbstract $gateway
+       );
+
+       //      }}}
+
+       //      {{{     toHtml()
+
+    /**
+     * Description of toHtml()
+     *
+     * @return string
+     * @access public
+     */
+       public function toHtml()
+       {
+//             $GLOBALS['styleSheets'][] =MEDIA_BASE_URL . 'admin/main.css';
+               $GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'Toolkit/UserArea/styles.css';
+               $GLOBALS['topScripts'][]
+                       = MEDIA_APP_BASE_URL . 'libjs/jquery/jquery-1.4.2.min.js';
+
+               if (is_array($this->tree)) {
+                       $html = $this->createTree($this->tree, reset($this->tree));
+               }
+
+               return $html;
+       }
+
+       //      }}}
+}
+?>
diff --git a/Toolkit/UserArea/assets/.keepme b/Toolkit/UserArea/assets/.keepme
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/Toolkit/UserArea/assets/arrow.png b/Toolkit/UserArea/assets/arrow.png
new file mode 100755 (executable)
index 0000000..ee11ab4
Binary files /dev/null and b/Toolkit/UserArea/assets/arrow.png differ
diff --git a/Toolkit/UserArea/assets/arrowClosed.png b/Toolkit/UserArea/assets/arrowClosed.png
new file mode 100755 (executable)
index 0000000..3b34262
Binary files /dev/null and b/Toolkit/UserArea/assets/arrowClosed.png differ
diff --git a/Toolkit/UserArea/assets/arrowOpen.png b/Toolkit/UserArea/assets/arrowOpen.png
new file mode 100755 (executable)
index 0000000..6967dea
Binary files /dev/null and b/Toolkit/UserArea/assets/arrowOpen.png differ
diff --git a/Toolkit/UserArea/assets/collapse.png b/Toolkit/UserArea/assets/collapse.png
new file mode 100755 (executable)
index 0000000..d10e051
Binary files /dev/null and b/Toolkit/UserArea/assets/collapse.png differ
diff --git a/Toolkit/UserArea/assets/expand.png b/Toolkit/UserArea/assets/expand.png
new file mode 100755 (executable)
index 0000000..38dcfc0
Binary files /dev/null and b/Toolkit/UserArea/assets/expand.png differ
diff --git a/Toolkit/UserArea/assets/grnball.gif b/Toolkit/UserArea/assets/grnball.gif
new file mode 100755 (executable)
index 0000000..5f7740b
Binary files /dev/null and b/Toolkit/UserArea/assets/grnball.gif differ
diff --git a/Toolkit/UserArea/assets/mobilemgreen.jpg b/Toolkit/UserArea/assets/mobilemgreen.jpg
new file mode 100644 (file)
index 0000000..a5fc6ce
Binary files /dev/null and b/Toolkit/UserArea/assets/mobilemgreen.jpg differ
diff --git a/Toolkit/UserArea/assets/mobilemred.jpg b/Toolkit/UserArea/assets/mobilemred.jpg
new file mode 100644 (file)
index 0000000..217826d
Binary files /dev/null and b/Toolkit/UserArea/assets/mobilemred.jpg differ
diff --git a/Toolkit/UserArea/assets/redball.gif b/Toolkit/UserArea/assets/redball.gif
new file mode 100755 (executable)
index 0000000..7005133
Binary files /dev/null and b/Toolkit/UserArea/assets/redball.gif differ
diff --git a/Toolkit/UserArea/assets/template1.gif b/Toolkit/UserArea/assets/template1.gif
new file mode 100755 (executable)
index 0000000..327d943
Binary files /dev/null and b/Toolkit/UserArea/assets/template1.gif differ
diff --git a/Toolkit/UserArea/assets/template2.gif b/Toolkit/UserArea/assets/template2.gif
new file mode 100755 (executable)
index 0000000..edf3d8b
Binary files /dev/null and b/Toolkit/UserArea/assets/template2.gif differ
diff --git a/Toolkit/UserArea/assets/template3.gif b/Toolkit/UserArea/assets/template3.gif
new file mode 100755 (executable)
index 0000000..16e2107
Binary files /dev/null and b/Toolkit/UserArea/assets/template3.gif differ
diff --git a/Toolkit/UserArea/assets/template4.gif b/Toolkit/UserArea/assets/template4.gif
new file mode 100755 (executable)
index 0000000..32174dd
Binary files /dev/null and b/Toolkit/UserArea/assets/template4.gif differ
diff --git a/Toolkit/UserArea/assets/template5.gif b/Toolkit/UserArea/assets/template5.gif
new file mode 100755 (executable)
index 0000000..6c36b50
Binary files /dev/null and b/Toolkit/UserArea/assets/template5.gif differ
diff --git a/Toolkit/UserArea/assets/template6.gif b/Toolkit/UserArea/assets/template6.gif
new file mode 100644 (file)
index 0000000..28d140e
Binary files /dev/null and b/Toolkit/UserArea/assets/template6.gif differ
diff --git a/Toolkit/UserArea/config.ini b/Toolkit/UserArea/config.ini
new file mode 100644 (file)
index 0000000..3d81908
--- /dev/null
@@ -0,0 +1,3 @@
+[conf]
+applicationName = "Toolbox"
+lockMainNavPages = Off
diff --git a/Toolkit/UserArea/css/styles.css b/Toolkit/UserArea/css/styles.css
new file mode 100644 (file)
index 0000000..744466b
--- /dev/null
@@ -0,0 +1,202 @@
+#form-warning-top {
+       color: #FF0000;
+       font-size: 14px;
+       font-weight: bold;
+       margin-bottom: 0.5em;
+       margin-top: 1em;
+}
+.required, .req {
+       color: #FF0000;
+}
+.group {
+       display: -moz-inline-box;
+       width: 100%;
+}
+.group td {
+       width: 324px;
+}
+.requiredNote {
+       text-align: center;
+}
+#contact {
+       margin: 10px;
+}
+#contact table {
+       background-color: #FFFFFF;
+       border: 1px solid #EEEEEE;
+       border-collapse: collapse;
+}
+#contact td {
+       border: 1px solid #EEEEEE;
+       border-collapse: collapse;
+       color: #000000;
+       font-family: arial, helvetica, sans-serif;
+       padding: 3px;
+       font-size: 12px;
+}
+.labelcell {
+       background-color: transparent;
+       padding-right: 10px;
+       padding-top: 3px;
+       text-align: right;
+       white-space: nowrap;
+       width: 140px;
+}
+.fieldcell {
+       padding-left: 4px;
+       width: 320px;
+}
+.fieldcell .text {
+       width: 90%;
+}
+#contact table.group {
+       font-size: 10px;
+       border: none;
+       padding-top: 4px;
+}
+#contact table.group td {
+       border: none;
+}
+#contact .hdr {
+       background-color: #999999;
+       border: 1px solid #666666;
+       font-weight: bold;
+}
+.paging {
+       text-align: center;
+       background-color: #F6F6F6;
+       border-color: #E86a10;
+       border-color: #296DC0;
+       border-style: solid;
+       border-width: 1px 0;
+       margin: 1.0em 0;
+       padding: 8px 0;
+       text-align: center;
+       width: 100%;
+       font-size: 12px;
+
+}
+.paging b {
+       border: 1px solid #b22c2c;
+       border: 1px solid #E86A10;
+       background: #FFF;
+       padding: 5px 7px;
+       margin: 0 5px;
+}
+.paging a {
+       background: #FFF;
+       border: 1px solid #CCC;
+       padding: 5px 7px;
+       text-decoration: none;
+       font-family: helvetica, times;
+       color: #000;
+       margin: 0 5px;
+}
+.paging a:hover {
+       border: 1px solid #999;
+       border: 1px solid #b22c2c;
+       border: 1px solid #E86A10;
+}
+#dataGrid {
+       margin: 10px auto;
+       border: 1px solid #296DC0;
+       width: 100%;
+       border-collapse: collapse;
+}
+#dataGrid thead th {
+       background: #296DC0;
+       border: 1px solid #1b4880;
+       color: #000;
+       font-weight: normal;
+}
+#dataGrid th a {
+       font-weight: bolder;
+       color: #000;
+       text-decoration: none;
+}
+#dataGrid th a:hover {
+       color: #E86A10;
+       text-decoration: underline;
+}
+#dataGrid tr {
+       border: 1px solid #296DC0;
+       border-collapse: collapse;
+}
+#dataGrid tbody tr td {
+       padding: 5px;
+}
+#dataGrid .editLink, #dataGrid .delLink,
+#dataGrid .mailLink, #dataGrid .dateLink,
+#dataGrid .posLink {
+       text-align: center;
+}
+img.status {
+       border: none;
+}
+.even {
+       background-color: #D9D9D9;
+}
+#gridSorter {
+       margin: 0 auto;
+       padding: 10px;
+       text-align: center;
+       border: 1px solid #296DC0;
+}
+#gridSorter table {
+       border: none;
+}
+#gridSorter td {
+       border: none;
+}
+.fieldcell textarea {
+       width: 90%;
+       height: 70px;
+}
+
+/*
+ * Banner Reporting
+ */
+#bannerInfo, #reportResult {
+    margin: 10px;
+    border: 1px solid #bbb;
+    border-right: 1px solid #444;
+    border-bottom: 1px solid #444;
+    padding: 20px;
+    width: 400px;
+    background: #efefef;
+    font-size: 12px;
+}
+#bannerInfo h3, #reportResult h3 {
+    margin: 0;
+}
+#bannerInfo p {
+    margin-bottom: 0;
+}
+
+#bannerInfo table, #reportResult table,
+#bannerInfo th, #reportResult th,
+#bannerInfo tr, #reportResult tr,
+#bannerInfo td, #reportResult td {
+    margin: 5px;
+    padding: 5px;
+    border-collapse: collapse;
+    font-size: 12px;
+}
+#bannerInfo td {
+    padding: 5px;
+}
+label.tooltip {
+       background-image: url(http://app.gaslightmedia.com/assets/icons/information.png);
+       width: 16px;
+       height: 16px;
+       background-repeat: no-repeat;
+       background-position: left;
+       padding-left: 17px;
+}
+
+/**
+ * Prevent the slider from showing through the datepicker
+ */
+.ui-datepicker {
+       z-index: 100 !important;
+}
diff --git a/Toolkit/UserArea/fixPageNoContent.php b/Toolkit/UserArea/fixPageNoContent.php
new file mode 100644 (file)
index 0000000..8b59bad
--- /dev/null
@@ -0,0 +1,48 @@
+<?php
+require_once '../../setup.phtml';
+$dbh = Toolkit_Database::getInstance();
+$dbh->beginTransaction();
+try {
+    $checkSql = 
+        "SELECT id
+           FROM paragraphs
+          WHERE page = :page
+            AND pos = 1";
+    $checkStmt = $dbh->prepare($checkSql);
+    $addSql = "
+        INSERT INTO paragraphs
+        (active,page,pos)
+        VALUES
+        (true,:page,1)";
+    $addStmt = $dbh->prepare($addSql);
+    $sql = "
+      SELECT id
+        FROM pages
+    ORDER BY parent,pos";
+    $stmt = $dbh->query($sql);
+    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
+        $checkStmt->bindParam(
+            ':page',
+            $row['id'],
+            PDO::PARAM_INT
+        );
+        $checkStmt->execute();
+        if ($checkStmt->rowCount() == 0) {
+            // nothing set yet need to add one
+            $addStmt->bindParam(
+                ':page',
+                $row['id'],
+                PDO::PARAM_INT
+            );
+            $addStmt->execute();
+            echo '<p style="color:white;background-color:red;">
+                Adding paragraph! PageId:'.$row['id'].'</p>';
+        } else {
+            echo '<p style="color:white;background-color:green;">
+                Good Page PageId:'.$row['id'].'</p>';
+        }
+    }
+    $dbh->commit();
+} catch(PDOException $e) {
+    die($e->getMessage());
+}
diff --git a/Toolkit/UserArea/fixPagePos.php b/Toolkit/UserArea/fixPagePos.php
new file mode 100644 (file)
index 0000000..c414a6d
--- /dev/null
@@ -0,0 +1,70 @@
+<?php
+require_once '../../setup.phtml';
+$dbh = Toolkit_Database::getInstance();
+$dbh->beginTransaction();
+$pageData = array();
+try {
+    $sql = "
+    UPDATE pages 
+       SET pos = :pos 
+     WHERE id = :id";
+    $updatePagePos = $dbh->prepare($sql);
+    $sql = "
+    SELECT id,parent,pos
+      FROM pages
+     ORDER BY parent,pos";
+    $res = $dbh->query($sql);
+    while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
+        $pageData[$row['parent']][] = $row['id'];
+    }
+    echo '<p>fixing page positions</p>';
+    if (is_array($pageData)) {
+        $curParent = 0;
+        $pos = 1;
+        foreach ($pageData as $parent => $pages) {
+            if ($curParent != $parent) {
+                $curParent = $parent;
+                $pos = 1;
+            }
+            foreach ($pages as $pageId) {
+                $updatePagePos->bindParam(":pos", $pos, PDO::PARAM_INT);
+                $updatePagePos->bindParam(":id", $pageId, PDO::PARAM_INT);
+                $updatePagePos->execute();
+                ++$pos;
+            }
+        }
+    }
+    $sql = "
+    UPDATE paragraphs 
+       SET pos = :pos 
+     WHERE id = :id";
+    $updateParagraphPos = $dbh->prepare($sql);
+    $sql = "
+    SELECT id,page,pos
+      FROM paragraphs
+     ORDER BY page,pos";
+    $res = $dbh->query($sql);
+    while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
+        $paragraphData[$row['page']][] = $row['id'];
+    }
+    echo '<p>fixing paragraphs positions</p>';
+    if (is_array($paragraphData)) {
+        $curPage = 0;
+        $pos = 1;
+        foreach ($paragraphData as $page => $paragraphs) {
+            if ($curPage != $page) {
+                $curPage = $page;
+                $pos = 1;
+            }
+            foreach ($paragraphs as $paragraphId) {
+                $updateParagraphPos->bindParam(":pos", $pos, PDO::PARAM_INT);
+                $updateParagraphPos->bindParam(":id", $paragraphId, PDO::PARAM_INT);
+                $updateParagraphPos->execute();
+                ++$pos;
+            }
+        }
+    }
+} catch(PDOException $e) {
+    die($e->getMessage());
+}
+$dbh->commit();
diff --git a/Toolkit/UserArea/libjs/edit-page.js b/Toolkit/UserArea/libjs/edit-page.js
new file mode 100644 (file)
index 0000000..a63bc1f
--- /dev/null
@@ -0,0 +1,256 @@
+var EditPage =
+{
+    openSection: '#pageContent',
+    sectionHeaders: null,
+    sectionAttributes: null,
+
+    init: function()//  {{{
+    {
+        $('input[name=deletePage]:submit').click(EditPage.confirmPageDelete);
+        $('#MemberCategories').change(function() {
+            $('input[name=include_members]').attr('checked', 'checked');
+        });
+        $('#MemberRegions').change(function() {
+            $('input[name=include_members]').attr('checked', 'checked');
+        });
+        $('#CouponCategories').change(function() {
+            $('input[name=include_coupons]').attr('checked', 'checked');
+        });
+        EditPage.pageAttributes();
+        EditPage.memberAttributes();
+        EditPage.couponAttributes();
+        EditPage.headlineAttributes();
+
+        EditPage.sectionHeaders = $('tbody tr.hdr td');
+        EditPage.sectionAttributes = $('span.attributes');
+
+
+        //  If there was an error with validation, then
+        //  find the first error and open that section.
+        var $firstFormValidationError = $('div.req:first');
+        if ($firstFormValidationError.length > 0) {
+            //  Hide all sections first
+            $("tbody.section > tr:not(.hdr)").toggle();
+
+            //  Then open the target section
+            $firstFormValidationError
+                .parents("tbody.section")
+                .children("tr:not(.hdr)")
+                .toggle();
+            $firstFormValidationError
+                .parents("tbody.section")
+                .children('tr.hdr')
+                .children()
+                .toggleClass('open');
+        } else {
+            //  Initially hide all sections EXCEPT the first section
+            //  which has an id #pageContent
+            $("tbody.section > tr:not(.hdr)")
+                .not("tbody#pageContent > tr")
+                .toggle();
+        }
+
+        $("tbody.section tr.hdr").click(function() {
+            var $currId = $(this).parents('tbody').attr('id');
+            if ($currId == EditPage.openSection) {
+                return false;
+            }
+
+            //  Set this section to the current section open
+            EditPage.openSection = $currId
+
+            //  Remove the class open from all the section headers.
+            //  This will reset the arrow in the header back to closed (>)
+            EditPage.sectionHeaders.each(function() {
+                $(this).removeClass('open');
+            });
+
+            //  default shows all the section "quick at a glance" attributes
+            EditPage.sectionAttributes.show();
+            //  hide current sections "quick at a glance" attributes
+            $(this).find('.attributes').hide();
+
+            //  hide all the sections
+            $('tbody.section > tr:not(.hdr)').hide();
+            //  unhide the section that was clicked
+            $(this).siblings().toggle();
+            //  make this section open, w/ a down arrow (v)
+            $(this).children().toggleClass('open');
+        });
+
+        $("select[multiple]").asmSelect({
+            animate: true
+        });
+
+        if ($("#description").is("textarea")) {
+            //  Only try to replace the textarea if the
+            //  CKEditor is compatible w/ the browser.
+            if (CKEDITOR.env.isCompatible) {
+                CKEDITOR.replace('description',
+                    {
+                        toolbar : [
+                            ['Format', 'Font','FontSize','Bold','Italic'],
+                            ['Cut','Copy','PasteText','-','Undo','Redo'],
+                            '/',
+                            ['NumberedList','BulletedList','-','Outdent','Indent'],
+                            ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
+                            ['TextColor'],
+                            ['Link','Unlink', 'Anchor'],
+                            ['Find','Replace','-','RemoveFormat','Source']
+                        ],
+                        filebrowserImageBrowseUrl : '../Toolkit/CKImages/browser.php?folder=1',
+                        filebrowserImageUploadUrl : '../Toolkit/CKImages/controller.php?command=Upload',
+                        filebrowserImageWindowWidth : '760',
+                        filebrowserImageWindowHeight : '500'
+                    });
+            }
+        }
+        var pageId = $("input[name='id']").val();
+        console.log(pageId);
+        if (pageId == '') {
+            $.get("Staff-Page/", function(data){
+                $("#staffPick").html(data);
+            });
+        } else {
+            $.get("Staff-Page/" + pageId + "/", function(data){
+                $("#staffPick").html(data);
+            });
+        }
+
+    },//    }}}
+
+    confirmPageDelete: function(event)// {{{
+    {
+        if (!confirm("Are you sure you wish to delete this page and its paragraphs?\n\n" +
+                     "All sub pages along with existing page drafts will also be deleted!")) {
+            event.preventDefault();
+        }
+    },// }}}
+    createCategoryShortcutView: function(element, section, container)// {{{
+    {
+        var target = section.find('select[name="'+element+'[]"]');
+        if (target.length) {
+            container.append('<span class="'+element+'"></span>');
+            var $holder = container.find('.'+element),
+                $numSelected = target.find(':selected').length;
+            if ($numSelected) {
+                EditPage.updateText($holder, '<tt>['+$numSelected+']</tt>Categories');
+            }
+            target.change(function() {
+                var $numSelected = target.find(':selected').length;
+                EditPage.updateText($holder, '<tt>['+$numSelected+']</tt>Categories');
+            });
+        }
+    },//    }}}
+    createRegionShortcutView: function(element, section, container)//   {{{
+    {
+        var target = section.find('select[name="'+element+'[]"]');
+        if (target.length) {
+            container.append('<span class="'+element+'"></span>');
+            var $holder = container.find('.'+element),
+                $numSelected = target.find(':selected').length;
+            if ($numSelected) {
+                EditPage.updateText($holder, '<tt>['+$numSelected+']</tt>Regions');
+            }
+            target.change(function() {
+                var $numSelected = target.find(':selected').length;
+                EditPage.updateText($holder, '<tt>['+$numSelected+']</tt>Regions');
+            });
+        }
+    },//    }}}
+    createCheckboxShortcutView: function(element, section, container, text)//   {{{
+    {
+        var target = section.find('input[name='+element+']:checkbox');
+        if (target.length) {
+            container.append('<span class="'+element+'"></span>');
+            var $holder = container.find('.'+element),
+                $checked = target.is(':checked')
+                ? '<tt>[X]</tt>'
+                : '<tt>[ ]</tt>';
+            EditPage.updateText($holder, $checked + text);
+
+            target.change(function() {
+                var $checked = target.is(':checked')
+                    ? '<tt>[X]</tt>'
+                    : '<tt>[ ]</tt>';
+                EditPage.updateText($holder, $checked + text);
+            });
+        }
+    },//    }}}
+    createTextShortcutView: function(element, section, container)// {{{
+    {
+        var target = section.find('input[name='+element+']');
+        if (target.length) {
+            container.append('<span class="'+element+'"></span>');
+            var $holder = container.find('.'+element);
+            if (target.val() != '') {
+                EditPage.updateText($holder, '{' + target.val() + '}');
+            }
+            target.change(function() {
+                if ($(this).val() != '') {
+                    EditPage.updateText($holder, '{' + $(this).val() + '}');
+                } else {
+                    EditPage.updateText($holder, '');
+                }
+            });
+        }
+    },//    }}}
+
+    couponAttributes: function()//  {{{
+    {
+        var $section = $('#coupons');
+        $section.find('tr.hdr td')
+                .append('<span class="attributes"></span>');
+
+        $attributes = $section.find('tr.hdr .attributes');
+
+        EditPage.createCheckboxShortcutView('include_coupons', $section, $attributes, 'Display Coupons');
+        EditPage.createCategoryShortcutView('coupon_categories', $section, $attributes);
+    },//    }}}
+
+    headlineAttributes: function()//    {{{
+    {
+        var $section = $('#headlines');
+        $section.find('tr.hdr td')
+                .append('<span class="attributes"></span>');
+
+        $attributes = $section.find('tr.hdr .attributes');
+
+        EditPage.createCheckboxShortcutView('headline', $section, $attributes, 'Headline');
+    },//    }}}
+
+    pageAttributes: function()//    {{{
+    {
+        var $section = $('#attributes');
+        $section.find('tr.hdr td')
+                .append('<span class="attributes"></span>');
+
+        $attributes = $section.find('tr.hdr .attributes');
+
+        EditPage.createTextShortcutView('keyword', $section, $attributes);
+        EditPage.createTextShortcutView('short_url', $section, $attributes);
+        EditPage.createCheckboxShortcutView('paragraph_links', $section, $attributes, 'Links');
+    },//    }}}
+
+    memberAttributes: function()//  {{{
+    {
+        var $section = $('#members');
+        $section.find('tr.hdr td')
+                .append('<span class="attributes"></span>');
+
+        $attributes = $section.find('tr.hdr .attributes');
+
+        EditPage.createCheckboxShortcutView('include_members', $section, $attributes, 'Display Members');
+        EditPage.createCategoryShortcutView('member_categories', $section, $attributes);
+        EditPage.createRegionShortcutView('member_regions', $section, $attributes);
+        EditPage.createCheckboxShortcutView('include_member_map', $section, $attributes, 'Map');
+        EditPage.createCheckboxShortcutView('search_form', $section, $attributes, 'Search');
+    },//    }}}
+
+    updateText: function(holder, content)// {{{
+    {
+        holder.html(content);
+    }// }}}
+};
+
+$(document).ready(EditPage.init);
diff --git a/Toolkit/UserArea/libjs/edit-paragraph.js b/Toolkit/UserArea/libjs/edit-paragraph.js
new file mode 100644 (file)
index 0000000..f80a4ff
--- /dev/null
@@ -0,0 +1,152 @@
+var EditParagraph =
+{
+    init: function()// {{{
+    {
+        $('.files').sortable({
+            placeholder: 'ui-state-highlight'
+        });
+
+        $('input[name="deleteParagraph"]').click(EditParagraph.confirmParagraphDelete);
+
+        //  Bind click events to the remove buttons for uploaded files
+        //  everytime a button is clicked, an entire li element is removed
+        //  so we can get rid of all the info stored in hidden fields
+        //  about the file (bytes, filename, etc...).
+        $('.remove').live('click', function(event) {
+            event.preventDefault();
+            $(this).parent('li').remove();
+        });
+
+        $('#filename').after('<span id="upload_notification" style="display: none;">Uploading</span>');
+        $('#filename').after('<span id="success_notification" style="display: none;"><span></span> Successfully uploaded</span>');
+        var $uploadNotification = $('#upload_notification');
+
+        $("tbody.section tr:not(.hdr)").toggle();
+        var $hdr = $('tbody.section tr.hdr');
+
+        $hdr.click(function() {
+            $(this).siblings()
+                   .toggle();
+            $(this).children()
+                   .toggleClass('open');
+        });
+
+        $("div.req").each(function() {
+            $(this).parents("tbody.section")
+                   .children("tr:not(.hdr)")
+                   .toggle();
+            $(this).parents("tbody.section")
+                   .children("tr.hdr")
+                   .children()
+                   .toggleClass('open');
+        });
+
+        if ($("#description").is("textarea")) {
+            //  Only try to replace the textarea if the
+            //  CKEditor is compatible w/ the browser.
+            if (CKEDITOR.env.isCompatible) {
+                CKEDITOR.replace('description',
+                    {
+                        toolbar : [
+                            ['Format', 'Font','FontSize','Bold','Italic'],
+                            ['Cut','Copy','PasteText','-','Undo','Redo'],
+                            '/',
+                            ['NumberedList','BulletedList','-','Outdent','Indent'],
+                            ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
+                            ['TextColor'],
+                            ['Link','Unlink', 'Anchor'],
+                            ['Find','Replace','-','RemoveFormat','Source']
+                        ]
+                    });
+            }
+        }
+    },// }}}
+
+    cleanName: function(filename)// {{{
+    {
+        var $alphaNumeric = filename.replace(/[^A-Za-z0-9]/g, '');
+
+        return $alphaNumeric;
+    },// }}}
+    confirmParagraphDelete: function(event)// {{{
+    {
+        if (!confirm("Are you sure you wish to delete this paragraph and its files?")) {
+            event.preventDefault();
+        }
+    },// }}}
+
+    getExtensionImage: function(ext)// {{{
+    {
+        var img;
+        switch (ext) {
+        case 'mp3' :
+            img = 'mp3.gif';
+            break;
+
+        case 'avi' :
+            img = 'avi.gif';
+            break;
+
+        case 'html' :
+            img = 'html.gif';
+            break;
+
+        case 'mov' :
+            img = 'mov.gif'
+            break;
+
+        case 'wmv' :
+            img = 'wmv.gif';
+            break;
+
+        case 'ppt' :
+            img = 'ppt.gif';
+            break;
+
+        case 'zip' :
+            img = 'zip.png';
+            break;
+
+        case 'rar' :
+        case 'tar' :
+            img = 'rar.gif';
+            break;
+
+        case 'txt' :
+            img = 'txt.png';
+            break;
+
+        case 'xlsx' :
+        case 'xls' :
+            img = 'xls.gif';
+            break;
+
+        case 'pdf' :
+            img = 'pdf.png';
+            break;
+
+        case 'doc' :
+        case 'docx' :
+            img = 'doc.gif';
+            break;
+
+        case 'png' : // image does not exist yet.
+        case 'jpeg' :
+        case 'jpg' :
+            img = 'jpg.gif';
+            break;
+
+        case 'gif' :
+            img = 'gif.gif';
+            break;
+
+        default :
+            img = 'download.gif';
+            break;
+        }
+
+        return img;
+    }// }}}
+};
+
+$(document).ready(EditParagraph.init);
diff --git a/Toolkit/UserArea/libjs/editUser.js b/Toolkit/UserArea/libjs/editUser.js
new file mode 100644 (file)
index 0000000..45b606c
--- /dev/null
@@ -0,0 +1,6 @@
+$(function (){
+    // get userId
+    var userId = $("#userId").val();
+    $("#appData").load("userArea.php?ac=getUserApps", {'userId':userId}, function() {
+    });
+});
diff --git a/Toolkit/UserArea/libjs/jquery.columnview.js b/Toolkit/UserArea/libjs/jquery.columnview.js
new file mode 100755 (executable)
index 0000000..53a3834
--- /dev/null
@@ -0,0 +1,267 @@
+/**
+ * jquery.columnview-1.2.js
+ *
+ * Created by Chris Yates on 2009-02-26.
+ * http://christianyates.com
+ * Copyright 2009 Christian Yates and ASU Mars Space Flight Facility. All rights reserved.
+ *
+ * Supported under jQuery 1.2.x or later
+ * Keyboard navigation supported under 1.3.x or later
+ * 
+ * Dual licensed under MIT and GPL.
+ */
+
+(function($){
+  $.fn.columnview = function(options){
+
+    var settings = $.extend({}, $.fn.columnview.defaults, options);
+        
+    // Add stylesheet, but only once
+    if(!$('.containerobj').get(0)){
+      $('head').prepend('\
+      <style type="text/css" media="screen">\
+        .containerobj {\
+          border: 1px solid #ccc;\
+          height:5em;\
+          overflow-x:auto;\
+          overflow-y:hidden;\
+          white-space:nowrap;\
+          position:relative;\
+        }\
+        .containerobj div {\
+          height:100%;\
+          overflow-y:scroll;\
+          overflow-x:hidden;\
+          position:absolute;\
+        }\
+        .containerobj a {\
+          display:block;\
+          white-space:nowrap;\
+          clear:both;\
+          padding-right:15px;\
+          overflow:hidden;\
+          text-decoration:none;\
+        }\
+        .containerobj a:focus {\
+          outline:none;\
+        }\
+        .containerobj a canvas {\
+        }\
+        .containerobj .feature {\
+          min-width:200px;\
+          overflow-y:auto;\
+        }\
+        .containerobj .feature a {\
+          white-space:normal;\
+        }\
+        .containerobj .hasChildMenu {\
+        }\
+        .containerobj .active {\
+          background-color:#3671cf;\
+          color:#fff;\
+        }\
+        .containerobj .inpath {\
+          background-color:#d0d0d0;\
+          color:#000;\
+        }\
+        .containerobj .hasChildMenu .widget {\
+          color:black;\
+          position:absolute;\
+          right:0;\
+          text-decoration:none;\
+          font-size:0.7em;\
+        }\
+      </style>');
+    }
+
+    // Hide original list
+    $(this).hide();
+    // Reset the original list's id
+    var origid = $(this).attr('id');
+    if (origid) {
+      $(this).attr('id', origid + "-processed");
+    }
+
+    // Create new top container from top-level LI tags
+    var top = $(this).children('li');
+    var container = $('<div/>').addClass('containerobj').attr('id', origid).insertAfter(this);
+    var topdiv = $('<div class="top"></div>').appendTo(container);
+    // Set column width
+    if (settings.fixedwidth || $.browser.msie) { // MSIE doesn't support auto-width
+      var width = typeof settings.fixedwidth == "string" ? settings.fixedwidth : '200px';
+      $('.top').width(width);
+    }
+    $.each(top,function(i,item){
+      var topitem = $(':eq(0)',item).clone(true).wrapInner("<span/>").data('sub',$(item).children('ul')).appendTo(topdiv);
+      if (settings.fixedwidth || $.browser.msie)
+      $(topitem).css({'text-overflow':'ellipsis', '-o-text-overflow':'ellipsis','-ms-text-overflow':'ellipsis'});
+      if($(topitem).data('sub').length) {
+        $(topitem).addClass('hasChildMenu');
+        addWidget(container, topitem);
+      }
+    });
+
+    // Firefox doesn't repeat keydown events when the key is held, so we use
+    // keypress with FF/Gecko/Mozilla to enable continuous keyboard scrolling.
+    var key_event = $.browser.mozilla ? 'keypress' : 'keydown';
+    
+    // Event handling functions
+    $(container).bind("click " + key_event, function(event){
+      if ($(event.target).is("a,span")) {
+        if ($(event.target).is("span")){
+          var self = $(event.target).parent();
+        }
+        else {
+          var self = event.target;          
+        }
+        if (!settings.multi) {
+          delete event.shiftKey;
+          delete event.metaKey;
+        }
+        self.focus();
+        var container = $(self).parents('.containerobj');
+        // Handle clicks
+        if (event.type == "click"){
+          var level = $('div',container).index($(self).parents('div'));
+          var isleafnode = false;
+          // Remove blocks to the right in the tree, and 'deactivate' other
+          // links within the same level, if metakey is not being used
+          $('div:gt('+level+')',container).remove();
+          if (!event.metaKey && !event.shiftKey) {
+            $('div:eq('+level+') a',container).removeClass('active').removeClass('inpath');
+            $('.active',container).addClass('inpath');
+            $('div:lt('+level+') a',container).removeClass('active');
+          }
+          // Select intermediate items when shift clicking
+          // Sorry, only works with jQuery 1.4 due to changes in the .index() function
+          if (event.shiftKey) {
+            var first = $('a.active:first', $(self).parent()).index();
+            var cur = $(self).index();
+            var range = [first,cur].sort(function(a,b){return a - b;});
+            $('div:eq('+level+') a', container).slice(range[0], range[1]).addClass('active');
+          }
+          $(self).addClass('active');
+          if ($(self).data('sub').children('li').length && !event.metaKey) {
+            // Menu has children, so add another submenu
+            var w = false;
+            if (settings.fixedwidth || $.browser.msie)
+            w = typeof settings.fixedwidth == "string" ? settings.fixedwidth : '200px';
+            submenu(container,self,w);
+          }
+          else if (!event.metaKey && !event.shiftKey) {
+            // No children, show title instead (if it exists, or a link)
+            isleafnode = true;
+            var previewcontainer = $('<div/>').addClass('feature').appendTo(container);
+            // Fire preview handler function
+            if ($.isFunction(settings.preview)) {
+              // We're passing the element back to the callback
+              var preview = settings.preview($(self));
+            }
+            // If preview is specifically disabled, do nothing with the previewbox
+            else if (!settings.preview) {
+            }
+            // If no preview function is specificied, use a default behavior
+            else {
+              var title = $('<a/>').attr({href:$(self).attr('href')}).text($(self).attr('title') ? $(self).attr('title') : $(self).text());
+              $(previewcontainer).html(title);
+            }
+            // Set the width
+            var remainingspace = 0; 
+            $.each($(container).children('div').slice(0,-1),function(i,item){
+              remainingspace += $(item).width();
+            });
+            var fillwidth = $(container).width() - remainingspace;
+            $(previewcontainer).css({'top':0,'left':remainingspace}).width(fillwidth).show();  
+          }
+          // Fire onchange handler function, but only if multi-select is off.
+          // FIXME Need to deal multiple selections.
+          if ($.isFunction(settings.onchange) && !settings.multi) {
+            // We're passing the element back to the callback
+            var onchange = settings.onchange($(self), isleafnode);
+          }
+        }
+        // Handle Keyboard navigation
+        if(event.type == key_event){
+          switch(event.keyCode){
+            case(37): //left
+              $(self).parent().prev().children('.inpath').focus().trigger("click");
+              break;
+            case(38): //up
+              $(self).prev().focus().trigger("click");
+              break;
+            case(39): //right
+              if($(self).hasClass('hasChildMenu')){
+                $(self).parent().next().children('a:first').focus().trigger("click");
+              }
+              break;
+            case(40): //down
+              $(self).next().focus().trigger("click");
+              break;
+            case(13): //enter
+              $(self).trigger("dblclick");
+              break;
+          }
+        }
+        event.preventDefault();
+      }
+    });
+
+  };
+  
+  $.fn.columnview.defaults = {
+    multi: false,     // Allow multiple selections
+    preview: true,    // Handler for preview pane
+    fixedwidth: false,// Use fixed width columns
+    onchange: false   // Handler for selection change
+  };
+
+  // Generate deeper level menus
+  function submenu(container,item,width){
+    var leftPos = 0;
+    $.each($(container).children('div'),function(i,mydiv){
+      leftPos += $(mydiv).width();
+    });
+    var submenu = $('<div/>').css({'top':0,'left':leftPos}).appendTo(container);
+    // Set column width
+    if (width)
+    $(submenu).width(width);
+    var subitems = $(item).data('sub').children('li');
+    $.each(subitems,function(i,subitem){
+      var subsubitem = $(':eq(0)',subitem).clone(true).wrapInner("<span/>").data('sub',$(subitem).children('ul')).appendTo(submenu);
+      if (width)
+      $(subsubitem).css({'text-overflow':'ellipsis', '-o-text-overflow':'ellipsis','-ms-text-overflow':'ellipsis'});
+      if($(subsubitem).data('sub').length) {
+        $(subsubitem).addClass('hasChildMenu');
+        addWidget(container, subsubitem);
+      }
+    });
+  }
+
+  // Uses canvas, if available, to draw a triangle to denote that item is a parent
+  function addWidget(container, item, color){
+    var triheight = $(item).height();
+    var canvas = $("<canvas></canvas>").attr({height:triheight,width:10}).addClass('widget').appendTo(item);    if(!color){ color = $(canvas).css('color'); }
+    canvas = $(canvas).get(0);
+    if(canvas.getContext){
+      var context = canvas.getContext('2d');
+      context.fillStyle = color;
+      context.beginPath();
+      context.moveTo(3,(triheight/2 - 3));
+      context.lineTo(10,(triheight/2));
+      context.lineTo(3,(triheight/2 + 3));
+      context.fill();
+    } else {
+      /**
+       * Canvas not supported - put something in there anyway that can be
+       * suppressed later if desired. We're using a decimal character here
+       * representing a "black right-pointing pointer" in Windows since IE
+       * is the likely case that doesn't support canvas.
+       */
+      $("<span>&#9658;</span>").addClass('widget').css({'height':triheight,'width':10}).prependTo(item);
+    }
+    $(container).find('.widget').bind('click', function(event){
+      event.preventDefault();
+    });
+
+  }
+})(jQuery);
\ No newline at end of file
diff --git a/Toolkit/UserArea/libjs/pagesTree.js b/Toolkit/UserArea/libjs/pagesTree.js
new file mode 100644 (file)
index 0000000..318f14e
--- /dev/null
@@ -0,0 +1,242 @@
+var PagesTree =
+{
+       init: function()
+       {
+               PagesTree.updateMoveArrowVisibility();
+               $('.admin_nav')
+                       .append('<li><a id="expand_all" href="#">Expand All</a></li>')
+            .append('<li><a id="collapse_all" href="#">Collapse All</a></li>')
+            .append('<li><a id="show_pos" href="#">Show Positions</a></li>')
+            .append('<li><a id="hide_pos" href="#">Hide Positions</a></li>')
+            ;
+
+               var $myTree = $('#tree');
+
+               if ($myTree.children('ul').size() > 0) {
+                       $myTree.tree({
+                               callback : {
+                                       onsearch : function (NODES, TREE_OBJ) {
+                                               TREE_OBJ.container.find('strong.search').removeClass('search');
+                                               NODES.addClass('search');
+
+                                               if (NODES.length == 0) {
+                                                       alert('No matches found - Please refine your search.');
+                                               }
+                                       }
+                               },
+                               plugins : {
+                                       cookie : {
+                                               prefix : "jstree_toolbox_",
+                                               types : {
+                                                       selected : false
+                                               }
+                                       }
+                               }
+                       });
+            $('#show_pos').click(function(event) {
+                               event.preventDefault();
+                $('select').show();
+            });
+            $('#hide_pos').click(function(event) {
+                               event.preventDefault();
+                $('select').hide();
+            });
+                       $('#expand_all').click(function(event) {
+                               event.preventDefault();
+                               $.tree.focused().open_all();
+                       });
+                       $('#collapse_all').click(function(event) {
+                               event.preventDefault();
+                               $.tree.focused().close_all();
+                       });
+
+                       $("#search_form").submit(function(event) {
+                               var $search = $("#q").val().toUpperCase();
+                               event.preventDefault();
+                               jQuery.expr[':'].Contains = function(a, i, m) {
+                                       return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
+                               };
+                               $.tree.focused().search($search, "contains('"+$search+"'),strong:Contains");
+                       });
+
+                       $('a.pagePreview').click(function(event) {
+                               var newWindow = window.open($(this).attr('href'));
+                               newWindow.focus();
+                               return false;
+                       });
+
+                       $('img.moveDown').click(function() {
+                               var $li = $(this).closest('li'),
+                                       $sibling = $li.next();
+                               if ($sibling.length == 1) {
+                                       var $id = $li.attr('id');
+                                       $li.detach();
+                                       $li.insertAfter($sibling);
+                                       PagesTree.updateMoveArrowVisibility();
+                                       $.ajax({
+                                               url : '../user-page-move/'+$id+'/down/',
+                        cache: false,
+                                               async: false,
+                                               success: function(html) {
+                                                       if (html == 0) {
+                                                               PagesTree.moveBack($li, $sibling);
+                                                       } else if ($sibling.hasClass('last')) {
+                                                               $sibling.removeClass('last');
+                                                               $li.addClass('last');
+                                                       }
+                                               },
+                                               error: function() {
+                                                       PagesTree.moveBack($li, $sibling);
+                                               }
+                                       });
+                               }
+                       });
+
+                       $('img.moveUp').click(function() {
+                               var $li = $(this).closest('li'),
+                                       $sibling = $li.prev();
+                               if ($sibling.length == 1) {
+                                       var $id = $li.attr('id');
+                                       $li.detach();
+                                       $li.insertBefore($sibling);
+                                       PagesTree.updateMoveArrowVisibility();
+                                       $.ajax({
+                                               url : '../user-page-move/'+$id+'/up/',
+                        cache: false,
+                                               async: false,
+                                               success: function(html) {
+                                                       if (html == 0) {
+                                                               PagesTree.moveBack($li, $sibling);
+                                                       } else if ($li.hasClass('last')) {
+                                                               $li.removeClass('last');
+                                                               $sibling.addClass('last');
+                                                       }
+                                               },
+                                               error: function() {
+                                                       PagesTree.moveBack($li, $sibling);
+                                               }
+                                       });
+                               }
+                       });
+
+                       $('.active-ball').click(function(event) {
+                               event.preventDefault();
+                               var id = $(this).attr('rel'),
+                                       _this = $(this);
+                    $.get('../user-change-state/'+id+'/?t=' + event.timeStamp, function(data) {
+                                       if (data) {
+                                               _this.children().toggle();
+                                               var newTitle = _this.attr('title') == 'Display'
+                                                       ? "Don't Display"
+                                                       : 'Display';
+                                               _this.attr('title', newTitle);
+                                       }
+                               });
+                       });
+            $('.mobile-active-ball').click(function(event) {
+                               event.preventDefault();
+                               var id = $(this).attr('rel'),
+                                       _this = $(this);
+                               $.get('../user-change-state-mobile/'+id+'/?t=' + event.timeStamp, function(data) {
+                                       if (data) {
+                                               _this.children().toggle();
+                                               var newTitle = _this.attr('title') == 'Display'
+                                                       ? "Don't Display"
+                                                       : 'Display';
+                                               _this.attr('title', newTitle);
+                                       }
+                               });
+                       });
+               }
+        $('.closed').hover(function(){
+            $(this).css('background', 'lightgrey');
+            //$(this).children('.right-element').show();
+        },function(){
+            $(this).css('background', 'none');
+            //$(this).children('.right-element').hide();
+        });
+        $('.leaf').hover(function(){
+            $(this).css('background', 'lightgrey');
+            //$(this).children('.right-element').show();
+        },function(){
+            $(this).css('background', 'none');
+            //$(this).children('.right-element').hide();
+        });
+        $('li.open').each(function(){
+            var count = $(this).children('ul').children('li').size();
+            PagesTree.loadSelectOptions(
+                $(this).children('ul').children('li').children('div.right-element'),
+                count
+            );
+        });
+        $('li.closed').each(function(){
+            var count = $(this).children('ul').children('li').size();
+            PagesTree.loadSelectOptions(
+                $(this).children('ul').children('li').children('div.right-element'),
+                count
+            );
+        });
+        $('select.pos-select').each(function(){
+            $(this).change(function(){
+                var id = $(this).attr('name');
+                var oldpos = $(this).attr('rel');
+                var newpos = $(this).attr('value');
+                window.location.href = '../user-page-move-sel/' + id + '/' + oldpos + '/' + newpos + '/';
+            });
+        });
+        $('ul.ltr').each(function(){
+            var count = $(this).children('li').size();
+            PagesTree.loadSelectOptions(
+                $(this).children('li').children('div.right-element'),
+                count
+            );
+        });
+       },
+
+    loadSelectOptions: function(ul, count)
+    {
+        ul.each(function(){
+            var selCount = $(this).children('select').attr('rel');
+            if ($(this).children('select').hasClass('parent-level-sel')) {
+                var begin = 2;
+            } else {
+                var begin = 1;
+            }
+            for (i = begin; i <= count; ++i) {
+                var html = '<option value="'+i+'"';
+                if (selCount == i) {
+                    html += ' selected="selected"';
+                }
+                html += '>'+i+'</option>';
+                $(this).children('select').append(html);
+            }
+        });
+    },
+
+       moveBack: function($li, $sibling)
+       {
+               alert('There was an error moving your page');
+               $li.detach();
+               $li.insertBefore($sibling);
+               PagesTree.updateMoveArrowVisibility();
+       },
+
+       updateMoveArrowVisibility: function()
+       {
+               $('img.moveUp, img.moveDown').show().removeClass('tOff');
+
+               var $tree = $('#tree');
+               $tree.find('ul').each(function() {
+                       var $firstUpArrow = $(this).find('img.moveUp:first'),
+                               $lis = $(this).children().last();
+                       $firstUpArrow.addClass('tOff');
+
+                       $lis.each(function() {
+                               var $lastDownArrow = $(this).find('.right-element:first img.moveDown:last');
+                               $lastDownArrow.addClass('tOff');
+                       });
+               });
+       }
+};
+
+$(document).ready(PagesTree.init);
diff --git a/Toolkit/UserArea/libjs/paragraph-tree.js b/Toolkit/UserArea/libjs/paragraph-tree.js
new file mode 100644 (file)
index 0000000..3c98402
--- /dev/null
@@ -0,0 +1,143 @@
+var ParagraphTree =
+{
+    init: function()
+    {
+        ParagraphTree.updateMoveArrowVisibility();
+        var $myTree = $('#tree');
+        if ($myTree.children('ul').size() > 0) {
+            $myTree.tree();
+        }
+
+        $('img.moveDown').click(function() {
+            var $li = $(this).closest('li'),
+                $sibling = $li.next();
+            if ($sibling.length == 1) {
+                var $id = $li.attr('id');
+                $li.detach();
+                $li.insertAfter($sibling);
+                ParagraphTree.updateMoveArrowVisibility();
+                $.ajax({
+                    url : '../user-paragraph-move/'+$id+'/down/',
+                    async: false,
+                    cache: false,
+                    success: function(html) {
+                        if (html == 0) {
+                            ParagraphTree.moveBack($li, $sibling);
+                        } else if ($sibling.hasClass('last')) {
+                            $sibling.removeClass('last');
+                            $li.addClass('last');
+                        }
+                    },
+                    error: function() {
+                        ParagraphTree.moveBack($li, $sibling);
+                    }
+                });
+            }
+        });
+
+        $('img.moveUp').click(function() {
+            var $li = $(this).closest('li'),
+                $sibling = $li.prev();
+            if ($sibling.length == 1) {
+                var $id = $li.attr('id');
+                $li.detach();
+                $li.insertBefore($sibling);
+                if ($li.hasClass('last')) {
+                    $li.removeClass('last');
+                    $sibling.addClass('last');
+                }
+                ParagraphTree.updateMoveArrowVisibility();
+                $.ajax({
+                    url : '../user-paragraph-move/'+$id+'/up/',
+                    async: false,
+                    cache: false,
+                    success: function(html) {
+                        if (html == 0) {
+                            ParagraphTree.moveBack($li, $sibling);
+                        } else if ($li.hasClass('last')) {
+                            $li.removeClass('last');
+                            $sibling.addClass('last');
+                        }
+                    },
+                    error: function() {
+                        ParagraphTree.moveBack($li, $sibling);
+                    }
+                });
+            }
+        });
+
+        $('.active-ball').click(function(event) {
+            event.preventDefault();
+            var id = $(this).attr('rel');
+            var _this = $(this);
+            $.get('../user-paragraph-change-state/'+id+'/?t=' + event.timeStamp, function(data) {
+                if (data) {
+                    _this.children().toggle();
+                    var newTitle = _this.attr('title') == 'Display'
+                        ? "Don't Display"
+                        : 'Display';
+                    _this.attr('title', newTitle);
+                }
+            });
+        });
+        $('ul.ltr').each(function(){
+            var count = $(this).children('li').size();
+            ParagraphTree.loadSelectOptions(
+                $(this).children('li').children('div.right-element'),
+                count
+            );
+        });
+        $('select.pos-select').each(function(){
+            $(this).change(function(){
+                var id = $(this).attr('name');
+                var oldpos = $(this).attr('rel');
+                var newpos = $(this).attr('value');
+                window.location.href = '../user-paragraph-move-sel/' + id + '/' + oldpos + '/' + newpos + '/';
+            });
+        });
+    },
+
+    loadSelectOptions: function(ul, count)
+    {
+        ul.each(function(){
+            var selCount = $(this).children('select').attr('rel');
+            var begin = 1;
+            for (i = begin; i <= count; ++i) {
+                var realNum = i + 1;
+                var html = '<option value="'+realNum+'"';
+                if (selCount == realNum) {
+                    html += ' selected="selected"';
+                }
+                html += '>'+ i +'</option>';
+                $(this).children('select').append(html);
+            }
+        });
+    },
+
+    moveBack: function($li, $sibling)
+    {
+        alert('There was an error moving your page');
+        $li.detach();
+        $li.insertBefore($sibling);
+        ParagraphTree.updateMoveArrowVisibility();
+    },
+
+    updateMoveArrowVisibility: function()
+    {
+        $('img.moveUp, img.moveDown').show().removeClass('tOff');
+
+        var $tree = $('#tree');
+        $tree.find('ul').each(function() {
+            var $firstUpArrow = $(this).find('img.moveUp:first');
+            $firstUpArrow.addClass('tOff');
+
+            var $lis = $(this).children().last();
+            $lis.each(function() {
+                var $lastDownArrow = $(this).find('.right-element:first img.moveDown:last');
+                $lastDownArrow.addClass('tOff');
+            });
+        });
+    }
+};
+
+$(document).ready(ParagraphTree.init);
diff --git a/Toolkit/UserArea/moveBySelect.php b/Toolkit/UserArea/moveBySelect.php
new file mode 100644 (file)
index 0000000..31db9f9
--- /dev/null
@@ -0,0 +1,126 @@
+<?php
+require_once '../../setup.phtml';
+$dbh = Toolkit_Database::getInstance();
+//echo '<pre>'.print_r($_REQUEST, true).'</pre>';
+$someNewPos = 999;
+try {
+    // start transaction
+    $dbh->beginTransaction();
+    $sql = "
+    SELECT parent
+      FROM pages
+     WHERE id = :id";
+    $stmt = $dbh->prepare($sql);
+    $stmt->bindParam(
+        ":id",
+        $_REQUEST['id'],
+        PDO::PARAM_INT
+    );
+    $stmt->execute();
+    $parent = $stmt->fetchColumn();
+    //var_dump($parent);
+    $updateSql = "
+    UPDATE pages
+       SET pos = :pos
+     WHERE id = :id";
+    $updateStmt = $dbh->prepare($updateSql);
+    $moveDownSql = "
+      SELECT id
+        FROM pages
+       WHERE parent = :parent
+         AND pos >= :oldpos
+         AND pos <= :newpos
+    ORDER BY pos";
+    $moveDownStmt = $dbh->prepare($moveDownSql);
+    $moveUpSql = "
+    UPDATE pages
+       SET pos = pos + 1
+     WHERE parent = :parent
+       AND pos BETWEEN :newpos AND :oldpos";
+    $moveUpStmt = $dbh->prepare($moveUpSql);
+
+    $updateStmt->bindParam(
+        ':pos',
+        $someNewPos,
+        PDO::PARAM_INT
+    );
+    $updateStmt->bindParam(
+        ':id',
+        $_REQUEST['id'],
+        PDO::PARAM_INT
+    );
+    $updateStmt->execute();
+    // going to a higher pos (moving down)
+    if ($_REQUEST['newpos'] > $_REQUEST['oldpos']) {
+        //echo '<pre>'.print_r($_REQUEST, true).'</pre>';
+        //var_dump($parent);
+        $moveDownStmt->bindParam(
+            ':parent',
+            $parent,
+            PDO::PARAM_INT
+        );
+        $moveDownStmt->bindParam(
+            ':oldpos',
+            $_REQUEST['oldpos'],
+            PDO::PARAM_INT
+        );
+        $moveDownStmt->bindParam(
+            ':newpos',
+            $_REQUEST['newpos'],
+            PDO::PARAM_INT
+        );
+        $moveDownStmt->execute();
+        $pos = $_REQUEST['oldpos'];
+        while ($row = $moveDownStmt->fetch(PDO::FETCH_ASSOC)) {
+            //var_dump($row);
+            $updateStmt->bindParam(
+                ':pos',
+                $pos,
+                PDO::PARAM_INT
+            );
+            $updateStmt->bindParam(
+                ':id',
+                $row['id']
+            );
+            $updateStmt->execute();
+            ++$pos;
+        }
+        // moving up
+    } else {
+        $moveUpStmt->bindParam(
+            ':parent',
+            $parent,
+            PDO::PARAM_INT
+        );
+        $moveUpStmt->bindParam(
+            ':oldpos',
+            $_REQUEST['oldpos'],
+            PDO::PARAM_INT
+        );
+        $moveUpStmt->bindParam(
+            ':newpos',
+            $_REQUEST['newpos'],
+            PDO::PARAM_INT
+        );
+        $moveUpStmt->execute();
+    }
+
+    $updateStmt->bindParam(
+        ':pos',
+        $_REQUEST['newpos'],
+        PDO::PARAM_INT
+    );
+    $updateStmt->bindParam(
+        ':id',
+        $_REQUEST['id'],
+        PDO::PARAM_INT
+    );
+    $updateStmt->execute();
+    $dbh->commit();
+} catch (PDOException $e) {
+       $dbh->rollback();
+    Toolkit_Logger::logException('DB Error', $e);
+}
+$cache = new Cache_Lite($GLOBALS['cacheOptions']);
+$cache->clean('Toolbox');
+header('Location: '.MEDIA_BASE_URL.'userArea/toolbox.php?showpos=1');
diff --git a/Toolkit/UserArea/moveBySelectPara.php b/Toolkit/UserArea/moveBySelectPara.php
new file mode 100644 (file)
index 0000000..fd276b8
--- /dev/null
@@ -0,0 +1,119 @@
+<?php
+require_once '../../setup.phtml';
+$dbh = Toolkit_Database::getInstance();
+$someNewPos = 999;
+try {
+    $dbh->beginTransaction();
+    $sql = "
+    SELECT page
+      FROM paragraphs
+     WHERE id = :id";
+    $stmt = $dbh->prepare($sql);
+    $stmt->bindParam(
+        ":id",
+        $_REQUEST['id'],
+        PDO::PARAM_INT
+    );
+    $stmt->execute();
+    $page = $stmt->fetchColumn();
+    $updateSql = "
+    UPDATE paragraphs
+       SET pos = :pos
+     WHERE id = :id";
+    $updateStmt = $dbh->prepare($updateSql);
+    $moveDownSql = "
+      SELECT id
+        FROM paragraphs
+       WHERE page = :page
+         AND pos >= :oldpos
+         AND pos <= :newpos
+    ORDER BY pos";
+    $moveDownStmt = $dbh->prepare($moveDownSql);
+    $moveUpSql = "
+    UPDATE paragraphs
+       SET pos = pos + 1
+     WHERE page = :page
+       AND pos BETWEEN :newpos AND :oldpos";
+    $moveUpStmt = $dbh->prepare($moveUpSql);
+
+    $updateStmt->bindParam(
+        ':pos',
+        $someNewPos,
+        PDO::PARAM_INT
+    );
+    $updateStmt->bindParam(
+        ':id',
+        $_REQUEST['id'],
+        PDO::PARAM_INT
+    );
+    $updateStmt->execute();
+    if ($_REQUEST['newpos'] > $_REQUEST['oldpos']) {
+        $moveDownStmt->bindParam(
+            ':page',
+            $page,
+            PDO::PARAM_INT
+        );
+        $moveDownStmt->bindParam(
+            ':oldpos',
+            $_REQUEST['oldpos'],
+            PDO::PARAM_INT
+        );
+        $moveDownStmt->bindParam(
+            ':newpos',
+            $_REQUEST['newpos'],
+            PDO::PARAM_INT
+        );
+        $moveDownStmt->execute();
+        $pos = $_REQUEST['oldpos'];
+        while ($row = $moveDownStmt->fetch(PDO::FETCH_ASSOC)) {
+            //var_dump($row);
+            $updateStmt->bindParam(
+                ':pos',
+                $pos,
+                PDO::PARAM_INT
+            );
+            $updateStmt->bindParam(
+                ':id',
+                $row['id']
+            );
+            $updateStmt->execute();
+            ++$pos;
+        }
+    } else {
+        $moveUpStmt->bindParam(
+            ':page',
+            $page,
+            PDO::PARAM_INT
+        );
+        $moveUpStmt->bindParam(
+            ':oldpos',
+            $_REQUEST['oldpos'],
+            PDO::PARAM_INT
+        );
+        $moveUpStmt->bindParam(
+            ':newpos',
+            $_REQUEST['newpos'],
+            PDO::PARAM_INT
+        );
+        $moveUpStmt->execute();
+    }
+
+    $updateStmt->bindParam(
+        ':pos',
+        $_REQUEST['newpos'],
+        PDO::PARAM_INT
+    );
+    $updateStmt->bindParam(
+        ':id',
+        $_REQUEST['id'],
+        PDO::PARAM_INT
+    );
+    $updateStmt->execute();
+    $dbh->commit();
+} catch (PDOException $e) {
+       $dbh->rollback();
+    Toolkit_Logger::logException('DB Error', $e);
+}
+$cache = new Cache_Lite($GLOBALS['cacheOptions']);
+$cache->clean('Toolbox');
+header('Location: '.MEDIA_BASE_URL.'userArea/toolbox.php?rt=Paragraphs&pageid='.$page);
diff --git a/Toolkit/UserArea/pageChangeState.php b/Toolkit/UserArea/pageChangeState.php
new file mode 100644 (file)
index 0000000..d4da710
--- /dev/null
@@ -0,0 +1,32 @@
+<?php
+require_once '../../setup.phtml';
+
+if (!isset($_GET['kpass'])) {
+       return false;
+}
+if (!ctype_digit($_GET['catid'])) {
+       return false;
+}
+
+$dbh = Toolkit_Database::getInstance();
+
+try {
+       $sql = "
+        UPDATE pages
+           SET active = not active
+         WHERE id     = :id";
+
+       $stmt = $dbh->prepare($sql);
+       $stmt->bindParam(':id', $_GET['catid'], PDO::PARAM_INT);
+       $res = $stmt->execute();
+
+       $cache = new Cache_Lite($GLOBALS['cacheOptions']);
+       $cache->clean('Toolbox');
+
+       echo (int) $res;
+       return $res;
+} catch (PDOException $e) {
+       Toolkit_Logger::logException('DB Error', $e);
+       return false;
+}
+?>
diff --git a/Toolkit/UserArea/pageMobileChangeState.php b/Toolkit/UserArea/pageMobileChangeState.php
new file mode 100644 (file)
index 0000000..015aa55
--- /dev/null
@@ -0,0 +1,31 @@
+<?php
+require_once '../../setup.phtml';
+
+if (!isset($_GET['kpass'])) {
+       return false;
+}
+if (!ctype_digit($_GET['catid'])) {
+       return false;
+}
+
+$dbh = Toolkit_Database::getInstance();
+try {
+    $sql = "
+        UPDATE pages
+           SET mobile_active = not mobile_active
+         WHERE id = :id";
+
+    $stmt = $dbh->prepare($sql);
+    $stmt->bindParam(':id', $_GET['catid'], PDO::PARAM_INT);
+    $res = $stmt->execute();
+    
+       $cache = new Cache_Lite($GLOBALS['cacheOptions']);
+       $cache->clean('Toolbox');
+
+       echo (int) $res;
+       return $res;
+} catch (PDOException $e) {
+       Toolkit_Logger::logException('DB Error', $e);
+       return false;
+}
+?>
diff --git a/Toolkit/UserArea/pageMove.php b/Toolkit/UserArea/pageMove.php
new file mode 100644 (file)
index 0000000..b989d7b
--- /dev/null
@@ -0,0 +1,96 @@
+<?php
+if (!isset($_GET['kpass'])) {
+       die();
+}
+
+require_once '../../setup.phtml';
+
+$writer = new Zend_Log_Writer_Firebug();
+$logger = new Zend_Log($writer);
+
+$request  = new Zend_Controller_Request_Http();
+$response = new Zend_Controller_Response_Http();
+$channel  = Zend_Wildfire_Channel_HttpHeaders::getInstance();
+$channel->setRequest($request);
+$channel->setResponse($response);
+
+//     start output buffering
+ob_start();
+
+//     Now you can make calls to the logger
+
+$dbh = Toolkit_Database::getInstance();
+
+extract($_GET);
+
+try {
+       $dbh->beginTransaction();
+       if ($direction == 'down') {
+               $sql = "
+            UPDATE pages
+               SET pos    =  pos - 1
+             WHERE id     <> :id
+               AND id     <> :home_id
+               AND pos    =  (
+                                       SELECT pos + 1
+                                         FROM pages
+                                        WHERE id =  :id)
+               AND parent =  (
+                                       SELECT parent
+                                         FROM pages
+                                        WHERE id =  :id)";
+               $stmt = $dbh->prepare($sql);
+               $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $stmt->bindValue(':home_id', HOME_ID, PDO::PARAM_INT);
+               $stmt->execute();
+
+               $sql = "
+            UPDATE pages
+               SET pos = pos + 1
+             WHERE id  = :id";
+               $stmt = $dbh->prepare($sql);
+               $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $stmt->execute();
+       } elseif ($direction == 'up') {
+               $sql = "
+            UPDATE pages
+               SET pos    =  pos + 1
+             WHERE id     <> :id
+               AND id     <> :home_id
+               AND pos    =  (
+                                       SELECT pos - 1
+                                         FROM pages
+                                        WHERE id = :id)
+               AND parent =  (
+                                       SELECT parent
+                                         FROM pages
+                                        WHERE id = :id)";
+               $stmt = $dbh->prepare($sql);
+               $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $stmt->bindValue(':home_id', HOME_ID, PDO::PARAM_INT);
+               $stmt->execute();
+
+               $sql = "
+            UPDATE pages
+               SET pos = pos - 1
+             WHERE id  = :id";
+               $stmt = $dbh->prepare($sql);
+               $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $stmt->execute();
+       }
+
+       $dbh->commit();
+       echo 1;
+} catch (PDOException $e) {
+       $dbh->rollback();
+       if ('production' == strtolower($_SERVER['GLM_HOST_ID'])) {
+               $logger->crit($e->getMessage());
+       } else {
+               Toolkit_Logger::logException('DB Error', $e);
+       }
+       echo 0;
+}
+//     Flush log data to browser
+$channel->flush();
+$response->sendHeaders();
+die();
diff --git a/Toolkit/UserArea/paragraphChangeState.php b/Toolkit/UserArea/paragraphChangeState.php
new file mode 100644 (file)
index 0000000..88aa1a9
--- /dev/null
@@ -0,0 +1,44 @@
+<?php
+require_once '../../setup.phtml';
+
+if (!isset($_GET['kpass'])) {
+       return false;
+}
+if (!ctype_digit($_GET['paragraphId'])) {
+       return false;
+}
+
+$dbh = Toolkit_Database::getInstance();
+
+try {
+       $sql = "
+        UPDATE paragraphs
+           SET active = not active
+         WHERE id     = :id";
+
+       $stmt = $dbh->prepare($sql);
+       $stmt->bindParam(':id', $_GET['paragraphId'], PDO::PARAM_INT);
+       $res = $stmt->execute();
+
+
+       $sql = "
+               SELECT page
+                 FROM paragraphs
+                WHERE id = :id";
+
+       $stmt = $dbh->prepare($sql);
+       $stmt->bindParam(':id', $_GET['paragraphId'], PDO::PARAM_INT);
+       $stmt->execute();
+       $stmt->bindColumn('page', $pageId);
+       $stmt->fetch(PDO::FETCH_ASSOC);
+
+       $cache = new Cache_Lite($GLOBALS['cacheOptions']);
+       $cache->clean('Toolbox');
+
+       echo (int) $res;
+       return $res;
+} catch (PDOException $e) {
+       Toolkit_Logger::logException('DB Error', $e);
+       return false;
+}
+?>
diff --git a/Toolkit/UserArea/paragraphFileUpload.php b/Toolkit/UserArea/paragraphFileUpload.php
new file mode 100644 (file)
index 0000000..2bc5553
--- /dev/null
@@ -0,0 +1,14 @@
+<?php
+require_once '../../setup.phtml';
+
+$fs = new Toolkit_FileServer_FileAdapter();
+try {
+       $res = $fs->upload('userfile');
+} catch (Toolkit_FileServer_Exception $e) {
+       Toolkit_Logger::logException('File Server', $e);
+       echo -1; // Don't return "false", it will mess up the JS plugin.
+       return;
+}
+
+echo json_encode($res);
+?>
diff --git a/Toolkit/UserArea/paragraphMove.php b/Toolkit/UserArea/paragraphMove.php
new file mode 100644 (file)
index 0000000..fd269d7
--- /dev/null
@@ -0,0 +1,51 @@
+<?php
+if (!isset($_GET['kpass'])) {
+       die();
+}
+
+require_once '../../setup.phtml';
+
+$dbh = Toolkit_Database::getInstance();
+
+extract($_GET);
+
+try {
+       $dbh->beginTransaction();
+       if ($direction == 'down') {
+               //      Update paragraph nodes on this page who lie at the target node
+               //      position and the position just after it.
+               $sql = "
+            UPDATE paragraphs
+               SET pos  = CASE WHEN id = :id
+                                     THEN pos + 1 ELSE pos - 1 END
+             WHERE page = (SELECT page FROM paragraphs WHERE id = :id)
+               AND pos BETWEEN (SELECT pos FROM paragraphs WHERE id = :id)
+               AND (SELECT pos + 1 FROM paragraphs WHERE id = :id)";
+               $stmt = $dbh->prepare($sql);
+               $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $stmt->execute();
+       } elseif ($direction == 'up') {
+               //      Update paragraph nodes on this page who lie at the target node
+               //      position and the position just before it.
+               $sql = "
+            UPDATE paragraphs
+               SET pos  = CASE WHEN id = :id
+                                     THEN pos - 1 ELSE pos + 1 END
+             WHERE page = (SELECT page FROM paragraphs WHERE id = :id)
+               AND pos BETWEEN (SELECT pos - 1 FROM paragraphs WHERE id = :id)
+               AND (SELECT pos FROM paragraphs WHERE id = :id)";
+               $stmt = $dbh->prepare($sql);
+               $stmt->bindParam(':id', $id, PDO::PARAM_INT);
+               $stmt->execute();
+       }
+
+       $dbh->commit();
+       die();
+} catch (PDOException $e) {
+       $dbh->rollback();
+       Toolkit_Logger::logException('DB Error', $e);
+       throw new Toolkit_UserArea_Exception(
+               "unable to move paragraph `$id` `$direction`"
+       );
+}
+?>
diff --git a/Toolkit/UserArea/styles.css b/Toolkit/UserArea/styles.css
new file mode 100644 (file)
index 0000000..3be1ead
--- /dev/null
@@ -0,0 +1,132 @@
+.webform table { width: 742px; }
+.fieldcell { width: auto; }
+
+/* form section arrows */
+tr.hdr td {
+       background: #DDD url("//app.gaslightmedia.com/assets/icons/bullet_arrow_right.png") no-repeat;
+       padding-left: 15px;
+       cursor: pointer;
+       cursor: hand;
+}
+tr.hdr td:hover {
+       background-color: #e5e5e5;
+}
+tr.hdr td.open{
+       background-image: url("//app.gaslightmedia.com/assets/icons/bullet_arrow_down.png");
+}
+
+/* paragraph files */
+.files {
+       list-style-type: none;
+       margin: 0;
+       padding: 0;
+       width: 60%;
+}
+.files li {
+       margin: 0 3px 3px 3px;
+       padding: 0.4em;
+       padding-left: 1.5em;
+}
+.files li span {
+       position: absolute;
+       margin-left: -1.3em;
+}
+.files .ui-state-highlight {
+       height: 1.5em;
+       line-height: 1.2em;
+}
+#success_notification {
+       font-weight: bold;
+       color: #11a52f;
+}
+
+/* right tree element */
+.right-element {
+       float: left;
+       }
+.paragraph-line {
+       float: none !important;
+}
+.paragraph-line strong {
+        margin-left: 10px;
+        }
+/* highlight search matches in tree */
+.search {
+       color: orange;
+}
+
+/* Ove */
+#q {
+       border: 2px inset black;
+       height: 20px;
+       padding: 2px;
+       font-size: 16px;
+       width: 200px;
+       margin-right: 10px;
+       font-weight: bold}
+
+#tree li {
+       display: block;
+       line-height: 24px !important;
+}
+li.closed { background: url(assets/arrowClosed.png) no-repeat !important;}
+li.open { background: url(assets/arrowOpen.png) no-repeat !important;}
+/*.ltr>li {
+       border-bottom: 1px dashed #ccc;
+}*/
+#tree li.last {
+       float: none;
+}
+#tree {
+       width: 630px;
+}
+
+/*
+ * #tree ul {
+ *     background: #ece;
+ *     }
+ *     #tree ul ul {
+ *             background: #cee;
+ *     }
+ *     #tree ul ul ul {
+ *             background: #eec;
+ *     }
+ *     #tree ul ul ul ul {
+ *             background: #ede;
+ *     }
+ */
+.right-element a {
+       text-decoration: underline !important;
+}
+
+#tree .editPage, .editPage:hover,
+#tree .editParagraphs, .editParagraphs:hover,
+#tree .pagePreview, .pagePreview:hover {
+       height: 16px;
+       padding: 0 5px 0 0px !important;
+       border: 0;
+}
+
+/*
+#tree .editPage, .editPage:hover { background: url(//app.gaslightmedia.com/assets/icons/page_edit.png) no-repeat; }
+#tree .editParagraphs, .editParagraphs:hover {         background: url(//app.gaslightmedia.com/assets/icons/page_add.png) no-repeat; }
+#tree .pagePreview, .pagePreview:hover {       background: url(//app.gaslightmedia.com/assets/icons/page_go.png) no-repeat; }
+
+#tree a:hover { color: green;}
+*/
+/* Lines */
+#tree li {
+       /*      border-bottom: 1px dotted #666;
+        *      padding-bottom: 1px;
+        */
+}
+
+/* Mousetip */
+.moveUp, .moveDown {
+       cursor: hand;
+       cursor: pointer;
+}
+.tOff {
+       visibility: hidden;
+}
+.form-success {border:1px solid green;color:green;padding:10px;margin:5px;}
diff --git a/Toolkit/UserArea/views/EditUserApps.html b/Toolkit/UserArea/views/EditUserApps.html
new file mode 100644 (file)
index 0000000..5bef2a5
--- /dev/null
@@ -0,0 +1,146 @@
+<style>
+    #appData {
+        width: 600px;
+        margin: 0;
+        padding: 0;
+    }
+    #userAppList {
+        width:600px;
+        clear:both;
+        float:left;
+    }
+    #userAppList label {
+        width: 150px;
+        float: left;
+        display: block;
+    }
+    #userToolboxPages {
+        width:600px;
+        clear: both;
+        float: left;
+
+    }
+    .pageLink {
+        width: 96%;
+        padding: 5px 2%;
+        border-bottom: 1px solid #CCC;
+        margin: 3px 0;
+        border-left: 1px solid #CCC;
+        border-right: 1px solid #CCC;
+        border-top: 1px solid #CCC;
+        background: #EFEFEF;
+    }
+    .btnDelete, .asmListItemRemove {
+        float: right;
+    }
+    .asmListItemRemove {
+        width: 5px;
+        height: 5px;
+        margin: 0 12px;
+    }
+    select.asmSelect {
+        width: 300px;
+    }
+</style>
+<div id="userAppList">
+    {foreach:apps,app}
+    <?php if ($app->getConfig()) {
+    continue;
+    }?>
+    <input type="hidden" name="app[{app.getId():h}]" value="0">
+    <label>
+        <?php if (is_array($t->userApps)
+        && in_array($app->getId(), $t->userApps)) {?>
+        <input type="checkbox" name="app[{app.getId():h}]" value="1" checked>
+        <?php } else { ?>
+        <input type="checkbox" name="app[{app.getId():h}]" value="1">
+        <?php }?>
+        {app.getName()}
+    </label>
+    {end:}
+</div>
+{if:hasToolbox}
+<b>Toolbox</b>
+<div id="userToolboxPages">
+    {foreach:pages,page}
+    <div class="pageLink">
+        <input type="hidden" value="{page[id]}" name="pages[]">
+        {page[name]}
+        <a href="#" class="ui-icon ui-icon-trash btnDelete">Delete</a>
+    </div>
+    {end:}
+    <div id="dialog-modal" title="Page Selector" style="display:none;">
+        <div id="pages"></div>
+    </div>
+    <button id="addToolboxPage">Add Toolbox Section</button>
+</div>
+{if:hasEvents}
+<div>
+    <b>Events Categories</b>
+    {if:categories}
+    <select name="eventCategories[]" class="event-cat" multiple="multiple" title="Select Categories">
+        {foreach:categories,category}
+            <?php
+            echo '<option value="'.$category->getId().'"';
+            if (   is_array($t->userEventCategories)
+            && in_array($category->getId(), $t->userEventCategories)
+            ) {
+                echo ' selected';
+            }
+            echo '>' . $category->getName();
+            echo '</option>'
+            ?>
+        {end:}
+    </select>
+    {end:}
+</div>
+{end:}
+<script>
+    $(function() {
+        $('body').delegate('.btnDelete', 'click', function() {
+            $(this).parent().remove();
+        });
+        $('select[multiple]').asmSelect({
+            removeClass: 'asmListItemRemove ui-icon ui-icon-trash'
+        });
+        $("#addToolboxPage").click(function() {
+            var selectedPageId   = null;
+            var selectedPageName = null;
+            $("#dialog-modal").dialog({
+                height: 240,
+                width: 800,
+                modal: true,
+                buttons: {
+                    "Select Page": function() {
+                        if (selectedPageId != '') {
+                            // here is where it adds the page
+                            $("#userToolboxPages").append('<div class="pageLink">'
+                                + '<input type="hidden" name="pages[]" value="'
+                                + selectedPageId + '">'
+                                + selectedPageName
+                                + '<a href="#" class="ui-icon ui-icon-trash btnDelete">Delete</a>'
+                                + '</div>');
+                            $(this).dialog("close");
+                        } else {
+                            alert("Select a Page");
+                        }
+                    },
+                    Cancel: function() {
+                        $(this).dialog("close");
+                    }
+                }
+            });
+            $("#pages").load('userArea.php?ac=showPages', function() {
+                $('#demo1').columnview({
+                    preview: false,
+                    onchange: function(element) {
+                        selectedPageId   = $(element).attr('data-page');
+                        selectedPageName = $(element).attr('data-name');
+                    }
+                });
+            });
+            return false;
+        });
+    });
+</script>
+{end:}
index 2f5d44e..e2de4de 100644 (file)
@@ -87,6 +87,7 @@ if (defined('BANNERS') && BANNERS) {
 if (defined('CONTACT_DB') && CONTACT_DB) {
     $nav['Contacts'] = MEDIA_BASE_URL.'admin/Contact/';
 }
+$nav['User Area'] = MEDIA_BASE_URL . 'admin/userArea.php';
 if (defined('EVENT_DB') && EVENT_DB) {
     $nav['Events']
         = (defined('COMMON_EVENTS') && COMMON_EVENTS)
diff --git a/admin/userArea.php b/admin/userArea.php
new file mode 100644 (file)
index 0000000..560d130
--- /dev/null
@@ -0,0 +1,19 @@
+<?php
+require_once '../setup.phtml';
+$GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'Toolkit/UserArea/css/styles.css';
+$nav['List Users']      = 'userArea.php';
+$nav['Create New User'] = 'userArea.php?ac=Edit';
+$registry = new Toolkit_Registry;
+$registry->baseUrl = MEDIA_BASE_URL;
+$registry->dbh     = Toolkit_Database::getInstance();
+$registry->logger  = Toolkit_Logger::getLogger();
+$registry->router  = new Toolkit_Router($registry);
+$registry->router->setPath(BASE . 'Toolkit/UserArea/Admin');
+$registry->router->setApplication('UserArea/Admin');
+
+$html = $registry->router->loader();
+
+GLM_TOOLBOX::top('Users', '');
+echo GLM_TOOLBOX::html_nav_table($nav, 4);
+echo $html;
+GLM_TOOLBOX::footer();
diff --git a/static/11.phtml b/static/11.phtml
new file mode 100644 (file)
index 0000000..705e836
--- /dev/null
@@ -0,0 +1,12 @@
+<?php
+if ($catid = filter_input(INPUT_GET, 'catid', FILTER_VALIDATE_INT)) {
+       $cf = new Toolkit_Contacts_ContactUs(
+               Toolkit_Database::getInstance(),
+               'contact_form',
+               'post',
+               BASE_URL . "index.php?catid=$catid"
+       );
+       $cf->configureForm();
+       $cf->useCaptcha(true);
+       echo $cf->toHtml();
+}
diff --git a/userArea/CommonEvents/.htaccess b/userArea/CommonEvents/.htaccess
new file mode 100644 (file)
index 0000000..7f2df55
--- /dev/null
@@ -0,0 +1,3 @@
+AddDefaultCharset utf-8
+php_flag register_globals off
+php_flag magic_quotes_gpc off
diff --git a/userArea/CommonEvents/index.php b/userArea/CommonEvents/index.php
new file mode 100644 (file)
index 0000000..c5bf976
--- /dev/null
@@ -0,0 +1,39 @@
+<?php
+try {
+    // look for a setup.phtml file in the directory one up from here
+    if (file_exists('../../setup.phtml')) {
+        include_once '../../setup.phtml';
+    } else {
+        throw new Exception('setup.phtml file not found!');
+    }
+    require_once '../setup.php';
+    // get the users Event Categories
+    $userAuth = Registry::get('Toolkit_UserArea_Auth');
+    //var_dump($userAuth);
+    $categories = $userAuth->getUserEventCategories(
+        Toolkit_Database::getInstance()
+    );
+    define('USER_AREA_EVENT_CATEGORIES', serialize($categories));
+    //var_dump($categories);
+    //var_dump(USER_AREA_EVENT_CATEGORIES);
+    //exit;
+    // set CommonApp define if not set
+    if (!defined('COMMON_APP_BASE')) {
+        define('COMMON_APP_BASE', '/var/www/server/CommonApps/');
+    }
+    // load the event application config files form CommonApps
+    define('COMMON_APP_NAME', 'EventCalendar');
+    define('COMMON_APP_VERSION', 'V1');
+    define('COMMON_APP_INI', 'application.ini');
+    define('COMMON_APP_SITE_INI', 'userAppEvent.ini');
+
+    define('COMMON_APP_CONTROLLER', 'AdminController');
+    $appPath = COMMON_APP_BASE . COMMON_APP_NAME . '/' . COMMON_APP_VERSION . '/';
+    define('COMMON_APP_PATH', $appPath);
+    // now only need to pull in the main file to run the app
+    // pull in admin.php file
+    require COMMON_APP_PATH . 'Bootstrap.php';
+
+} catch(Exception $e) {
+    die($e->getMessage());
+}
diff --git a/userArea/Contact/contact_inquiry.phtml b/userArea/Contact/contact_inquiry.phtml
new file mode 100755 (executable)
index 0000000..4eaf7e1
--- /dev/null
@@ -0,0 +1,125 @@
+<?php
+
+/**
+ * contact_inquiry.phtml
+ * 
+ * Groups are now added to the contact inquiry types.  Groups is a
+ * required field.
+ * 
+ * PHP versions 4 and 5
+ * 
+ * @category  Toolkit
+ * @package   Contacts
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: contact_inquiry.phtml,v 1.3 2009/07/24 14:27:45 matrix Exp $
+ * @link      http://pear.php.net/package/Contacts
+ * @see       References to other sections (if any)...
+ */
+
+/**
+ * base setup file for all apps
+ */
+require_once '../../setup.phtml';
+
+/**
+ * base setup for contact admin section
+ */
+require_once "contact_setup.inc";
+GLM_TOOLBOX::top('Contact Inquiries', '');
+//     Adjust the nav for this page, add the Edit Groups page.
+if (is_array($nav) && array_key_exists('Contact Inquiry Fields', $nav)) {
+       $tmp = array('Inquiry Groups' => 'list_groups.php');
+       array_insert($nav, 'Contact Inquiry Fields', $tmp); 
+}
+GLM_TOOLBOX::html_nav_table($nav, $navWidth);
+$qs = "
+ SELECT id, header, groupid, pos
+   FROM contact_inq
+  ORDER BY groupid, pos;";
+$result = $DB->db_exec($qs);
+$query = "
+    SELECT id, name
+      FROM inq_group
+     ORDER BY name;";
+if ($groupData = $DB->db_auto_get_data($query)) {
+       foreach ($groupData as $groupRow) {
+               $gRow[$groupRow['id']] = $groupRow['name'];
+       }
+}
+?>
+<table id="admin-list-table">
+       <tr>
+         <th colspan="4">
+               <form action="edit_inquiry.phtml" method="POST" name="edit_inquiry">
+                       <input type="submit" name="Command" value="Add Item" />
+               </form>
+         </th>
+       </tr>
+       <tr>
+         <th>Options:</th>
+         <th>Pos:</th>
+         <th>Group:</th>
+         <th>Inquiry Name:</th>
+       </tr>
+<?php
+$num = $DB->db_numrows($result);
+if ($num > 0) {
+       for ($i = 0; $i < $num; $i++) {
+               $data = $DB->db_fetch_array($result, $i, PGSQL_ASSOC);  
+               if ($data['groupid'] != $oldgroup && isset($oldgroup)) {
+                       echo '<tr><td colspan="4">&nbsp;</td></tr>';
+               }
+               ?>
+               <tr>
+                       <td nowrap>
+                               <a href="edit_inquiry.phtml?id=<?php echo $data['id'];?>&amp;Command=Edit">[Edit / Delete]</a>
+                       </td>
+                       <td>
+        <?php
+        $qs = "
+         SELECT COUNT(id) AS maxpos
+           FROM contact_inq
+          WHERE groupid = ".$data['groupid'];
+
+        $maxresult = $DB->db_exec($qs);
+        $max_data = $DB->db_fetch_array($maxresult, 0, PGSQL_ASSOC);
+        $maxpos = $max_data['maxpos'];
+        $pos = '<select style="font-size: 10pt;" name="pos" 
+            onChange="location.href=this[this.selectedIndex].value;"
+        size="1">';
+        for ($newpos = 1; $newpos <= $maxpos; $newpos++) {
+            $string = 'Command=Move&amp;groupid='.$data['groupid'].'&amp;id='.$data['id']."&amp;newpos=$newpos";
+            $pos .= "<option value=\"update_inquiry.phtml?$string\"";
+            if ($newpos == $data['pos']) { 
+                $pos .= ' selected';
+            }
+            $pos .= ">$newpos</option>";
+        }
+        $pos .= '</select>';
+        echo $pos;
+        ?>
+                       </td>
+                       <td nowrap>
+                               <?php echo $gRow[$data['groupid']];?>
+                       </td>
+                       <td align="left">
+                               <?php echo $data['header'];?>
+                       </td>
+               </tr>
+               <?php
+               $oldgroup = $data['groupid'];
+       }
+} else {
+       ?>
+       <tr>
+               <th colspan="2">Nothing in the database yet</th>
+       </tr>
+       <?php
+}
+?>
+</table>
+<?php
+GLM_TOOLBOX::footer();
+?>
diff --git a/userArea/Contact/contact_setup.inc b/userArea/Contact/contact_setup.inc
new file mode 100755 (executable)
index 0000000..95f721e
--- /dev/null
@@ -0,0 +1,475 @@
+<?php
+
+/**
+* contact_setup.phtml
+* 
+* Config setting for the admin contact application 
+* 
+* PHP versions 4 and 5
+* 
+* @category  Toolkit
+* @package   Contacts
+* @author    Steve Sutton <steve@gaslightmedia.com>
+* @copyright 2009 Steve Sutton
+* @license   Gaslight Media
+* @version   CVS: $Id: contact_setup.inc,v 1.7 2010/05/13 17:05:53 matrix Exp $
+* @link      <>
+*/
+extract($_REQUEST);
+// The Contact Type array is now is one location and is used by the 
+// Toolkit_Contacts_Admin_EditContact class
+$conf = new Config;
+$contactRoot =& $conf->parseConfig(
+       BASE . 'Toolkit/Contacts/config.ini',
+       'IniFile'
+);
+if (!defined("ENTRIES_PER_PAGE")) {
+
+    /**
+    * how many per page on list contacts
+    */
+    define("ENTRIES_PER_PAGE", 10);    // Entries per Page in list_contact.phtml
+}
+
+/**
+* define for customer table
+*/
+define("CUSTOMER_TABLE", "customer");    // name of customer table
+
+/**
+* define for contact table
+*/
+define("CONTACT_TABLE", "contact");        // name of contact table
+
+$table = $contactRoot->getItem('section', 'conf')
+    ->getItem('directive', 'table')
+    ->getContent();
+/**
+* Table to user in db
+*/
+define("TABLE", $table);            // which table to use
+
+/**
+* postgres date formate
+*/
+define("DATEFORMAT", "US");                // date format (for edit_contact.phmtl)
+
+/**
+* template for the newsletter
+*/
+define("NEWSLETTER_PROTOTYPE", "newsletter_template.html");                // date format (for edit_contact.phmtl)
+
+/**
+* class_template needed for GLM_TEMPLATE::get_seo_url()
+*/
+require_once BASE.'classes/class_template.inc';
+$DB = new GLM_DB();
+if (!defined("HTML_EMAIL")) {
+
+    /**
+    * HTML_EMAIL = ON or OFF 
+    */
+    define("HTML_EMAIL", "ON");
+}
+if (!defined("PRODUCTION_MODE")) {
+
+    /**
+    * PRODUCTION_MODE off/on  mail sent
+    */
+    define("PRODUCTION_MODE", "ON");
+}
+if (!defined("NEWSLETTER")) {
+
+    /**
+    * NEWSLETTER 1 or true will allow newsletters
+    */
+    define("NEWSLETTER", 1); //bool- does the contact database mail out a newsletter? 
+}
+
+if (!function_exists("template_read")) {
+
+    /**
+    * Short description for function
+    * 
+    * Long description (if any) ...
+    * 
+    * @param unknown $template Parameter description (if any) ...
+    * 
+    * @return string  Return description (if any) ...
+    */
+    function template_read($template)
+    {
+        $fp       = fopen($template, "r");
+        $contents = fread($fp, filesize($template));
+        fclose($fp);
+        if ($contents) {
+            return $contents;
+        } else {
+            return "";
+        }
+    }
+}
+// {{{ array_insert()
+
+
+/**
+* insert an array into another array after position.
+* You can specify an associative array key or index key
+* to dictact the positioning of the new array
+* 
+* @param array   &$array       array to be used
+* @param unknown $position     position to add array
+* @param unknown $insert_array array to be inserted
+* 
+* @return void   
+*/
+function array_insert(&$array, $position, $insert_array)
+{
+    if (!is_int($position)) {
+        $i = 0;
+        foreach ($array as $key => $value) {
+            if ($key == $position) {
+                $position = ++$i;
+                break;
+            }
+            ++$i;
+        }
+    }
+    $first_array = array_splice($array, 0, $position);
+    $array = array_merge($first_array, $insert_array, $array);
+}
+// }}}
+// {{{ explode_template()
+if (!function_exists("explode_template")) {
+
+    /**
+    * Short description for function
+    * 
+    * Long description (if any) ...
+    * 
+    * @param unknown $template Parameter description (if any) ...
+    * @param unknown $data     Parameter description (if any) ...
+    * 
+    * @return unknown Return description (if any) ...
+    */
+    function explode_template($template, $data)
+    {
+        $template = template_read($template);
+        $output   = template_replacement($template, $data);
+        $output   = wordwrap($output, 72);
+        return $output;
+
+    }
+}
+// }}}
+// {{{ template_replacement($template, $fieldarr)
+if (!function_exists("template_replacement")) {
+
+    /**
+    * Short description for function
+    * 
+    * Long description (if any) ...
+    * 
+    * @param unknown $template Parameter description (if any) ...
+    * @param array   $fieldarr Parameter description (if any) ...
+    * 
+    * @return unknown Return description (if any) ...
+    */
+    function template_replacement($template, $fieldarr)
+    {
+        if (is_array($fieldarr)) {
+            foreach ($fieldarr as $key => $value) {
+                $template = str_replace("<!-- ".$key." -->", $value, $template);
+            }
+        }
+        return $template;
+    }
+}
+// }}}
+// {{{ add_image($image, $align)
+if (!function_exists("add_image")) {
+
+    /**
+    * Short description for function
+    * 
+    * Long description (if any) ...
+    * 
+    * @param string $image Parameter description (if any) ...
+    * @param string $align Parameter description (if any) ...
+    * 
+    * @return string Return description (if any) ...
+    */
+    function add_image($image, $align)
+    {
+        if ($image != "") {
+            return '<div style="margin:5px;float:'.$align.';"><img src="'.MIDSIZED.$image.'"></div>';
+        }
+    }
+}
+// }}}
+// {{{ Navigation array
+$nav      = array(
+    "Report Builder"         => "index.phtml",
+    "Add Contact"            => "edit_contact.php",
+    "List Contacts"          => "list_contact.phtml",
+    "Contact Inquiry Fields" => "contact_inquiry.phtml",
+    "HTML Emails"            => "emails.php",
+    "Saved Reports"          => "list_query.phtml",
+);
+// }}}
+$navWidth = 7;
+$query    = "select * from contact_inq order by pos;";
+$cData    = $DB->db_auto_get_data($query);
+if (is_array($cData)) {
+    foreach ($cData as $key => $value) {
+        $int_array[$value['id']] = $value['header'];
+    }
+}
+$contactTypesSetup = 
+    $contactRoot->getItem('section', 'contact_types')
+       ->toArray();
+$cType = $contactTypesSetup['contact_types'];
+// {{{ search_where($name, $search_where)
+
+/**
+* Short description for function
+* 
+* Long description (if any) ...
+* 
+* @param string $name         Parameter description (if any) ...
+* @param string $search_where Parameter description (if any) ...
+* 
+* @return string Return description (if any) ...
+*/
+function search_where($name, $search_where)
+{
+    $out = '
+    <select name="'.$name.'">
+        <option value="1" '.( ( !isset( $search_type ) || $search_type == "0" ) ? 'selected' : '' ).'>Anywhere 
+        <option value="2" '.( ( $search_where == '1' ) ? 'selected' : '' ).'>Begining 
+        <option value="3" '.( ( $search_where == '2' ) ? 'selected' : '' ).'>Ending
+    </select>';
+    return $out;
+}
+// }}}
+// {{{ search_type($name, $search_type)
+
+/**
+* Short description for function
+* 
+* Long description (if any) ...
+* 
+* @param string $name        Parameter description (if any) ...
+* @param string $search_type Parameter description (if any) ...
+* 
+* @return string Return description (if any) ...
+*/
+function search_type($name, $search_type)
+{
+    $out = '
+    <select name="'.$name.'">
+        <option value="2" '.( ( !isset( $search_type ) || $search_type == '2' ) ? 'selected' : '' ).'>And 
+        <option value="3" '.( ( $search_type == '3' ) ? 'selected' : '' ).'>Or
+        <option value="4" '.( ( $search_type == '4' ) ? 'selected' : '' ).'>Not
+    </select>';
+    return $out;
+}
+// }}}
+// {{{ search_bool($name, $search_type)
+
+/**
+* Short description for function
+* 
+* Long description (if any) ...
+* 
+* @param string $name        Parameter description (if any) ...
+* @param string $search_type Parameter description (if any) ...
+* 
+* @return string Return description (if any) ...
+*/
+function search_bool($name, $search_type)
+{
+    $out = '
+    <select name="'.$name.'">
+        <option value="n" '.( !isset( $search_type ) ? 'selected' : '' ).'>Don\'t Care 
+        <option value="1" '.( ( $search_type == '1' ) ? 'selected' : '' ).'>Yes
+        <option value="0" '.( ( $search_type == '0' ) ? 'selected' : '' ).'>No
+    </select>';
+    return( $out );
+}
+// }}}
+// {{{ interest($field)
+
+/**
+* Short description for function
+* 
+* Long description (if any) ...
+* 
+* @param unknown $field Parameter description (if any) ...
+* 
+* @return boolean Return description (if any) ...
+*/
+function interest($field)
+{        
+    if (!is_array($GLOBALS['int_array'])) {
+        return false;
+    }
+    echo "<table><tr>";
+    $count = 0;
+    foreach ($GLOBALS['int_array'] as $key => $value) {
+        if ($count==0) {
+            echo "<td>";        
+        }
+        echo "<input type=\"checkbox\" name=\"interest[]\" value=\"$key\"";
+        if (strstr($field, ":".$key.":")) {
+            echo " checked";                
+        }
+        echo ">$value<br>";        
+        if ($count==5) {
+            echo "</td><td>";        
+        }
+        if ($count==11) {
+            echo "</td>";        
+        }
+        $count++;        
+    }        
+    echo "</tr></table>";
+}
+/**
+* Get a group of select elements to represent a date
+*
+* @param string $M Name attribute of the month select list
+* @param string $D Name attribute of the day select list
+* @param string $Y Name attribute of the year select list
+* @param string $m Selected value of the month select list
+* @param string $d Selected value of the day select list
+* @param string $y Selected value of the year select list
+*                   
+* @return string Html string of group select lists
+* @access public
+*/
+function dateSelector($M, $D, $Y, array $m = null, array $d = null, array $y = null)
+{
+    //  Get a Select element
+    $month = new HTML_Select($M);
+    //  Get a Range of months jan-dec
+    $monthArray = array_flip(range(1, 12));
+    //  Make the keys and values the same
+    foreach ($monthArray as $i => &$j) {
+        $j = $i;
+    }
+    $month->loadArray($monthArray);
+    if (is_null($m)) {
+        $month->setSelectedValues(array(date('m')));
+    } else {
+        $month->setSelectedValues($m);
+    }
+
+    //  Get a Select element
+    $day = new HTML_Select($D);
+    //  Get a Range of months jan-dec
+    $dayArray = array_flip(range(1, 31));
+    //  Make the keys and values the same
+    foreach ($dayArray as $i => &$j) {
+        $j = $i;
+    }
+    $day->loadArray($dayArray);
+    if (is_null($d)) {
+        $day->setSelectedValues(array(date('d')));
+    } else {
+        $day->setSelectedValues($d);
+    }
+
+    //  Get a Select element
+    $year = new HTML_Select($Y);
+    //  Get a Range of months jan-dec
+    $yearArray = array_flip(range(CONTACTS_FIRST_YEAR, date('Y')));
+    //  Make the keys and values the same
+    foreach ($yearArray as $i => &$j) {
+        $j = $i;
+    }
+    $year->loadArray($yearArray);
+    if (is_null($y)) {
+        $year->setSelectedValues(array(date('Y')));
+    } else {
+        $year->setSelectedValues($y);
+    }
+
+    return $month->toHtml() . $day->toHtml() . $year->toHtml();
+}
+
+// }}}
+// default query on create_date
+$c_date_from  = GLM_TOOLBOX::contact_date_entry("", "", "", "fc_month", "fc_day", "fc_year");
+$c_date_to    = GLM_TOOLBOX::contact_date_entry("", "", "", "tc_month", "tc_day", "tc_year");
+
+// The Following $DB_fields array is no longer used for the edit contact page
+// You must alter the class Toolkit_Contacts_Admin_EditContact 
+// The following is only used for the search form and the listing pages
+
+$primaryKey = $contactRoot->getItem('section', 'conf')
+    ->getItem('directive', 'primarykey')
+    ->getContent();
+/**
+* Description for define
+*/
+define("ID", $primaryKey);
+
+/**
+* Description for define
+*/
+define("MAILOK", "mail_ok");
+
+$sequence = $contactRoot->getItem('section', 'conf')
+    ->getItem('directive', 'sequence')
+    ->getContent();
+/**
+* Description for define
+*/
+define("SEQUENCE", $sequence);
+
+/**
+* Description for define
+*/
+define("WHERE", ID." IS NOT NULL");
+// $DB_fields are used for edit and updating contacts
+$DB_fields[] = array("name" => "id",            "title" => "id",            "type" => "hide");
+$DB_fields[] = array("name" => "create_date",   "title" => "Create Date",   "type" => "static");
+$DB_fields[] = array("name" => "fname",         "title" => "First Name",    "type" => "text");
+$DB_fields[] = array("name" => "lname",         "title" => "Last Name",     "type" => "text");
+if (TABLE == 'customer') {
+    $DB_fields[] = array("name" => "add1",       "title" => "Address",       "type" => "text");
+    $DB_fields[] = array("name" => "add2",      "title" => "Address 2",     "type" => "text");
+} else {
+    $DB_fields[] = array("name" => "company",       "title" => "Company Name",  "type" => "text");
+    $DB_fields[] = array("name" => "address",       "title" => "Address",       "type" => "text");
+    $DB_fields[] = array("name" => "address2",      "title" => "Address 2",     "type" => "text");
+}
+$DB_fields[] = array("name" => "city",          "title" => "City",          "type" => "text");
+$DB_fields[] = array("name" => "state",         "title" => "State",         "type" => "state");
+$DB_fields[] = array("name" => "zip",           "title" => "Zip",           "type" => "text");
+$DB_fields[] = array("name" => "phone",         "title" => "Phone",         "type" => "text");
+$DB_fields[] = array("name" => "fax",           "title" => "Fax",           "type" => "text");
+$DB_fields[] = array("name" => "email",         "title" => "Email",         "type" => "text");
+$DB_fields[] = array("name" => "mail_ok",       "title" => "Mail Ok?",      "type" => "radio");
+$DB_fields[] = array("name" => "interest",      "title" => "Interest",      "type" => "interest");
+$DB_fields[] = array("name" => "contact_type", "title" => "Contact Type", "type" => "drop", "drop" => $cType);
+
+// $fields are used for building the query page
+foreach ($DB_fields as $key=>$value) {
+    if ($value['type'] == "text" || $value['type'] == "state") {
+        $fields[$value['name']] = $value['title'];
+    } elseif ( $value['type'] == "radio") {
+        $boolean[$value['name']] = $value['title'];
+    } elseif ( $value['type'] == "drop") {
+        $dropdowns[$value['name']] = array('title' => $value['title'], 'drop' => $value['drop']);
+    }
+}
+
+$data['bailout'] .= "You are receiving this message because you have expressed an interest in ";
+$data['bailout'] .= "receiving specials and information from ".SITENAME.". If you do not ";
+$data['bailout'] .= "wish to receive future items of this nature, please reply to this e-mail ";
+$data['bailout'] .= "with the word \"CANCEL\" on the subject line. You will then be removed ";
+$data['bailout'] .= "from future mailings.<br>";
+$data['bailout'] .= "<a href=\"mailto:".OWNER_EMAIL."?subject=CANCEL\">".OWNER_EMAIL."</a><br>";
+?>
diff --git a/userArea/Contact/del_query.phtml b/userArea/Contact/del_query.phtml
new file mode 100755 (executable)
index 0000000..a7c5ad6
--- /dev/null
@@ -0,0 +1,20 @@
+<?php
+//$Id: del_query.phtml,v 1.2 2009/05/20 20:27:27 matrix Exp $
+include "../../setup.phtml";
+include "contact_setup.inc";
+
+$qs = "DELETE 
+          FROM         query_db 
+          WHERE        id = $id";
+
+if(!$DB->db_auto_exec($qs)) {
+    GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs,1);
+}
+GLM_TOOLBOX::html_header("Admin","Deleted","");
+?>
+<script lang="javascript">
+document.onload=window.opener.location.reload(1);
+</script>
+Query <?echo $id?> is Deleted
+<center><a href="" onClick="window.close();return(false);">Close This
+Window</a></center>
diff --git a/userArea/Contact/download.phtml b/userArea/Contact/download.phtml
new file mode 100755 (executable)
index 0000000..5dfc324
--- /dev/null
@@ -0,0 +1,224 @@
+<?php
+
+/**
+ * download.phtml
+ *
+ * gives admin user ability to download a csv file for import into
+ * another source.  Forces the save as dialog box.
+ * tested on ie6 ie7 and firefox.  $query_string is passed through to
+ * this page by a form.
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  Toolkit
+ * @package   PackageName
+ * @author    Steve Sutton <steve@gaslightmedia.com>
+ * @copyright 2009 Gaslight Media
+ * @license   Gaslight Media
+ * @version   CVS: $Id: download.phtml,v 1.3 2009/08/05 15:15:00 matrix Exp $
+ * @link      <>
+ */
+
+/**
+ * main site setup config file
+ */
+require_once "../../setup.phtml";
+
+/**
+ * main contact setup file
+ */
+require_once "contact_setup.inc";
+
+// check that the site sending this request is the same
+// as the base_url
+$base = str_replace("admin/Contact/list_contact.phtml",
+    "",
+    $_SERVER['HTTP_REFERER']
+);
+if ($base != MEDIA_BASE_URL) {
+    // redirect them
+    header("Location: index.phtml");
+}
+
+$delimiter = str_replace("comma", ",", $delimiter);
+$delimiter = str_replace("tab", "\t", $delimiter);
+$delimiter = str_replace("csv", ",", $delimiter);
+$delimiter = str_replace("pipe", "|", $delimiter);
+
+if ($_REQUEST['query_string']) {
+    /* Remove the old reports if they exsists */
+    if (is_file("report.csv")) {
+        unlink("report.csv");
+    }
+    if (is_file("report.tar.gz")) {
+        unlink("report.tar.gz");
+    }
+    if (is_file("report.zip")) {
+        unlink("report.zip");
+    }
+
+    if (!$fp = fopen("report.csv", "w")) {
+        html_error("Cant open report", 0);
+    }
+    $query_string = stripslashes($_REQUEST['query_string']);
+    $query_string = str_replace("SELECT " . ID . ",", "SELECT ", $query_string);
+    $query_string = str_replace(" FROM ",
+        ",contact_type,interest FROM ",
+        $query_string);
+
+    $dbh = Toolkit_Database::getInstance();
+
+    $res = $dbh->prepare($query_string);
+    $res->execute();
+    $total = $res->rowCount();
+       $headers =array();
+    $headerString = '';
+    if ($total > 0) {
+        for ($i = 0; $i < $total; ++$i) {
+            $result_string = "";
+            $row           = $res->fetch(PDO::FETCH_ASSOC);
+            $cConTypes     = array();
+            foreach ($row as $fieldName => $value) {
+                               if ($i == 0) {
+                    if (in_array($fieldName, array('contact_type', 'interest'))) {
+                        switch ($fieldName) {
+                        case 'contact_type' :
+                            foreach ($cType as $contactTypeName) {
+                                $headers[] = $contactTypeName;
+                            }
+                            break;
+                        case 'interest' :
+                            foreach ($int_array as $interesName) {
+                                $headers[] = $interesName;
+                            }
+                            break;
+                        }
+                    } else {
+                        $headers[] = $fieldName;
+                    }
+                }
+                // this section creates the contact_type part of the rows
+                // need to make this one a set number of fields for the contact
+                // types needed for all contacts
+                // so create count($cType) number of columns for this one field
+                if ($fieldName == 'contact_type') {
+                    $cConTypes = array();
+                    $st        = array();
+                    if (strstr($value, ":")) {
+                        $cConTypesStr = preg_replace("/^:|:$/",
+                            "",
+                            $value
+                        );
+                        $cConTypes    = explode(":", $cConTypesStr);
+                    }
+                    if (is_array($cType) && !empty($cType)) {
+                        foreach ($cType as $contactTypeId => $contactTypeName) {
+                            $st[]
+                            = (   is_array($cConTypes)
+                               && in_array($contactTypeId, $cConTypes))
+                                ? $contactTypeName
+                                : '';
+                            }
+                        $result_string .= implode("|", $st);
+                    }
+                    $result_string .= '|';
+                }
+                // this section creates the interest part of the rows
+                // need to make this one a set number of fields for the contact
+                // types needed for all contacts
+                // so create count($int_array) number of columns for this one field
+                else if ($fieldName == 'interest') {
+                    $iIntTypes = array();
+                    $st        = array();
+                    if (strstr($value, ":")) {
+                        $iIntTypesStr = preg_replace("/^:|:$/",
+                            "",
+                            $value);
+                        $iIntTypes    = explode(":", $iIntTypesStr);
+                    }
+                    if (   is_array($int_array)
+                        && !empty($int_array)
+                        ) {
+                        foreach ($int_array as $interestId => $interestName) {
+                            $st[]
+                            = (   is_array($iIntTypes)
+                               && in_array($interestId, $iIntTypes))
+                                ? $interestName
+                                : '';
+                            }
+                        $result_string .= implode("|", $st);
+                    }
+                    $result_string .= '|';
+                }
+                // this one deals with al the other fields
+                else if (!in_array($fieldName, array('contact_type', 'interest'))) {
+                    $result_string .= $value.'|';
+                }
+            }
+            $result_string = substr($result_string, 0, strlen($result_string)-1);
+            if ($i == 0) {
+                if ($csv) {
+                    $headerString = '"'.implode('","', $headers)."\"\n";
+                } else {
+                    $headerString = implode($delimiter, $headers)."\n";
+                }
+                fputs($fp, $headerString, strlen($headerString));
+            }
+            if ($csv) {
+                $result_string = str_replace("|", "\",\"", $result_string);
+                $result_string = "\"".$result_string."\"\n";
+            } else {
+                $result_string = str_replace("|", $delimiter, $result_string);
+                $result_string = $result_string."\n";
+            }
+            fputs($fp, $result_string, strlen($result_string));
+        }
+    }
+    if (!fclose($fp)) {
+        html_error("Cant close filepointer", 0);
+    }
+    chmod("report.csv", 0660);
+    $output = "report.csv";
+
+    if ($file == "gz") {
+        $output = "report.tar.gz";
+        exec("tar -czvf report.tar.gz report.csv 2>&1", $result_array, $result);
+        if ($result != 0) {
+            echo $result_array[0];
+            exit;
+        }
+        chmod("report.tar.gz", 0660);
+    }
+
+    if ($file == "zip") {
+        $output = "report.zip";
+        exec("zip report report.csv 2>&1", $result_array, $result);
+        if ($result != 0) {
+            echo $result_array[0];
+            exit;
+        }
+        chmod("report.zip", 0660);
+    }
+    if ($file == "rpt") {
+        $output = "report.csv";
+        chmod("report.csv", 0660);
+    }
+    if (ini_get('zlib.output_compression')) {
+        ini_set('zlib.output_compression', 'Off');
+    }
+    header("Content-Type: application/force-download\n");
+    /* Correction for the stupid MSIE thing */
+    if (strstr(getenv('HTTP_USER_AGENT'), 'MSIE')) {
+        header("Content-Disposition: inline; filename=\"$output\"");
+    } else {
+        header("Content-Disposition: attachment; filename=\"$output\"");
+    }
+    //header("Location: $output");
+    $fn = fopen($output, "r");
+    fpassthru($fn);
+    @fclose($fn);
+    exit();
+} else {
+    header("Location: list_contact.phtml");
+}
+?>
diff --git a/userArea/Contact/edit_autoresponse.phtml b/userArea/Contact/edit_autoresponse.phtml
new file mode 100755 (executable)
index 0000000..e9c927f
--- /dev/null
@@ -0,0 +1,102 @@
+<?php
+//$Id: edit_autoresponse.phtml,v 1.12 2010/08/11 18:16:41 matrix Exp $
+include "../../setup.phtml";
+include "contact_setup.inc";
+GLM_TOOLBOX::top("AutoReponse for Newsletter", HELP_BASE."response.phtml?key=edit+section");
+
+GLM_TOOLBOX::html_nav_table($nav, $navWidth);
+
+if ($id) {
+       $qs = "SELECT   id,subject,response
+               FROM    news_response
+               WHERE   id = $id";
+
+       if (!$res = $DB->db_exec($qs)) {
+               GLM_TOOLBOX::html_error(DB_ERROR_MSG.__LINE__, 1);
+       }
+       $row = $DB->db_fetch_array($res,0, PGSQL_ASSOC);
+} else {
+       $row['subject']  = '';
+       $row['response'] = '';
+}
+?>
+<script src=<?php echo MEDIA_BASE_URL."admin/verify.js";?>></script>
+<script type="text/javascript" src="<?php echo MEDIA_APP_BASE_URL;?>ckeditor/current/ckeditor.js"></script>
+<script language="javascript">
+<!--// closed source
+function mySubmit(o){
+       o.response.optional = true;
+       o.response.r = 'Description';
+       o.subject.optional = false;
+       o.subject.r = 'Subject';
+       return(verify(o))
+}
+var Newsletter =
+{
+    init: function()
+    {
+        if ($('#response').length) {
+            //  Only try to replace the textarea if the
+            //  CKEditor is compatible w/ the browser.
+            if (CKEDITOR.env.isCompatible) {
+                CKEDITOR.replace('response',
+                    {
+                        toolbar : 'Default',
+                        width : 570,
+                        height : 400,
+                        filebrowserImageBrowseUrl : '../../Toolkit/CKImages/browser.php?folder=1',
+                        filebrowserImageUploadUrl : '../../Toolkit/CKImages/controller.php?command=Upload',
+                                               filebrowserImageWindowWidth : '760',
+                                               filebrowserImageWindowHeight : '500'
+                    });
+            }
+        }
+    }
+};
+
+$(document).ready(Newsletter.init);
+
+//-->
+</script>
+<form id="form1" name="form1" enctype="multipart/form-data" action="update_autoresponse.phtml" method="POST">
+<table id="admin-edit-table">
+<?
+foreach ($row as $key => $value) {
+       switch ($key) {
+
+    case "id":
+        echo "<input type=\"hidden\" name=\"id\" value=\"$value\">";
+        break;
+
+    case "subject":
+        echo "<tr><td class=\"navtd\" align=\"right\">Subject:</td>";
+        GLM_TOOLBOX::text_box("subject", $value);
+        echo "</tr>";
+        break;
+
+    case "response":
+        echo "<tr><td class=\"navtd\" align=\"right\">Response:</td>";
+        echo '<td><textarea name="response" id="response" cols="60" rows="60">'.$value.'</textarea></td>';
+        echo "</tr>";
+        break;
+
+    default:
+    break;
+       }
+}
+echo '<tr><td></td><td nowrap="nowrap">';
+if ($id) {
+       ?>
+    <input type="submit" name="Command" value="Update">
+    <?php
+} else {
+       ?>
+    <input type="submit" name="Command" value="Insert">
+    <?php
+}
+echo '
+</td></tr>
+</table>
+</form>';
+GLM_TOOLBOX::footer();
+?>
diff --git a/userArea/Contact/edit_contact.php b/userArea/Contact/edit_contact.php
new file mode 100644 (file)
index 0000000..01a7f2f
--- /dev/null
@@ -0,0 +1,25 @@
+<?php
+require_once '../../setup.phtml';
+include "contact_setup.inc";
+$form = new Toolkit_Contacts_Admin_EditContact(
+    Toolkit_Database::getInstance(), 
+    'edit_contact'
+);
+$form->setConfig($contactRoot);
+$form->setTableName(
+    $contactRoot->getItem('section', 'conf')
+    ->getItem('directive', 'table')
+    ->getContent()
+);
+$form->setPrimaryKey(
+    $contactRoot->getItem('section', 'conf')
+    ->getItem('directive', 'primarykey')
+    ->getContent()
+);
+
+$form->configureForm($contactRoot);
+$formOutput = $form->toHtml();
+GLM_TOOLBOX::top("Updatable Listings (Add/Edit)", "help/contact.phtml?key=Edit");
+GLM_TOOLBOX::html_nav_table($nav, $navWidth);
+echo $formOutput;
+GLM_TOOLBOX::footer();
diff --git a/userArea/Contact/edit_group.php b/userArea/Contact/edit_group.php
new file mode 100644 (file)
index 0000000..93c4751
--- /dev/null
@@ -0,0 +1,99 @@
+<?php
+include "../../setup.phtml";
+include "contact_setup.inc";
+if ($_POST) {
+       $sub_oktogo = true;
+       if (empty($_POST['group'])) {
+               $sub_oktogo = false;
+       }
+       switch ($_POST['Command']) {
+    case 'Add' :
+        $qs = "INSERT INTO inq_group(name) VALUES('".$_POST['group']."')";
+        break;
+
+    case 'Edit' :
+        $qs = "UPDATE inq_group SET name = '".$_POST['group']."' WHERE id = ".$_POST['id'];
+        break;
+
+    case 'Delete' :
+        $qs = "DELETE FROM inq_group WHERE id = ".$_POST['id'];
+        break;
+
+    default :
+        unset($qs);
+        break;
+       }
+       if ($_POST['Command'] == 'Delete') {
+               $DB->db_exec($qs);
+               header('Location: list_groups.php');
+       } else if ($sub_oktogo && isset($qs)) {
+               $DB->db_exec($qs);
+               header('Location: list_groups.php');
+       }
+}
+?>
+<script type="text/javascript">
+function form_sub_check() {
+       var sub_oktogo = true;
+       var group = document.getElementById('group').value;
+       var groupBox = document.getElementById('group_box');
+
+       if (group == '') {
+               groupBox.className = "problem";
+               sub_oktogo = false;     
+               problems = '-- Name\n';
+       } else {
+               groupBox.className = '';
+    }
+
+       if (!sub_oktogo)
+               alert('Please give your new group a name before continuing');
+       //      Return whether the form will submit or not!
+       return sub_oktogo ? true : false;
+}
+</script>
+<style type="text/css">
+.problem {
+       background-color: #FCA9A4 !important;
+}
+</style>
+<?php
+GLM_TOOLBOX::top('Edit/Add Inquiry','');
+//     Adjust the nav for this page, add the Edit Groups page.
+if (is_array($nav) && array_key_exists('Contact Inquiry Fields', $nav)) {
+       $tmp = array('Inquiry Groups' => 'list_groups.php');
+       array_insert($nav, 'Contact Inquiry Fields', $tmp); 
+}
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+if (is_numeric($_GET['id'])) {
+       $query = 'SELECT * FROM inq_group WHERE id = '.$_GET['id'];
+       if ($data = $DB->db_auto_get_data($query)) {
+               $name = $data[0]['name'];
+               $id = $data[0]['id'];
+       }
+} else {
+       $name = '';
+}
+?>
+<form action="edit_group.php" method="POST" onSubmit="return form_sub_check();">
+       <table id="admin-edit-table">
+               <tr>
+                       <th>Group Name:</th>
+                       <td id="group_box" <?php echo ($_POST && !$sub_oktogo) ? 'class="problem"' : '';?>>
+                               <input type="text" name="group" id="group" value="<?php echo $name;?>">
+                               <input type="hidden" name="id" id="id" value="<?php echo $id;?>">
+                       </td>
+               </tr>
+               <tr>
+                       <td colspan="2" align="center">
+                               <?php if ($_GET['Command'] == "Edit") :?>
+                                       <input type="submit" name="Command" value="Edit">
+                                       <input type="submit" name="Command" value="Delete">
+                               <?php else :?>
+                                       <input type="submit" name="Command" value="Add">
+                               <?php endif;?>
+                       </td>
+               </tr>
+       </table>
+</form>
+<?php GLM_TOOLBOX::footer();?>
diff --git a/userArea/Contact/edit_inquiry.phtml b/userArea/Contact/edit_inquiry.phtml
new file mode 100755 (executable)
index 0000000..450a50e
--- /dev/null
@@ -0,0 +1,129 @@
+<?php
+require_once "../../setup.phtml";
+require_once "contact_setup.inc";
+GLM_TOOLBOX::top('Edit/Add Inquiry','');
+?>
+<script type="text/javascript">
+    $(document).ready(function(){
+        $('#deleteButton').click(function(){
+            $('input[name="xCommand"]').val('Delete');
+        });
+    });
+function form_sub_check()
+{
+    var submitButton = $('input[name="xCommand"]').val();
+    if (submitButton == 'Delete') {
+        return true;
+    }
+       var sub_oktogo = true;
+       var problems = '';
+       var header = $("#header").val();
+       var headerBox = $("#header_box");
+    var group = $("#groupid").val();
+    var groupBox = $("#group_box");
+    var newGroup = $("#new_group").val();
+    
+       if (header == '') {
+               headerBox.addClass("problem");
+               sub_oktogo = false;     
+               problems = '-- Name\n';
+       } else {
+               headerBox.removeClass("problem");
+    }
+       if ((group == undefined || group == 0) && newGroup == '') {
+               groupBox.addClass("problem");
+               sub_oktogo = false;
+               problems += '-- Group\n';
+       } else {
+               groupBox.removeClass("problem");
+    }
+       if (!sub_oktogo) {
+               alert('You have problems on your form!\nPlease carefully review the following and re-submit your form.\n\n' + problems);
+    }
+    // Return whether the form will submit or not!
+       return sub_oktogo ? true : false;
+}
+</script>
+<style type="text/css">
+.problem {
+       background-color: #FCA9A4 !important;
+}
+</style>
+<?php
+//     Adjust the nav for this page, add the Edit Groups page.
+if (is_array($nav) && array_key_exists('Contact Inquiry Fields', $nav)) {
+    $tmp = array('Inquiry Groups' => 'list_groups.php');
+    array_insert($nav, 'Contact Inquiry Fields', $tmp); 
+}
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+if (is_numeric($_GET['id'])) {
+    $query = "SELECT * FROM contact_inq WHERE id = $id";
+    if ($data = $DB->db_auto_get_data($query)) {
+        $header                        = $data[0]['header'];
+        $description   = $data[0]['description'];
+        $pos                   = $data[0]['pos'];
+        $groupid               = $data[0]['groupid'];
+    }
+} else {
+    $header                    = '';
+    $description       = '';
+    $groupid           = '';
+}
+$query = "SELECT * FROM inq_group ORDER BY name;";
+if ($gData = $DB->db_auto_get_data($query)) {
+    $group_sel = '<select id="groupid" name="groupid">';
+    $group_sel .= '<option value="">New Group - &gt;&gt;</option>';
+    foreach ($gData as $gRow) {
+        $group_sel .= '<option value="'.$gRow['id'].'"';
+        if( $groupid && $gRow['id'] == $groupid )
+        {
+            $group_sel .= ' selected';
+        }
+        $group_sel .= '>'.$gRow['name'];
+        $group_sel .= '</option>';
+    }
+    $group_sel .= '</select>';
+}
+?>
+<form action="update_inquiry.phtml" method="POST" onSubmit="return form_sub_check();">
+    <input type="hidden" name="old_groupid" value="<?php echo $groupid;?>" />
+    <table id="admin-edit-table">
+        <tr>
+            <th>Name:</th>
+            <td id="header_box">
+                <input type="text" name="header" id="header" size="50" value="<?echo $header?>">
+                <input type="hidden" name="id" value="<?echo $id?>">
+            </td>
+        </tr>
+        <?
+        echo '<input type="hidden" name="oldpos" value="'.$pos.'">';
+    ?> 
+    <tr>
+        <th>Group:</th>
+        <td id="group_box">
+        <?php echo $group_sel;?>
+        <input type="text" id="new_group" name="new_group" value="" />
+        </td>
+    </tr>
+    <tr>
+        <td colspan=2 align=center>
+            <input type="hidden" name="xCommand" value="" />
+<?php
+if ($Command == "Edit") {
+    ?>
+    <input type="submit" name="Command" value="Edit">
+    <input type="submit" id="deleteButton" name="Command" value="Delete">
+    <?php
+} else {
+?>
+    <input type="submit" name="Command" value="Add">
+<?php
+}
+?>
+        </td>
+        </tr>
+    </table>
+</form>
+<?php
+GLM_TOOLBOX::footer();
+?>
diff --git a/userArea/Contact/emails.php b/userArea/Contact/emails.php
new file mode 100644 (file)
index 0000000..86695f7
--- /dev/null
@@ -0,0 +1,36 @@
+<?php
+require_once '../../setup.phtml';
+require_once BASE . 'classes/class_db.inc';
+require_once 'contact_setup.inc';
+$DB = new GLM_DB();
+$query = "select * from news_response order by id;"; 
+$data  = $DB->db_auto_get_data( $query );
+GLM_TOOLBOX::top( "Email HTML Newsletters", "");
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+$out = '<table id="admin-list-table">
+       <tr><td colspan="2" align="center">
+                       <form name="add" action="edit_autoresponse.phtml" method="post">
+                               <button name="command" onClick="add.submit()">Add HTML EMAIL</button>
+       </td></tr>
+       <tr>
+               <th>Function:</th>
+               <th>Subject:</th>
+               <th>Last Update:</th>
+               <th> &nbsp; </th>
+       </tr>';
+       
+if (is_array($data)) {
+       foreach ($data as $key => $val) {
+               $out .= '<tr>
+                       <td><a href="edit_autoresponse.phtml?id='.$val["id"].'">[Edit]</a>&nbsp;
+                               <a href="view_newsletter.phtml?id='.$val["id"].'">[View]</a></td>
+                       <td>'.$val["subject"].'</td>
+                       <td>'.$val["last_update"].'</td>
+                       <td><a href="update_autoresponse.phtml?Command=Delete&amp;id='.$val["id"].'" onClick="return(confirm(\'This will delete the Email Newsletter!\n\nAre you sure?\'))">[Delete]</a></td>
+               </tr>';
+       }
+}
+$out .= '</table>';
+echo $out;
+GLM_TOOLBOX::footer();
+?>
diff --git a/userArea/Contact/form.js b/userArea/Contact/form.js
new file mode 100755 (executable)
index 0000000..0bbabf0
--- /dev/null
@@ -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('<OPTION VALUE="',href,'">',text,'<\/OPTION>');
+}
diff --git a/userArea/Contact/help/contact.phtml b/userArea/Contact/help/contact.phtml
new file mode 100755 (executable)
index 0000000..bdec6d7
--- /dev/null
@@ -0,0 +1,146 @@
+<HTML>
+<HEAD>
+<TITLE>Help</TITLE>
+</HEAD>
+<BODY BGCOLOR="#FFFFFF" BACKGROUND="../../help/helpbg.gif" TEXT="#000000" LINK="#FF0000" VLINK="#800000" ALINK="#FF00FF" BACKGROUND="?">
+<FONT FACE="ms sans serif,arial,helvetica" SIZE=2 COLOR="#444444">
+<H4 align="center">Contact Help</H4>
+<hr>
+<?
+switch ($key) {
+       case "search":
+       ?>
+<h4 align="center">Contact Database Search</h4>
+
+<P>
+In this page you will start to build your query to the contact database.
+</p>
+<p>
+<big><b>Search:</b></big>
+</p>
+<p>
+<b>Search records for:</b>
+</p>
+<p>Here is where you will enter any keywords to use in the search.  You must
+enter in something in the "Search records for" box.  You may use more than one
+word (ie.) Sam Field.</p>
+<p><font color=red>HINT:</font>To help search use wildcards!</p>
+<p>? optional space<br>
+* optional spaces<br>
++ at least one space
+. will match anything<br>
+</p>
+<p><font color=green>NOTE:</font>Leaving this fields blank will select all
+contacts.  You can leave this blank and choose "Mail OK" true to get all
+contacts that allow emails.</p>
+<p><b>Search Where in fields:</b></p>
+<p>Tells the database to Search "Anywhere", "Beginning", or "Ending" of the
+fields to be searched.</p>
+<p><b>In Fields:</b></p>
+<p>Select from "In Fields" box.  This determines what fields to look in for
+this search.</p>
+<p><font color=red>HINT</font>
+If you want to select more than one field to search in hold down the 'Ctrl' key while clicking on the selection to select or
+deselect it from the list.</p>
+<p><font color=red>HINT</font>
+You can use the "All" and "None" buttons to help you save time.  This will
+select all or none of the fields in the boxes.</p>
+<p><b>Search Type:</b></p>
+<p>Select the type of search you want (ie.) an "Exact string" search will return
+only those fields which match the "Search records" for string exactly as compared
+to "Or" which will return any field that match any words you place into "Search
+records for"</p>
+<p><b>Case Sensitivity:</b></p>
+<p>This will turn "On" and "Off" the case sensitivity.
+(ie.)If you leave it "Off" and enter "bob" it will return anything like
+"bob","BOB","Bob","BOb","boB",or "BoB" turned "On" will match only "bob".</p>
+
+<p>
+<big><b>Output of records</b></big>
+</p>
+<p><b>Output Fields:</b></p>
+<p>Select from "Output Fields" box.  This determines what fields will be in the
+output of this search.</p>
+<p><font color=red>HINT</font>
+You can use the "All" and "None" buttons to help you save time.  This will
+select all or none of the fields in the boxes.</p>
+<p><font color=red>HINT</font>
+If you want to select more than
+one Output field hold down the 'Ctrl' key while clicking on the selection to select or
+deselect it from the list.</p>
+<p><b>File Output:</b></p>
+<p>Select from here if you wish to download a file with the results of this
+search.  The file will built "On the Fly" so you can download it.</p>
+<p><font color=green>NOTE:</font>The text file is output as report.doc.  This
+is only a text file.
+</p>
+<p><b>Delimiter:</b></p>
+<p>This determines what separates the fields in your file.</p>
+
+<?
+       break;
+
+       case "List":
+       ?>
+<h4 align="center">List Contacts</h4>
+<P>
+This page is for listing the results of your query.  You can download files if
+you have selected a file type or edit and delete the contact found.
+</p>
+<p><b>[Edit]</b></p>
+<p>Link to contact edit page.</p>
+
+<p><b>[Delete]</b></p>
+<p>Link to Delete Contact.</p>
+
+<p><big><b>Download Files</b></big></p>
+<p>If you see this then there is a file you can download.
+Click on the file and you can download it.</p>
+<?
+       break;
+
+       case "Edit":
+       ?>
+<h4 align="center">Edit a Contact</h4>
+<P>
+This page is for editing and modifying an existing Contact in the database.
+When editing is complete, click on the "Submit Query" button. The database will
+be updated, and you will be directed back to the "List Contacts" page.
+</p>
+<p>
+
+<p>
+<b>Submit Query</b>
+</p>
+<p>When you have made the changes you want to the Contact,
+you can click "Submit Query." This will update the information about the
+Contact in the database.
+</p>
+<?
+       break;
+
+       case "Add":
+       ?>
+<h4 align="center">Add an Contact</h4>
+<P>
+This page is for Adding Contacts in the database.
+When form is complete, click on the "Submit Query" button. The database will
+be updated, and you will be directed back to the "List Contacts" page.
+</p>
+
+<p>
+<b>Submit Query</b>
+</p>
+<p>When you have made the changes you want to the Contact,
+you can click "Submit Query." This will update the information about the
+Contact in the database.
+</p>
+<?
+       break;
+
+}
+?>
+<BR CLEAR=ALL>
+<CENTER><A HREF="" onClick = "window.close('self');"><IMG SRC="../../help/closewindow.gif" border=0></A></CENTER>
+</BODY>
+</HTML>
diff --git a/userArea/Contact/htmlarea.css b/userArea/Contact/htmlarea.css
new file mode 100644 (file)
index 0000000..23bdf7d
--- /dev/null
@@ -0,0 +1,180 @@
+.htmlarea { background: #fff; }
+
+.htmlarea .toolbar {
+  cursor: default;
+  background: ButtonFace;
+  padding: 1px 1px 2px 1px;
+  border: 1px solid;
+  border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
+}
+.htmlarea .toolbar table { font-family: tahoma,verdana,sans-serif; font-size: 11px; }
+.htmlarea .toolbar img { border: none; }
+.htmlarea .toolbar .label { padding: 0px 3px; }
+
+.htmlarea .toolbar .button {
+  background: ButtonFace;
+  color: ButtonText;
+  border: 1px solid ButtonFace;
+  padding: 1px;
+  margin: 0px;
+}
+.htmlarea .toolbar .buttonHover {
+  border: 1px solid;
+  border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
+}
+.htmlarea .toolbar .buttonActive, .htmlarea .toolbar .buttonPressed {
+  padding: 2px 0px 0px 2px;
+  border: 1px solid;
+  border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
+}
+.htmlarea .toolbar .buttonPressed {
+  background: ButtonHighlight;
+}
+.htmlarea .toolbar .indicator {
+  padding: 0px 3px;
+  overflow: hidden;
+  width: 20px;
+  text-align: center;
+  cursor: default;
+  border: 1px solid ButtonShadow;
+}
+
+.htmlarea .toolbar .buttonDisabled { background-color: #aaa; }
+
+.htmlarea .toolbar .buttonDisabled img {
+  filter: alpha(opacity = 25);
+  -moz-opacity: 25%;
+}
+
+.htmlarea .toolbar .separator {
+  position: relative;
+  margin: 3px;
+  border-left: 1px solid ButtonShadow;
+  border-right: 1px solid ButtonHighlight;
+  width: 0px;
+  height: 16px;
+  padding: 0px;
+}
+
+.htmlarea .toolbar .space { width: 5px; }
+
+.htmlarea .toolbar select { font: 11px Tahoma,Verdana,sans-serif; }
+
+.htmlarea .toolbar select,
+.htmlarea .toolbar select:hover,
+.htmlarea .toolbar select:active { background: FieldFace; color: ButtonText; }
+
+.htmlarea .statusBar {
+  border: 1px solid;
+  border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
+  padding: 2px 4px;
+  background-color: ButtonFace;
+  color: ButtonText;
+  font: 11px Tahoma,Verdana,sans-serif;
+}
+
+.htmlarea .statusBar .statusBarTree a {
+  padding: 2px 5px;
+  color: #00f;
+}
+
+.htmlarea .statusBar .statusBarTree a:visited { color: #00f; }
+.htmlarea .statusBar .statusBarTree a:hover {
+  background-color: Highlight;
+  color: HighlightText;
+  padding: 1px 4px;
+  border: 1px solid HighlightText;
+}
+
+
+/* Hidden DIV popup dialogs (PopupDiv) */
+
+.dialog {
+  color: ButtonText;
+  background: ButtonFace;
+}
+
+.dialog .content { padding: 2px; }
+
+.dialog, .dialog button, .dialog input, .dialog select, .dialog textarea, .dialog table {
+  font: 11px Tahoma,Verdana,sans-serif;
+}
+
+.dialog table { border-collapse: collapse; }
+
+.dialog .title {
+  background: #008;
+  color: #ff8;
+  border-bottom: 1px solid #000;
+  padding: 1px 0px 2px 5px;
+  font-size: 12px;
+  font-weight: bold;
+  cursor: default;
+}
+
+.dialog .title .button {
+  float: right;
+  border: 1px solid #66a;
+  padding: 0px 1px 0px 2px;
+  margin-right: 1px;
+  color: #fff;
+  text-align: center;
+}
+
+.dialog .title .button-hilite { border-color: #88f; background: #44c; }
+
+.dialog button {
+  width: 5em;
+  padding: 0px;
+}
+
+.dialog .buttonColor {
+  padding: 1px;
+  cursor: default;
+  border: 1px solid;
+  border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
+}
+
+.dialog .buttonColor-hilite {
+  border-color: #000;
+}
+
+.dialog .buttonColor .chooser, .dialog .buttonColor .nocolor {
+  height: 0.6em;
+  border: 1px solid;
+  padding: 0px 1em;
+  border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
+}
+
+.dialog .buttonColor .nocolor { padding: 0px; }
+.dialog .buttonColor .nocolor-hilite { background-color: #fff; color: #f00; }
+
+.dialog .label { text-align: right; width: 6em; }
+.dialog .value input { width: 100%; }
+.dialog .buttons { text-align: right; padding: 2px 4px 0px 4px; }
+
+.dialog legend { font-weight: bold; }
+.dialog fieldset table { margin: 2px 0px; }
+
+.popupdiv {
+  border: 2px solid;
+  border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
+}
+
+.popupwin {
+  padding: 0px;
+  margin: 0px;
+}
+
+.popupwin .title {
+  background: #fff;
+  color: #000;
+  font-weight: bold;
+  font-size: 120%;
+  padding: 3px 10px;
+  margin-bottom: 10px;
+  border-bottom: 1px solid black;
+  letter-spacing: 2px;
+}
+
+form { margin: 0px; border: none; }
diff --git a/userArea/Contact/index.phtml b/userArea/Contact/index.phtml
new file mode 100755 (executable)
index 0000000..fea8093
--- /dev/null
@@ -0,0 +1,315 @@
+<?php
+session_start();
+require_once "../../setup.phtml";
+require_once "contact_setup.inc";
+error_reporting();
+if (isset($mailout)) {
+    unset($_SESSION['mailout']);
+       //session_unregister("mailout");
+}
+if (isset($_SESSION['sess_vars'])) {
+       extract($_SESSION['sess_vars']);
+    unset($_SESSION['sess_vars']);
+       //session_unregister("sess_vars");
+}
+$qs = "SELECT  count(*) as total
+          FROM         ".TABLE;
+if (TABLE == CUSTOMER_TABLE) {
+       $qs .= " WHERE (fname != '-Guest-' OR fname is null)";
+}
+$res = $DB->db_auto_get_data($qs);
+$total = $res[0]['total'];
+GLM_TOOLBOX::top("Contact Database","help/contact.phtml?key=search","SteveContactsDatabase_1.0");
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+?>
+<table id="admin-list-table">
+  <tr>
+    <td colspan=4>
+       There
+       <?php
+       if ($total < 1 ) {
+               echo " No records";
+       } elseif ($total > 1) {
+               echo "are $total contacts";
+       } else {
+               echo "is $total contact";
+       }
+       ?> in the database.
+       </td>
+  </tr>
+  <tr>
+    <th colspan=4 class="theader">
+       Search:
+    </th>
+  </tr>
+  <tr>
+    <td colspan=4>
+       <b>Search records for:</b><br>
+       </td>
+  </tr>
+  <tr>
+  <td colspan=4>
+  <form name="search" action="query_contact.phtml" method="POST" onSubmit="
+       var msg = '';
+       var errors = '';
+       var ping = 0;
+       var all = 0;
+       this.fvalue.value = '';
+       this.rfvalue.value = '';
+       this.rdvalue.value = '';
+
+       if(this.search.value == '') {
+               all++;
+       }
+
+       for(var i = 0;i<4;i++) {
+               if(this.search_type.options[i].selected){
+                       ping++;
+               }
+       }
+
+       if(all == 0) {
+               if(ping == 0) {
+                       errors += '-You must select a search type\n';
+               }
+       }
+
+       for(var i=0;i<<?echo count($fields)?>;i++) {
+               if(this.ifields.options[i].selected) {
+                       this.fvalue.value += ':' + this.ifields.options[i].value;
+               }
+       }
+
+       for(var i=0;i<<?echo count($fields)?>;i++) {
+               if(this.return_fields.options[i].selected) {
+                       this.rfvalue.value += ':' + this.return_fields.options[i].value;
+               }
+       }
+
+       for(var i=0;i<1;i++) {
+               if(this.dates.options[i].selected) {
+                       this.rdvalue.value += ':' + this.dates.options[i].value;
+               }
+       }
+
+       if(all == 0) {
+               if(this.fvalue.value == '') {
+                       errors += '-You must select at least one field to search in\n';
+               }
+       }
+
+        if(this.rfvalue.value == '') {
+               errors += '-You must select at least one field for output\n';
+       }
+
+       if(all == 1) {
+               if(errors == '') {
+                       return(true);
+               }
+       }
+
+       if(errors == '') {
+               return(true);
+       } else {
+               msg += '_______________________________________\n\n';
+               msg += 'The form was not submitted please check\n';
+               msg += 'the following and resubmit\n\n';
+               msg += errors + '\n\n';
+               msg += '_______________________________________\n\n';
+
+               alert(msg);
+               return(false);
+       }
+  ">
+  <input name="search" value="<?echo stripslashes($search)?>" size=40>
+  <input type="submit" name="Submit Query">
+  </td>
+  </tr>
+  <tr>
+    <th colspan=4 class="theader">
+       Search Dates Ranges
+    </th>
+  </tr>
+  <tr>
+         <td align="left" colspan=4 nowrap>
+                 <div style="float:left;width:240px;height:35px;">Created From:<br> <?echo $c_date_from?></div>
+                 <div style="float:left;width:240px;height:35px;">Created To:<br> <?echo $c_date_to?></div>
+         </td>
+  </tr>
+  <tr>
+    <td class="small" valign=top>
+       <b>In Fields:</b><br>
+       <select name="ifields" multiple size=8>
+       <?foreach($fields as $key2=>$value2) {?>
+       <option value="<?echo $key2?>" <?=(strstr($fvalue,$key2))?"selected":""?>><?echo $value2?>
+       <?}?>
+       </select>
+       <br>
+       <label for="in-all"><input type="radio" id="in-all" name="a" onClick="
+       for(var i=0;i<<?echo count($fields)?>;i++) {
+               this.form.ifields.options[i].selected=1;
+       }
+       ">All</label>
+       <label for="in-none"><input type="radio" id="in-none" name="a" onClick="
+       for(var i=0;i<<?echo count($fields)?>;i++) {
+               this.form.ifields.options[i].selected=0;
+       }
+       ">None</label>
+       </td>
+       <td valign=top class="small" nowrap>
+      <b>Search Where:</b><br>
+         <select name="alter">
+         <option value="0" <?=($alter=="0")?"selected":""?>>Anywhere
+         <option value="1" <?=($alter=="1")?"selected":""?>>Begining
+      <option value="2" <?=($alter=="2")?"selected":""?>>Ending
+         </select><br>
+       <input type="hidden" name="fvalue">
+       <?php
+       if (is_array($boolean)) {
+               foreach ($boolean as $bool_key => $bool_val) {
+                       echo '<br>
+                               <b>'.$bool_val.'</b><br>';
+                       echo search_bool($bool_key, ${$bool_key});
+               }
+       }
+       if (is_array($dropdowns)) {
+               foreach ($dropdowns as $drop_key => $drop_row) {
+                       echo '<br>
+                               <b>'.$drop_row['title'].'</b>';
+                       echo '<br>';
+                       if( is_array( $drop_row['drop'] ) ) {
+                               echo GLM_TOOLBOX::build_picklist( $drop_key.'[]', $drop_row['drop'], ${$drop_key}, 'multiple', 0, null, 5 );
+                       }
+               }
+       }
+       echo '</td><td valign=top width=25%>';
+?>
+       <br><b>Search Type:</b><br>
+  <select name="search_type" size=4>
+  <option value="1" <?=(!isset($search_type) || $search_type=="1")?"selected":""?>>Exact string
+  <option value="2" <?=($search_type=="2")?"selected":""?>>And
+  <option value="3" <?=($search_type=="3")?"selected":""?>>Or
+  <option value="4" <?=($search_type=="4")?"selected":""?>>Not
+  </select>
+       </td>
+      <td valign=top class=small width=25%>
+      <b>Case Sensitivity:</b><br>
+      <select name="case">
+      <option value="ON" <?=($case == "ON")?"selected":""?>>On
+      <option value="OFF" <?=(!isset($case) || $case == "OFF")?"selected":""?>>Off
+      </select><br>
+         </td>
+         </tr>
+         <tr>
+         <td colspan="4"> &nbsp;
+<?php
+    $sql = "
+      SELECT contact_inq.*, inq_group.name as group
+        FROM contact_inq
+             LEFT OUTER JOIN inq_group
+               ON (contact_inq.groupid = inq_group.id)
+       WHERE inq_group.id != 6
+    ORDER BY groupid, pos";
+
+    $interests = array();
+    $intData = $DB->db_auto_get_data($sql);
+    foreach ($intData as $row) {
+        $interests[$row['group']][$row['id']] = $row['header'];
+    }
+
+    foreach ($interests as $i => $j) {
+        echo '<fieldset>';
+        echo '<legend>';
+        echo $i;
+        echo '</legend>';
+        foreach ($j as $k => $v) {
+            echo '<label class="glmCheckBox">';
+            echo '<input type="checkbox" name="cols[]" value="'.$k.'" ';
+            if (   is_array($cols)
+                && in_array($data['id'], $cols)) {
+                echo " checked";
+                       }
+            echo '>';
+            echo $v;
+            echo '</label>';
+                                       }
+        echo '</fieldset>';
+    }
+?>
+      </td>
+       </tr>
+  <tr>
+    <th colspan=4>
+       Output of records:
+    </th>
+  </tr>
+  <tr>
+    <td class="small" valign=top>
+       <b>Output Fields:</b><br>
+       <select name="return_fields" multiple size=8>
+       <?foreach($fields as $key2=>$value2) {?>
+       <option value="<?echo $key2?>" <?=(strstr($rfvalue,$key2))?"selected":""?>><?echo $value2?>
+       <?}?>
+       </select>
+       <br>
+       <input type="hidden" name="rfvalue">
+       <label for="out-all"><input type="radio" id="out-all" name="a" onClick="
+       for(var i=0;i<<?echo count($fields)?>;i++) {
+               this.form.return_fields.options[i].selected=1;
+       }
+       for(var i=0;i<<?echo ($p_date_from)?"3":"1";?>;i++) {
+               this.form.dates.options[i].selected=1;
+       }
+       ">All</label>
+       <label for="out-none"><input id="out-none" type="radio" name="a" onClick="
+       for(var i=0;i<<?echo count($fields)?>;i++) {
+               this.form.return_fields.options[i].selected=0;
+       }
+       for(var i=0;i<<?echo ($p_date_from)?"3":"1";?>;i++) {
+               this.form.dates.options[i].selected=0;
+       }
+       ">None</label>
+  </td>
+  <td class="small" valign=top>
+       <input type="hidden" name="rdvalue" value="">
+    <b>Output fields (Dates):</b>
+       <select name="dates" multiple size=3>
+       <option value="create_date" <?=(strstr($dates,"create_date"))?"selected":""?>>Created Date
+       <?if($p_date_from)
+       {?>
+  <option value="purch_date" <?=(strstr($dates,"purch_date"))?"selected":""?>>Last Purchase Date
+  <?}
+  if($a_date_from)
+  {?>
+  <option value="access_date" <?=(strstr($dates,"access_date"))?"selected":""?>>Last Access Date
+  <?}?>
+       </select>
+  </td>
+  <td class="small" valign=top width=25%>
+  <b>File output:</b><br>
+  <select name="file" size=4>
+  <option value="" <?=(!isset($file) || $file == "")?"selected":""?>>No File
+  <option value="zip" <?=($file=="zip")?"selected":""?>>zip file
+  <option value="gz" <?=($file=="gz")?"selected":""?>>tar.gz(tar ball)
+  <option value="rpt" <?=($file=="rpt")?"selected":""?>>text file
+  </select>
+  </td>
+  <td valign=top class=small width=25%>
+  <b>Delimiter:</b><br>
+  <select name="delimiter" size=4>
+  <option value="tab" <?=($delimiter=="tab")?"selected":""?>>TAB
+  <option value="comma" <?=($delimiter=="comma")?"selected":""?>>Comma
+  <option value="csv" <?=($delimiter=="csv")?"selected":""?>>CSV
+  <option value="pipe" <?=($delimiter=="pipe")?"selected":""?>>Pipe
+  </select>
+  </td>
+  </tr>
+  <tr>
+    <td colspan="4" align="center">
+    <input type="submit" name="Submit Query">
+    </td>
+  </tr>
+  </table>
+<?php
+GLM_TOOLBOX::footer();
+?>
diff --git a/userArea/Contact/list_contact.phtml b/userArea/Contact/list_contact.phtml
new file mode 100755 (executable)
index 0000000..c253eb3
--- /dev/null
@@ -0,0 +1,285 @@
+<?php
+include "../../setup.phtml";
+include "contact_setup.inc";
+if (!$start) {
+       $start = 0;
+}
+
+if ($postquery) {
+       $query_string = $postquery;
+}
+$checkqs = "SELECT     count(*) as contacts
+                   FROM        ".TABLE;
+
+if (!$checkres = $DB->db_auto_get_data($checkqs)) {
+       GLM_TOOLBOX::html_error(DB_ERROR_MSG.__LINE__.$checkqs,1);
+}
+
+$numcontacts = $checkres[0]['contacts'];
+if ($numcontacts == 0) {
+       GLM_TOOLBOX::html_error("There are no contacts in the database",1);
+}
+
+if(!isset($back) && !isset($query_string)) {
+       $query = "SELECT        ".ID.",*
+                         FROM          ".TABLE."
+                         WHERE         ".WHERE."
+                         ORDER BY      lname,fname";
+
+       $query = addslashes($query);
+       $qs = "SELECT   id
+                  FROM         query_db
+                  WHERE        query_name = '(current)'";
+
+       if (!$res = $DB->db_exec($qs)) {
+               GLM_TOOLBOX::html_error(DB_ERROR_MSG.__LINE__.$qs,1);
+    }
+
+       if ($DB->db_numrows($res)==0) {
+        $qs = "INSERT
+               INTO    query_db
+                        (query,query_name)
+               VALUES  ('$query','(current)')";
+       } else {
+               $id = $res->fetchColumn();
+               $qs = "UPDATE   query_db
+                          SET          query = '$query',
+                                       file = '',
+                                       delimiter = ''
+                          WHERE        id = $id";
+       }
+       if (!$res = $DB->db_exec($qs)) {
+               html_error(DB_ERROR_MSG.__LINE__.$qs,1);
+    }
+       unset($qs);
+}
+
+if ($delimiter == "csv") {
+       $csv = TRUE;
+}
+
+if (isset($query_string) && $query_string) {
+       $query_string = strtr($query_string,"\n"," ");
+       $query_string = strtr($query_string,"\t"," ");
+       $query_string = stripslashes($query_string);
+       $qs = $query_string;
+} elseif ($query_no) {
+       $qs = "select query from query_db where id = $query_no";
+       $queryres = $DB->db_exec($qs);
+       if ($queryres->rowCount() == 0) {
+               $qs = "SELECT   ".ID.",*
+                         FROM          ".TABLE."
+                         WHERE         ".WHERE."
+                         ORDER BY      lname,fname";
+       } else {
+               $qs = $queryres->fetchColumn();
+       }
+} else {
+       $queryqs = "SELECT      query
+                               FROM    query_db
+                               WHERE   query_name LIKE '(current)'";
+       $queryres = $DB->db_exec($queryqs);
+       if ($queryres->rowCount() == 0) {
+               $qs = "SELECT   ".ID.",*
+                         FROM          ".TABLE."
+                         WHERE         ".WHERE."
+                         ORDER BY      lname,fname";
+       } else {
+               $qs = $queryres->fetchColumn();
+       }
+}
+
+GLM_TOOLBOX::top("List Contacts","help/contact.phtml?key=List");
+?>
+<script src="wm.js"></script>
+<script src="msg.js"></script>
+<table id="admin-list-table">
+<?php
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+if (NEWSLETTER) {
+$mquery = "select id,subject,last_update from news_response order by last_update desc;";
+       $mres = $DB->db_exec($mquery);
+    $mailout = array();
+       while ($mrow = $mres->fetch())
+       {
+               $mailout[] = $mrow;
+       }
+?>
+<script type="text/javascript">
+       var remind;
+       remind = 'This will mailout the Newsletter\n';
+</script>
+<table id="admin-edit-table" style="width:500px;">
+  <tr>
+    <th colspan=2>
+       <form action="mailout.phtml" method="POST" onSubmit="return(confirm(remind));">
+               <select name="mail_id" style="width:100%;"><?
+       unset($mrow);
+       foreach ($mailout as $mrow) {
+               echo '<option value="'.$mrow["id"].'">';
+               echo ' '.htmlspecialchars(strip_tags($mrow["subject"]));
+               echo ' (Updated: '.$mrow["last_update"].')';
+               echo '</option>';
+       }
+       ?>
+         </select>
+         <input type="hidden" name="postmail" value="<?echo $qs?>">
+         <input type="submit" value="Mail Out the Newsletter">
+       </form>
+       </th>
+</tr>
+<?php }
+$totalqs = substr_replace($qs," count(*) as total FROM ",strpos($qs,"SELECT")+7,strpos($qs,"FROM")-3);
+if (strpos($totalqs,"ORDER BY")!=0) {
+       $totalqs = substr_replace($totalqs,"",strpos($totalqs,"ORDER"));
+}
+if (!$totalres = $DB->db_exec($totalqs)) {
+       GLM_TOOLBOX::html_error(DB_ERROR_MSG.__LINE__.$totalqs,1);
+}
+if ($totalres->rowCount() == 0) {
+       $totalnum = 0;
+} else {
+       $totalnum = $totalres->fetchColumn();
+}
+$qs .= " LIMIT ".ENTRIES_PER_PAGE." OFFSET ".$start;
+$res = $DB->db_exec($qs);
+?>
+<tr>
+  <td colspan="2"><?php echo $totalnum?>Result(s)
+<?php
+if ($_REQUEST['Action']) {
+    echo '<div style="background-color:green;color:white;padding:5px;">'.$_REQUEST['Action'].' Successfully!</div>';
+}
+?></td>
+</tr>
+<?php
+if(!$res) GLM_TOOLBOX::html_error(DB_ERROR_MSG.__LINE__.$qs,1);
+// What page are you on?
+if ($start==0) {
+       $page == 1;
+} else {
+       $page = ($start / ENTRIES_PER_PAGE) + 1;
+}
+$totalpages = floor($totalnum / ENTRIES_PER_PAGE);
+$totalpages++;
+
+$result_string = "";
+$num = $DB->db_numrows($res);
+if (!$start) {
+       $start = 0;
+}
+$begin  = 0;
+$ending = $num;
+
+$stuff = "query_string=".urlencode($query_string)."&file=".$file."&delimiter=".$delimiter."&csv=".$csv;
+// for paging results get a first page and last page link also
+// first page is easy use 0
+$first = "<a href=\"list_contact.phtml?".$stuff."&start=0\">FIRST</a> - ";
+// last page use total pages
+$lastpage = " - <a href=\"list_contact.phtml?".$stuff."&start=".( ( $totalpages - 1 ) * ENTRIES_PER_PAGE )."\">Last</a>";
+if ($totalnum > ENTRIES_PER_PAGE && ( $page != $totalpages ) ) {
+       $end = ENTRIES_PER_PAGE + $start;
+} else {
+       $end = $totalnum;
+}
+$last = $start - ENTRIES_PER_PAGE;
+if (!$query_string) {
+       $query_string = $qs;
+       $query_string = str_replace(" LIMIT ".ENTRIES_PER_PAGE." OFFSET ".$start,"",$query_string);
+}
+
+if (($start - ENTRIES_PER_PAGE) < 0) {
+       $prev = "PREV";
+} else {
+       $prev = "<a href=\"list_contact.phtml?".$stuff."&start=".$last."\">PREV</a>";
+}
+if ($end < $totalnum) {
+       $next = "<a href=\"list_contact.phtml?".$stuff."&start=".$end."\">NEXT</a>";
+} else {
+       $next = "NEXT";
+}
+?>
+<tr>
+ <td colspan="2">
+ <?php
+ if($num!=0)
+ echo $first.$prev."-".($start+1)."-to-".$end."-".$next.$lastpage;
+ ?>
+ </td>
+</tr>
+<tr>
+  <td colspan="2">
+<?php
+if (count($res)>0) {
+       for ($i=$begin;$i<$ending;$i++) {
+               if (!$row = $DB->db_fetch_array($res,$i,PGSQL_ASSOC)) {
+                       GLM_TOOLBOX::html_error(DB_ERROR_MSG.__LINE__,1);;
+               }
+        $col = 0;
+        foreach ($row as $fieldName => $fieldVal) {
+                       $fields[$col] = $fieldName;
+            if ($i == $begin) {
+                $head_ar[] = $fieldName;
+            }
+            $body_ar[] = $fieldVal;
+            ++$col;
+        }
+               if ($i == $begin) {
+                       $head_array = array_values($head_ar);
+               }
+               $contact_data[] = array_values($body_ar);
+               ?>
+               <tr <?php echo $background;
+       $id = ID;
+                       ?>>
+                <td nowrap><a href="edit_contact.php?<?php echo ID . '=' . $row[$id]?>&start=<?php echo $start;?>">
+                 [Edit]</a>
+                 <a href="update_contact.phtml?Command=Delete&id=<?php echo $row[$id]?>&start=<?php echo $start;?>" onClick="
+                       if(confirm('This will delete this record Are you sure?')) {
+                               return(true);
+                       }else {
+                               return(false);
+                       }
+                       ">
+                 [Delete]</a>
+                 </td>
+                 <td align=left>
+                 <?
+                 foreach($fields as $key) {
+                 if($key != "id" && $key != "cust_id"
+                                 && $key != "userid" && $key != "usernum"
+                                 && $key != "usergroup" && $key != "passwd")
+                       echo $row[$key]." ";
+                 }
+                 ?>
+                 </td>
+               </tr>
+               <?
+       }
+}
+       ?>
+       </td>
+</tr>
+       </table>
+       <?php
+if(isset($file) && $file != "" && $DB->db_numrows($res) > 0) {
+?>
+<table>
+<tr>
+    <th colspan=2>Download files</th>
+</tr>
+<tr>
+  <td><form action="download.phtml">
+  <input type="hidden" name="query_string" value="<?php echo $query_string?>">
+  <input type="hidden" name="file" value="<?php echo $file?>">
+  <input type="hidden" name="delimiter" value="<?php echo $delimiter?>">
+  <input type="hidden" name="csv" value="<?php echo $csv?>">
+  <input type="submit" value="Download Report">
+  </form></td>
+</tr>
+</table>
+<?php
+}
+GLM_TOOLBOX::html_nav_table($nav,5);
+GLM_TOOLBOX::footer();
+?>
diff --git a/userArea/Contact/list_groups.php b/userArea/Contact/list_groups.php
new file mode 100644 (file)
index 0000000..3f4206e
--- /dev/null
@@ -0,0 +1,56 @@
+<?php
+include_once '../../setup.phtml';
+include "contact_setup.inc";
+GLM_TOOLBOX::top('Contact Inquiries', '');
+//     Adjust the nav for this page, add the Edit Groups page.
+if (is_array($nav) && array_key_exists('Contact Inquiry Fields', $nav))
+{
+       $tmp = array('Inquiry Groups' => 'list_groups.php');
+       array_insert($nav, 'Contact Inquiry Fields', $tmp); 
+}
+GLM_TOOLBOX::html_nav_table($nav, $navWidth);
+$qs = "
+    SELECT id, name
+      FROM inq_group
+     ORDER BY name;";
+$result = $DB->db_exec( $qs );
+?>
+<table id="admin-list-table">
+       <tr>
+         <th colspan="2">
+          <form action="edit_group.php" method="POST" name="edit_group">
+                       <input type="submit" name="Command" value="Add Group" />
+               </form>
+         </th>
+       <tr>
+       <tr>
+         <th>Options:</th>
+         <th>Group:</th>
+       <tr>
+       <?php
+       if($DB->db_numrows($result) > 0) 
+       {
+               for($i=0 ;$i < $DB->db_numrows($result); $i++) 
+               {
+                       $data = $DB->db_fetch_array($result, $i, PGSQL_ASSOC);  
+                       ?>
+                       <tr>
+                               <td width="10" nowrap><a href="edit_group.php?id=<?echo $data['id'];?>&amp;Command=Edit">[Edit / Delete]</a></td>
+                               <td width="80%" align="left"><?echo $data['name'];?>
+                       </tr>
+                       <?php
+               }
+       }
+       else 
+       {
+               ?>
+               <tr>
+                       <th colspan="2">Nothing in the database yet</th>
+               </tr>
+               <?php
+       }
+       ?>
+</table>
+<?php
+GLM_TOOLBOX::footer();
+?>
diff --git a/userArea/Contact/list_query.phtml b/userArea/Contact/list_query.phtml
new file mode 100755 (executable)
index 0000000..18b12c7
--- /dev/null
@@ -0,0 +1,57 @@
+<?php
+require_once '../../setup.phtml';
+require_once 'contact_setup.inc';
+
+GLM_TOOLBOX::top("Query DB","");
+
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+?>
+<script src="<?echo MEDIA_BASE_URL."admin/wm.js"?>"></script>
+<script src="<?echo MEDIA_BASE_URL."admin/msg.js"?>"></script>
+<table id="admin-list-table">
+<tr bgcolor="#2f4f4f">
+  <th class="theader">
+  Functions:
+  </th>
+  <th class="theader">
+  Queries in database
+  </th>
+</tr>
+<?
+//if(!$dbd = db_connect()) html_error(DB_ERROR_MSG,0);
+
+$qs = "SELECT  id,query_name 
+          FROM         query_db";
+
+if(!$res = $DB->db_exec($qs)) GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs,0);
+
+for($i=0;$i<$DB->db_numrows($res);$i++) {
+       $row = $DB->db_fetch_array($res,$i,PGSQL_ASSOC);
+       
+?>
+       <script lang="javascript">
+       var o<?echo $i?> = new Object();
+       o<?echo $i?>.msg = 'You are about to Permanently Delete this Query';
+       o<?echo $i?>.url = 'del_query.phtml?id=<?echo $row[id]?>';
+       o<?echo $i?>.popup = '1';
+       o<?echo $i?>.popup.name = "delwin";
+       o<?echo $i?>.width = 630;
+       o<?echo $i?>.height = 300;
+       </script>
+<tr>
+ <td>
+ <a href="query_contact.phtml?query_no=<?echo $row[id]?>">[Recall]</a>
+ <?if($row[query_name] != "(current)") {?>
+ <a href="del_query.phtml?id=<?echo $row[id]?>" onClick="
+ glm_confirm(o<?echo $i?>);
+ return(false);
+ ">[Delete]</a>
+ <?}?>
+ </td>
+  <td><b><?echo $row[query_name]?></b></td>
+</tr>
+<?}?>
+</table>
+<?
+GLM_TOOLBOX::footer();
+?>
diff --git a/userArea/Contact/mailout.phtml b/userArea/Contact/mailout.phtml
new file mode 100644 (file)
index 0000000..b190e9c
--- /dev/null
@@ -0,0 +1,160 @@
+<html>
+<head>
+<title>Mailing out The Newsletter</title>
+</head>
+<body bgcolor="white">
+<?php
+require_once '../../setup.phtml';
+require_once 'contact_setup.inc';
+
+// File names for SPAMerizer
+$Filename = tempnam( "/var/spool/SPAMerizer", "MOUNP" );
+unlink($Filename);
+
+$HeadFilename = $Filename.".head";
+$BodyFilename = $Filename.".body";
+$ToFilename = $Filename.".to";
+$ReadyFilename = $Filename.".ready";
+
+$postmail = stripslashes($postmail);
+
+$pattern   = '/SELECT.*FROM/is';
+$replace   = "SELECT email INTO TEMPORARY temp_table FROM";
+$postmail  = preg_replace($pattern, $replace, $postmail);
+$postmail  = preg_replace("/ORDER BY.*/is","", $postmail);
+$postmail .= " AND ".MAILOK;
+
+if (!$mailres = $DB->db_exec($postmail)) {
+       html_error(DB_ERROR_MSG.__LINE__.$postmail, 1);
+}
+
+$mailqs = "SELECT 
+                  DISTINCT ON (email) email
+                  FROM         temp_table
+                  GROUP BY email;";
+flush();
+if (!$mailres = $DB->db_exec($mailqs)) {
+       html_error(DB_ERROR_MSG.__LINE__.$mailqs, 1);
+}
+
+if ($DB->db_numrows($mailres)>0) {
+       for($a=0;$a<$DB->db_numrows($mailres);$a++) {
+               $mvdata = $DB->db_fetch_array($mailres, $a, PGSQL_ASSOC);       
+               $email = trim($mvdata["email"]); 
+        if ($email) {
+            $mail[] = $email;  
+        }
+    }
+}
+if (is_array($mail) && count($mail)>0) {
+       // write the temp.to file
+       $mail = implode("\n", $mail);
+       $fp = fopen($ToFilename, "w");
+       fputs($fp, $mail, strlen($mail));
+       fclose($fp);
+} else {
+       $mail = "";
+}
+
+
+if ($mail != "") {
+       // I am changing this to a two part mime type email
+       // html and text
+       // using class_html     
+       $responseqs = "SELECT   * 
+                                  FROM         news_response
+                                  WHERE        id = $mail_id";
+       if (!$resres = $DB->db_exec($responseqs)) {
+               html_error(DB_ERROR_MSG.$responseqs, 0);
+    }
+
+       $responserow = $DB->db_fetch_array($resres, 0, PGSQL_ASSOC);
+
+       $subject = trim($responserow['subject']);
+       $data['subject'] = &$subject;
+       $message = $responserow['response'];
+       // html part of email
+       //$data['response'] = stripslashes(nl2br($message));
+       $data['response'] = $message;
+       $data['url'] = MEDIA_BASE_URL;
+       
+       $html = explode_template(NEWSLETTER_PROTOTYPE,$data);
+
+       // text part of email
+       $text = strip_tags($message);
+       $text .= "\n\n-------------------------------------------------------------------\n";
+       $text .= "You are receiving this message because you have expressed an interest in\n";
+       $text .= "receiving specials and information from ".SITENAME.". If you do not\n";
+       $text .= "wish to receive future items of this nature, please reply to this e-mail\n";
+       $text .= "with the word \"CANCEL\" on the subject line. You will then be removed \n";
+       $text .= "from future mailings.\n";
+       $text .= "-------------------------------------------------------------------\n";
+       
+       // Write the temp.header file
+       $glm_headers = "NotifyAddr: ".OWNER_EMAIL."\n"
+               . "ProcessName: ".SITENAME."\n"
+               . "From: ".FROM_NEWS_EMAIL."\n"
+               . "ReportInterval: 2\n"
+               . "BlockSize: 1\n"
+               . "ProductionMode: ".PRODUCTION_MODE."\n";
+
+       $fp = fopen($HeadFilename, "w");
+       fputs($fp, $glm_headers, strlen($glm_headers));
+       fclose($fp);
+
+       $headers =      "From: ".FROM_NEWS_EMAIL."\n".
+                               "To: ".OWNER_EMAIL."\n".
+                               "Subject: $subject\n".
+                               "Reply-to: ".REPLY_TO."\n".
+                               "Mime-Version: 1.0\n".
+                               "Content-Type: multipart/alternative; boundary=ContentBoundry\n\n";     
+       $fp = fopen($BodyFilename,"w");
+       if(HTML_EMAIL=="ON"){
+               $body_html = '--ContentBoundry
+Content-Type: text/plain; charset="UTF-8"
+'.$text.'
+--ContentBoundry
+Content-Type: text/html; charset="UTF-8"
+
+'.$html.'
+
+--ContentBoundry--';
+               fputs($fp, $headers, strlen($headers));
+               fputs($fp, $body_html, strlen($body_html));
+       } else {
+               fputs($fp, $headers, strlen($headers));
+               fputs($fp, $text, strlen($text));       
+       }
+       fclose($fp);
+       // write the temp.ready file and your done!
+       $fp = fopen($ReadyFilename, "w");
+       fclose($fp);
+?>
+<table>
+<tr>
+  <td>Mail the current <?echo $subject?></td>
+</tr>
+<tr>
+  <td><?echo (PRODUCTION_MODE == "ON")?"ProductionMode is ON, Mail is sent.":"ProductionMode is OFF, Mail is not sent."?></td>
+</tr>
+<tr>
+  <td><?echo (HTML_EMAIL == "ON")?"HTML Email is ON, Mail is html encoded.":"HTML Email is OFF, Mail is plain text."?></td>
+</tr>
+<tr>
+  <td>You will recieve notification on the mailing task by email at <?=OWNER_EMAIL?>.</td>
+</tr>
+</table>
+<?
+} else {
+?>
+<table width=500 bgcolor="#e0e0e0">
+<tr bgcolor="#2f4f4f">
+  <th><font color=white>Newsletter Not Sent!</th>
+  </tr>
+</table>
+<?php
+}
+
+?>
+</body>
+</html>
diff --git a/userArea/Contact/main.css b/userArea/Contact/main.css
new file mode 100755 (executable)
index 0000000..fef38df
--- /dev/null
@@ -0,0 +1,23 @@
+body {
+       background-color: #FFFFFF;
+}
+
+.navlink {
+       font-size: 80%;
+       font-family: arial;
+}
+
+td {
+       font-size: 80%;
+       font-family: arial,helvetica;
+}
+
+.theader {
+       font-size: 120%;
+       font-family: arial,helvetica;
+       color: #FFFFFF;
+}
+
+.theadertd {
+       background-color: #000080;
+}
diff --git a/userArea/Contact/msg.js b/userArea/Contact/msg.js
new file mode 100755 (executable)
index 0000000..8ed837d
--- /dev/null
@@ -0,0 +1,29 @@
+function glm_confirm(o) {
+       var p = o.msg.split("\n");
+       var k = 0;
+       for(i = 0;i < p.length;i++) {
+               if(k > p[i].length)
+                       continue;
+               else 
+                       k = p[i].length;
+       }       
+       
+       var bound = "";
+       for(i = 0; i < k; i++) {
+               bound = bound+'_';
+       }
+       var str = bound+"\n\n"+o.msg+"\n\n"+bound+"\n\nAre You Sure?";
+       if(confirm(str)) {
+               if(o.popup == '1') {
+                       var nw = new Object();
+                       nw.url = o.url;
+                       nw.name = o.popup.name;
+                       nw.width = o.width;
+                       nw.height = o.height;
+                       glm_open(nw);
+               }
+               else {
+                       location.replace(o.url);
+               }
+       }
+}
diff --git a/userArea/Contact/newsletter_template.html b/userArea/Contact/newsletter_template.html
new file mode 100755 (executable)
index 0000000..9a145a7
--- /dev/null
@@ -0,0 +1,42 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+       <meta http-equiv="content-type" content="text/html;charset=utf-8">
+</head>
+<body>
+<table cellspacing="0" cellpadding="0" border="0" width="100%">
+       <tr>
+               <td align="center">
+      <table cellspacing="0" cellpadding="0" border="0" width="550" bgcolor="#ffffff">
+       <tr>
+               <td>
+                                               <a href="<!-- url -->"><img src="<!-- url -->assets/nHeader.jpg" width="550" height="114" alt="" style="border: 0; display: block;"></a>
+                                       </td>
+                               </tr>
+                               <tr>
+                                       <td>
+            <table cellspacing="15" cellpadding="0" border="0">
+               <tr>
+                       <td>
+                                                                       <font face="arial, helvetica, sans-serif" size="2">
+                                                                               <!-- response -->
+                                                                       </font>
+                                                               </td>
+                                                       </tr>
+                                                       <tr>
+                                                               <td>
+                                                                       <font face="arial, helvetica, sans-serif" size="1">
+                                                                       <hr>
+                                                                               <!-- bailout -->
+                                                                       </font>
+                                                               </td>
+                                                       </tr>
+                                               </table>
+                                       </td>
+                               </tr>
+                       </table>
+               </td>
+       </tr>
+</table>                                                                       
+</body>
+</html>
diff --git a/userArea/Contact/notes/ChangeLog b/userArea/Contact/notes/ChangeLog
new file mode 100755 (executable)
index 0000000..fc6c567
--- /dev/null
@@ -0,0 +1,327 @@
+2002-05-07 13:47  matrix
+
+       * contact_setup.inc, del_query.phtml, download.phtml,
+       edit_contact.phtml, form.js, index.phtml, list_contact.phtml,
+       list_query.phtml, mailout.phtml, main.css, msg.js,
+       query_contact.phtml, query_db.phtml, query_save.phtml,
+       update_contact.phtml, verify.js, wm.js, help/contact.phtml,
+       notes/ChangeLog, notes/Contact, notes/adm2.sql, notes/contact.sql,
+       notes/guest.sql: "version 2.4"
+
+2002-05-07 13:45  matrix
+
+       * contact.sql, contact_setup.inc, edit_contact.phtml,
+       list_contact.phtml, update_contact.phtml, notes/ChangeLog,
+       notes/contact.sql, notes/Contact: adding ChangeLog file and moving
+       sql file into notes.  I have also set the insert part of
+       update_contact.phtml to use nextval to generate the PRIMEKEY so
+       this will work with previous version of th shop which don't have
+       the default set on cust_id
+
+2002-05-07 11:14  matrix
+
+       * contact.sql, contact_setup.inc, del_query.phtml, download.phtml,
+       edit_contact.phtml, form.js, index.phtml, list_contact.phtml,
+       list_query.phtml, mailout.phtml, main.css, msg.js,
+       query_contact.phtml, query_db.phtml, query_save.phtml,
+       update_contact.phtml, verify.js, wm.js, help/contact.phtml,
+       notes/adm2.sql, notes/guest.sql: testing out both contact and
+       customer table use
+
+2002-05-07 10:08  matrix
+
+       * form.js, msg.js, verify.js, wm.js: "putting javascript files in
+       dir"
+
+2002-05-07 09:57  matrix
+
+       * index.phtml: "all versions now 2.0"
+
+2002-05-07 09:57  matrix
+
+       * index.phtml: new file
+
+2002-05-07 09:44  matrix
+
+       * admin_constants.inc, contact.phtml, contact.sql,
+       contact_setup.inc, contact_test.sql, del_query.phtml,
+       download.phtml, edit_contact.phtml, index.html, list_contact.phtml,
+       list_cust_form.phtml, list_customers.phtml, list_query.phtml,
+       mailout.phtml, main.css, path.phtml, query_contact.phtml,
+       query_db.phtml, query_save.phtml, shopping_cart_setup.inc,
+       update_contact.phtml, help/contact.phtml, notes/adm2.sql,
+       notes/guest.sql: "merging final changes into one app"
+
+2002-03-14 11:23  matrix
+
+       * download.phtml: removed offending dot
+
+2002-03-12 10:32  matrix
+
+       * contact_setup.inc: file contact_setup.inc was initially added on
+       branch glm-Contact-2-0.
+
+2002-03-12 10:32  matrix
+
+       * download.phtml: file download.phtml was initially added on branch
+       glm-Contact-2-0.
+
+2002-03-12 10:32  matrix
+
+       * contact.phtml, contact_setup.inc, del_query.phtml,
+       download.phtml, edit_contact.phtml, list_contact.phtml,
+       list_query.phtml, mailout.phtml, query_contact.phtml,
+       query_db.phtml, update_contact.phtml: make it customer and ocntact
+
+2002-03-12 09:36  matrix
+
+       * list_cust_form.phtml, list_customers.phtml, path.phtml,
+       shopping_cart_setup.inc: updates
+
+2002-03-12 09:34  matrix
+
+       * contact.phtml, del_query.phtml, edit_contact.phtml,
+       list_contact.phtml, list_query.phtml, query_contact.phtml,
+       query_db.phtml, update_contact.phtml: prepare for merging
+
+2001-12-17 10:13  matrix
+
+       * list_contact.phtml, mailout.phtml: added ID
+
+2001-12-17 10:02  matrix
+
+       * list_contact.phtml, mailout.phtml: mail can't be sent by url
+
+2001-11-27 16:50  matrix
+
+       * contact.phtml, del_query.phtml, edit_contact.phtml,
+       list_contact.phtml, list_query.phtml, query_contact.phtml,
+       query_db.phtml, query_save.phtml, update_contact.phtml: needed to
+       update adding contacts to customer table as there is no default
+       value for cust_id
+
+2001-11-21 14:07  matrix
+
+       * contact.phtml, del_query.phtml, edit_contact.phtml,
+       list_contact.phtml, list_query.phtml, path.phtml,
+       query_contact.phtml, query_db.phtml, update_contact.phtml: using
+       setup.phtml not path.phtml
+
+2001-11-07 14:30  matrix
+
+       * list_contact.phtml: removed echo
+
+2001-11-07 14:27  matrix
+
+       * contact.phtml, del_query.phtml, edit_contact.phtml,
+       list_query.phtml, mailout.phtml, path.phtml, query_contact.phtml,
+       query_db.phtml, update_contact.phtml: updatng now using setup.phtml
+
+2001-11-07 14:24  matrix
+
+       * list_contact.phtml: correcting email out code
+
+2001-10-15 15:19  matrix
+
+       * contact.phtml, query_contact.phtml: adding date search
+
+2001-10-11 14:44  matrix
+
+       * list_contact.phtml: updating
+
+2001-10-11 14:34  matrix
+
+       * mailout.phtml: file mailout.phtml was initially added on branch
+       glm-Contact-2-0.
+
+2001-10-11 14:32  matrix
+
+       * list_contact.phtml, mailout.phtml: added autoresponder
+
+2001-09-25 10:14  matrix
+
+       * path.phtml: changed the path so we use one file
+
+2001-09-25 10:13  matrix
+
+       * contact.phtml: tr tag
+
+2001-07-02 14:29  matrix
+
+       * path.phtml: symplified the path files now this referes to the
+       main one in admin
+
+2001-06-22 08:55  matrix
+
+       * contact.phtml, contact.sql, edit_contact.phtml,
+       update_contact.phtml: adding field referred_by
+
+2001-06-19 08:50  matrix
+
+       * list_contact.phtml: no real change
+
+2001-06-19 08:49  matrix
+
+       * update_contact.phtml, edit_contact.phtml: modified for mailok
+
+2001-06-19 08:45  matrix
+
+       * list_contact.phtml: modified for errors on recalls
+
+2001-06-19 08:45  matrix
+
+       * edit_contact.phtml, update_contact.phtml: modified for mailok
+
+2001-06-18 10:08  matrix
+
+       * query_db.phtml: shop_query_db
+
+2001-06-18 10:08  matrix
+
+       * help/helpbg.gif: file helpbg.gif was initially added on branch
+       glm-Contact-shop-1-0.
+
+2001-06-18 10:08  matrix
+
+       * help/: closewindow.gif, contact.phtml, helpbg.gif: added images
+       to help folder
+
+2001-06-18 10:08  matrix
+
+       * help/closewindow.gif: file closewindow.gif was initially added on
+       branch glm-Contact-shop-1-0.
+
+2001-06-18 10:05  matrix
+
+       * query_contact.phtml: shop_query_db
+
+2001-06-18 10:04  matrix
+
+       * list_query.phtml: added nav links
+
+2001-06-18 10:03  matrix
+
+       * list_query.phtml: new shop query db
+
+2001-06-11 13:14  matrix
+
+       * list_contact.phtml: error correction
+
+2001-06-11 10:51  matrix
+
+       * list_contact.phtml: if there are no queries insert current
+
+2001-06-11 10:31  matrix
+
+       * list_contact.phtml: if there are no contacts html_error
+
+2001-06-11 10:18  matrix
+
+       * list_query.phtml: added nav to top of page
+
+2001-06-11 10:15  matrix
+
+       * help/contact.phtml: corrected paths to help images
+
+2001-06-08 09:17  matrix
+
+       * contact.sql: changing query table name to keep from messing up
+       other application
+
+2001-06-08 09:16  matrix
+
+       * help/contact.phtml: updateing help file
+
+2001-06-08 09:12  matrix
+
+       * contact.phtml: changed radio buttons on mail_ok to drop down
+
+2001-06-08 08:50  matrix
+
+       * list_contact.phtml: modified
+
+2001-06-08 08:46  matrix
+
+       * contact.phtml: made the mail_ok a drop down
+
+2001-06-07 14:54  matrix
+
+       * contact.phtml, list_contact.phtml, query_contact.phtml: updated
+       per gloriebe contactdb
+
+2001-06-07 14:06  matrix
+
+       * query_contact.phtml, help/contact.phtml: made changes for ereg
+       wildcards
+
+2001-06-06 15:51  matrix
+
+       * contact.phtml, contact.sql, edit_contact.phtml,
+       list_contact.phtml, query_contact.phtml, query_save.phtml,
+       update_contact.phtml: shop version
+
+2001-06-06 15:42  matrix
+
+       * main.css: added file
+
+2001-06-06 15:40  matrix
+
+       * report.rpt: "removed"
+
+2001-06-06 15:00  matrix
+
+       * contact.phtml, list_contact.phtml, query_contact.phtml,
+       update_contact.phtml, help/contact.phtml: worked out some bugs
+
+2001-06-06 13:41  matrix
+
+       * help/contact.phtml: changed path on images
+
+2001-06-06 13:38  matrix
+
+       * main.css: adding needed files
+
+2001-06-06 13:38  matrix
+
+       * main.css: file main.css was initially added on branch
+       glm-Contact-2-0.
+
+2001-06-05 11:17  matrix
+
+       * path.phtml: changed path to help
+
+2001-06-05 11:13  matrix
+
+       * path.phtml: changed path to help
+
+2001-06-05 10:45  matrix
+
+       * path.phtml: added path file
+
+2001-06-05 10:38  matrix
+
+       * contact.phtml, list_contact.phtml, query_contact.phtml: added
+       pipe and csv delimiter
+
+2001-05-31 12:43  matrix
+
+       * contact.phtml, contact.sql, contact_test.sql, del_query.phtml,
+       edit_contact.phtml, list_contact.phtml, list_query.phtml,
+       query_contact.phtml, query_db.phtml, query_save.phtml,
+       update_contact.phtml, help/contact.phtml: combining the contact
+       databases
+
+2001-04-04 13:42  matrix
+
+       * admin_constants.inc, index.html, list_cust_form.phtml,
+       list_customers.phtml, path.phtml, report.rpt,
+       shopping_cart_setup.inc, notes/adm2.sql, notes/guest.sql: Initial
+       revision
+
+2001-04-04 13:42  matrix
+
+       * admin_constants.inc, index.html, list_cust_form.phtml,
+       list_customers.phtml, path.phtml, report.rpt,
+       shopping_cart_setup.inc, notes/adm2.sql, notes/guest.sql: imported
+       sources
+
diff --git a/userArea/Contact/notes/Contact b/userArea/Contact/notes/Contact
new file mode 100755 (executable)
index 0000000..937f46f
--- /dev/null
@@ -0,0 +1,4 @@
+All application setup stuff will be in contact_setup.phtml
+1)     right now if you add to the $fields array you'll still have to change
+       edit_contact.phtml and update_contact.phtml
+2)     contact.sql - contains the query to build the contact table and query_db table
diff --git a/userArea/Contact/notes/contact.sql b/userArea/Contact/notes/contact.sql
new file mode 100755 (executable)
index 0000000..4fd960b
--- /dev/null
@@ -0,0 +1,100 @@
+\connect - postgres
+
+CREATE TABLE "contact" (
+       "id" SERIAL PRIMARY KEY, 
+       "create_date" date default current_date,
+       "fname" text,
+       "lname" text,
+       "company" text,
+       "address" text,
+       "address2" text,
+       "city" text,
+       "state" text,
+       "zip" text,
+       "country" text,
+       "phone" text,
+       "fax" text,
+       "email" text,
+       "user_agent" text,
+       "remote_addr" text,
+       "interest" text,
+       "mail_ok" boolean default 'f',
+    "contact_type" text
+);
+
+REVOKE ALL on "contact" from PUBLIC;
+GRANT ALL on "contact" to "nobody";
+GRANT ALL on "contact" to "postgres";
+
+REVOKE ALL on "contact_id_seq" from PUBLIC;
+GRANT ALL on "contact_id_seq" to "nobody";
+GRANT ALL on "contact_id_seq" to "postgres";
+
+CREATE TABLE "query_db" (
+       "id" SERIAL PRIMARY KEY, 
+       "query_name" text,
+       "query" text,
+       "file" text,
+       "delimiter" text
+);
+
+REVOKE ALL on "query_db" from PUBLIC;
+GRANT ALL on "query_db" to "nobody";
+GRANT ALL on "query_db" to "postgres";
+
+REVOKE ALL on "query_db_id_seq" from PUBLIC;
+GRANT ALL on "query_db_id_seq" to "nobody";
+GRANT ALL on "query_db_id_seq" to "postgres";
+
+CREATE TABLE "news_response" (
+       "id" SERIAL PRIMARY KEY, 
+       "subject" text,
+       "response" text,
+       "image" text,
+       "image2" text,
+       "image3" text,
+       "image_align" text,
+       "image2_align" text,
+       "image3_align" text,
+       "mailout" date default current_date,
+       "last_update" date default current_date
+);
+
+REVOKE ALL on "news_response" from PUBLIC;
+GRANT ALL on "news_response" to "postgres";
+GRANT ALL on "news_response" to "nobody";
+GRANT ALL on "news_response_id_seq" to "nobody";
+
+INSERT INTO news_response (subject,response) values ('subject','response');
+
+CREATE UNIQUE INDEX contact_id_indx ON contact(id);
+CREATE INDEX contact_email_indx ON contact(email);
+CREATE INDEX contact_fname_indx ON contact(fname);
+CREATE INDEX contact_lname_indx ON contact(lname);
+CREATE INDEX contact_create_date_indx ON contact(create_date);
+CREATE UNIQUE INDEX news_response_id_indx ON contact(id);
+CREATE UNIQUE INDEX query_db_id_indx ON contact(id);
+
+CREATE TABLE contact_inq (
+    id serial NOT NULL,
+    header text,
+       pos integer,
+    description text,
+    image text,
+    groupid integer
+);
+REVOKE ALL ON TABLE contact_inq FROM PUBLIC;
+GRANT ALL ON TABLE contact_inq TO nobody;
+REVOKE ALL ON TABLE contact_inq_id_seq FROM PUBLIC;
+GRANT ALL ON TABLE contact_inq_id_seq TO nobody;
+ALTER TABLE ONLY contact_inq
+    ADD CONSTRAINT contact_inq_pkey PRIMARY KEY (id);
+
+CREATE TABLE inq_group (
+    id SERIAL PRIMARY KEY,
+    name text
+);
+GRANT ALL ON inq_group TO nobody;
+GRANT ALL ON inq_group_id_seq TO nobody;
+
+INSERT INTO inq_group (name) VALUES ('Areas of Interest');
diff --git a/userArea/Contact/preview.phtml b/userArea/Contact/preview.phtml
new file mode 100755 (executable)
index 0000000..aec6264
--- /dev/null
@@ -0,0 +1,14 @@
+<?php
+require_once '../../setup.phtml';
+require_once 'contact_setup.inc';
+
+$query = "SELECT * FROM news_response WHERE id = {$_REQUEST['id']}";
+$res = $DB->db_auto_get_data($query);
+$data['url'] = MEDIA_BASE_URL;
+$data['subject'] = $res[0]["subject"];
+$response = $res[0]["response"];
+$data['response'] = $response;
+
+$page = GLM_TOOLBOX::explode_template(NEWSLETTER_PROTOTYPE,$data);
+echo $page;
+?>
diff --git a/userArea/Contact/query_contact.phtml b/userArea/Contact/query_contact.phtml
new file mode 100755 (executable)
index 0000000..fd553cb
--- /dev/null
@@ -0,0 +1,413 @@
+<?php
+session_start();
+require_once '../../setup.phtml';
+require_once 'contact_setup.inc';
+/* Includes  */
+extract($_POST);
+function clean_array(&$array){
+       if (is_array($array)){
+               $counter = 0;
+               foreach ($array as $key=>$value){
+                       if ($value == ""){
+                               unset($array[$counter]);
+                       }
+                       $counter++;
+               }
+       }
+}
+$sess_vars = $_POST;
+$_SESSION['sess_vars'] = $sess_vars;
+if (!isset($query_no)) {
+       /* The fields array is sent as a string 
+               explode it out using : as delimiter */
+       $fvalue = preg_replace("/^:/","",$fvalue);
+       $fields = explode(":",$fvalue);
+       $rfvalue = preg_replace("/^:/","",$rfvalue);
+       $return_fields = explode(":",$rfvalue);
+       $dates = preg_replace("/^:/","",$rdvalue);
+       $dates = explode(":",$dates);
+
+       clean_array($return_fields);
+       clean_array($dates);
+       if (!isset($search)) {
+               header("Location: index.phtml");
+       }
+       /* Chop off whitespaces spaces */
+       $search = chop(trim($search));
+    $search = preg_replace("/\\\|\"/", "", $search);
+       if (!$search && (count ($fields) == 1 && $fields[0] == '')) {
+               $ALL = TRUE;
+       }
+
+       function getKeywords($keywords) {
+               /* Replace the whitespace with a , */
+               $keywords = str_replace(" ",",",$keywords);
+               $keywords = str_replace(",,",",",$keywords);
+               $seperated = explode(",",$keywords);
+               /* Return exploded string */
+               return $seperated;
+       }
+
+       switch($search_type) {
+    case "1":
+        $keywords = $search;
+        $compare = "OR";
+        break;
+
+    case "2":
+        $keywords = getKeywords($search);
+        $compare = "AND";
+        break;
+
+    case "3":
+        $keywords = getKeywords($search);
+        $compare = "OR";
+        break;
+
+    case "4":
+        $keywords = getKeywords($search);
+        $compare = "AND";
+        $NOT = TRUE;
+        break;
+
+    default:
+        echo "not valid";
+        break;
+       }
+
+       if (is_array($keywords)) {
+               for ($rip=0;$rip<count($keywords);$rip++) {
+                       $keywords[$rip] = trim($keywords[$rip]);
+                       /* if * is at the begging the replace with .* */
+                       $keywords[$rip] = preg_replace("/[\x2a]/",".*",$keywords[$rip]);
+                       $keywords[$rip] = preg_replace("/[\x3f]/",".?",$keywords[$rip]);
+                       $keywords[$rip] = preg_replace("/[\x2b]/",".+",$keywords[$rip]);
+               }
+       } else {
+               $keywords = trim($keywords);
+               /* if * is at the begging the replace with .* */
+               $keywords = preg_replace("/[\x2a]/",".*",$keywords);
+               $keywords = preg_replace("/[\x3f]/",".?",$keywords);
+               $keywords = preg_replace("/[\x2b]/",".+",$keywords);
+       }
+       
+       switch($alter) {
+    /* $alter defines where to look in fields */
+    case "1":
+        $begin = "^";
+        $end = "";
+        break;
+
+    case "2":
+        $begin = "";
+        $end = " *$";
+        break;
+
+    default:
+        $begin = "";
+        $end = "";
+        break;
+       }
+       
+       $operator = " ";
+       if ($NOT) {
+               $operator .= "!~";
+       } else {
+               $operator .= "~";
+       }
+       if ($case == "OFF") {
+               $operator .= "*";
+       }
+       if ($search == "" && ! (count ($fields)  == 1 && $fields[0] == '') )  {
+               $operator = "=";
+       }
+       $operator .= " ";
+
+       /* finally, build the query string from string or array $keywords */
+       $query_string = "SELECT ".ID.",";
+       $totali = count($return_fields)-1;
+       for ($i=0;$i<count($return_fields);$i++) {
+               $query_string .= $return_fields[$i];
+               if ($i != $totali) {
+                       $query_string .= ",";
+               }
+               if ($i == 8) {
+                       $query_string .= "\n";
+               }
+       }
+       $totald = count($dates)-1;
+       for ($i=0;$i<count($dates);$i++) {
+               if ($dates[$i] != " " && $dates[$i] != "") {
+                       if ($i == 0) {
+                               $query_string .= ",";
+                       }
+               }
+               $query_string .= $dates[$i];
+               if ($i != $totald) {
+                       $query_string .= ",";
+               }
+       }
+       if (!$ALL) {    
+               $query_string .= "\nFROM\t".TABLE." \nWHERE\t".WHERE."\nAND\t";
+               $query_string .= "(";
+               for ($b=0;$b<count($fields);$b++) {
+                       $totalb = count($fields)-1;
+                       if (is_array($keywords)) {
+                               for ($c=0;$c<count($keywords);$c++) {
+                                       $totalc = count($keywords)-1;
+                                       $query_string .= $fields[$b].$operator."'".
+                                               $begin.$keywords[$c].$end."'";
+                                       if ($c != $totalc) {
+                                               $query_string .= " \n$compare\t";
+                                       }
+                               }
+                       } else {
+                               $query_string .= $fields[$b].$operator."'".
+                                       $begin.$keywords.$end."'";
+                       }
+                       if ($b != $totalb) {
+                               $query_string .= " \n$compare\t";
+                       }
+               }
+               $query_string .= ")";
+       } else {
+               $query_string .= "\nFROM\t".TABLE." \nWHERE\t".WHERE."\n";
+       }
+       if (is_array ($boolean) ) {
+               foreach ($boolean as $bool_key => $bool_val) {
+                       if ($_POST[$bool_key] == "1") {
+                               $bstring[] = " $bool_key = 't'";
+                       } elseif ($_POST[$bool_key] == "0") {
+                               $bstring[] = " $bool_key = 'f'";
+                       }
+               }
+               if (is_array($bstring)) {
+                       $query_string .= ' and ('.implode(" $compare ",$bstring) .')  ';
+               }
+       }
+       if( is_array( $dropdowns ) ) {
+               foreach( $dropdowns as $drop_key => $drop_val ) {
+                       if( is_array( $_POST[$drop_key] ) ) {
+                               foreach( $_POST[$drop_key] as $mdrop_key => $mdrop_val ){
+                                       if( $mdrop_val != '' ){
+                                               $dstring[] = " $drop_key $operator ':".$mdrop_val.":'";
+                                       }
+                               }
+                       }elseif( !is_array( $_POST[$drop_key] ) ) {
+                               if( $_POST[$drop_key] != '' ){
+                                       $dstring[] = " $drop_key = '".$_POST[$drop_key]."'";
+                               }
+                       }
+               }
+               if( is_array($dstring) ) {
+                       $query_string .= ' and ('.implode(" $compare ",$dstring).' ) ';
+               }
+       }
+       if (is_array ($cols) ) {
+               foreach ($cols as $ikey => $ival) {
+                       $cstring[] = " interest $operator ':$ival:'";
+               }
+               if (is_array($cstring)) {
+                       $query_string .= ' and ('.implode(" $compare ",$cstring).')  ';
+               }
+       }
+       if (isset($fp_month)) {
+               $fp_str = mktime(0,0,0,$fp_month,$fp_day,$fp_year);
+               $tp_str = mktime(0,0,0,$tp_month,$tp_day,$tp_year);
+               $fa_str = mktime(0,0,0,$fa_month,$fa_day,$fa_year);
+               $ta_str = mktime(0,0,0,$ta_month,$ta_day,$ta_year);
+               
+               if ($fp_str<$tp_str) {
+                       $fp_date = $fp_month."/".$fp_day."/".$fp_year;
+                       $tp_date = $tp_month."/".$tp_day."/".$tp_year;
+                       $query_string .= " AND purch_date >= '$fp_date'
+                                                          AND purch_date <= '$tp_date'";
+               }
+               if ($fa_str<$ta_str) {
+                       $fa_date = $fa_month."/".$fa_day."/".$fa_year;
+                       $ta_date = $ta_month."/".$ta_day."/".$ta_year;
+                       $query_string .= " AND access_date >= '$fa_date'
+                                                          AND access_date <= '$ta_date'";
+               }
+               if ($fp_str>$tp_str) {
+                       $fp_date = $fp_month."/".$fp_day."/".$fp_year;
+                       $tp_date = $tp_month."/".$tp_day."/".$tp_year;
+                       $query_string .= " AND purch_date <= '$tp_date'";
+               }
+               if ($fa_str>$ta_str) {
+                       $fa_date = $fa_month."/".$fa_day."/".$fa_year;
+                       $ta_date = $ta_month."/".$ta_day."/".$ta_year;
+                       $query_string .= " AND access_date <= '$ta_date'";
+               }
+       }
+       if (isset($fc_month)) {
+               $fc_str = mktime(0,0,0,$fc_month,$fc_day,$fc_year);
+               $tc_str = mktime(0,0,0,$tc_month,$tc_day,$tc_year);
+               
+               if ($fc_str<$tc_str) {
+                       $fc_date = $fc_month."/".$fc_day."/".$fc_year;
+                       $tc_date = $tc_month."/".$tc_day."/".$tc_year;
+                       $query_string .= " AND create_date >= '$fc_date'
+                                                          AND create_date <= '$tc_date'";
+               }
+               if ($fc_str>$tc_str) {
+                       $fc_date = $fc_month."/".$fc_day."/".$fc_year;
+                       $tc_date = $tc_month."/".$tc_day."/".$tc_year;
+                       $query_string .= " AND create_date <= '$tc_date'";
+               }
+       }
+} else {
+//     if (!$dbd = db_connect()) html_error(DB_ERROR_MSG,0);
+
+       $qs = "SELECT   query_name,query,delimiter,file 
+                  FROM         query_db
+                  WHERE        id = $query_no";
+
+       if (!$res = $DB->db_exec($qs)) GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs,0);
+       $row = $DB->db_fetch_array($res,0,PGSQL_ASSOC);
+       $query_name = $row[query_name];
+       $query_string = $row[query];
+       $file = $row[file];
+       $delimiter = $row[delimiter];
+}
+
+/* Thought the customer would like to see what's in the query */
+$showq = str_replace("SELECT","Return\n",$query_string);
+$showq = str_replace ("\nFROM\t".TABLE." \nWHERE\t".WHERE."\nAND\t",
+" \nfrom the contact database \nwhere ",$showq);
+$showq = str_replace ("\nFROM\t".TABLE." \nWHERE\t".WHERE."\n",
+" \nfrom the contact database",$showq);
+$showq = str_replace("fname","first name",$showq);
+$showq = str_replace("cust_id,","",$showq);
+$showq = str_replace("lname","last name",$showq);
+$showq = str_replace("!~*","does not contain",$showq);
+$showq = str_replace("!~","does not contain",$showq);
+$showq = str_replace("~*","contains",$showq);
+$showq = str_replace("~","is in",$showq);
+$showq = str_replace("does not contain '^"," does not start with ",$showq);
+$showq = str_replace("contains '^"," starts with ",$showq);
+$showq = str_replace("is in '^"," starts with ",$showq);
+$showq = str_replace("$"," in the ending ",$showq);
+$showq = str_replace("OR","or",$showq);
+$showq = str_replace("AND","and",$showq);
+$showq = str_replace("'","",$showq);
+if (!$ALL) {
+       if ($case == "OFF") {
+               $showq .= "\n(case insensitive match)";
+       } else {
+               $showq .= "\n(case sensitive match)";
+       }
+}
+if (isset($file) && $file != "") {
+       $showq .= "\noutput 1 file in ";
+       if ($file == "rpt") {
+               $showq .= "text";
+       }elseif ($file == "gz") {
+               $showq .= "tar ball";
+       }else {
+               $showq .= "zip";
+       }
+       if ($delimiter == "csv") {
+               $showq .= " format using ".$delimiter;
+    } else {
+               $showq .= " format using ".$delimiter." as delimiter";
+    }
+}
+$showq .= ".";
+$query = addslashes($query_string);
+
+GLM_TOOLBOX::top("QUERY BUILDER PAGE","");
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);
+?>
+<script src="<?echo MEDIA_BASE_URL."admin/wm.js"?>"></script>
+<script src="<?echo MEDIA_BASE_URL."admin/msg.js"?>"></script>
+
+<table id="admin-list-table">
+<tr>
+  <th bgcolor="#2f4f4f" class="theader">
+       Submit Query
+  </th>
+  </tr>
+       <tr>
+       <td><a href="index.phtml">Go Back to Query page</a></td>
+       </tr>
+  <tr>
+  <td>
+       <?echo nl2br($showq)?>
+    <br>
+       <?if (isset($query_name)) {
+       echo "Query ".$query_name." Recalled";
+       }?>
+       
+       <form action="list_contact.phtml" method="POST">
+       <input type="hidden" name="delimiter" value="<?echo $delimiter?>">
+       <input type="hidden" name="file" value="<?echo $file?>">
+       <?php
+       if (!$_GET['query_no']) {
+       ?>
+       <input type="hidden" name="query_string" value="<?echo $query_string?>">
+       <?php
+       } else {
+       ?>
+       <input type="hidden" name="query_no" value="<?php echo $_GET['query_no'];?>">
+       <?php
+       }
+       ?>
+       <input type="hidden" name="Submit" value="Submit Query">
+       <center>
+       <input type="submit" value="Send Query">
+       </form>
+       </center>
+       </td>
+  </tr>
+</table>
+<script lang="javascript">
+       var o_save = new Object();
+       o_save.url = 'query_save.phtml';
+       o_save.name = 'savewin';
+       o_save.width = 510;
+       o_save.height = 150;
+</script>
+<table>
+  <tr>
+  <th bgcolor="#2f4f4f" class="theader">
+       Do you wish to save this query for future use?
+  </th>
+  </tr>
+  <tr>
+    <td>
+       <a href="#" onClick="
+       glm_open(o_save);
+       return(false);
+       ">Save This Report</a>
+       </td>
+</tr>
+</table>
+
+<?php
+/* Save the query with (current) as query_name */
+$qs = "SELECT id
+            FROM query_db 
+           WHERE query_name = '(current)'";
+
+if (!$res = $DB->db_exec($qs)) {
+    GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs,0);
+}
+
+if (!$row = $DB->db_fetch_array($res,0,PGSQL_ASSOC)) {
+       $qs = "INSERT 
+                  INTO         query_db
+                                       (query_name,query,file,delimiter)
+                  VALUES       ('(current)','$query','$file','$delimiter')";
+} else {
+       $qs = "UPDATE   query_db 
+                  SET          query = '$query',
+                                       file = '$file',
+                                       delimiter = '$delimiter'
+                  WHERE        id = $row[id]";
+}
+if (!$DB->db_auto_exec($qs)) {
+    GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs,0);
+}
+GLM_TOOLBOX::footer();
+?>
diff --git a/userArea/Contact/query_db.phtml b/userArea/Contact/query_db.phtml
new file mode 100755 (executable)
index 0000000..3134464
--- /dev/null
@@ -0,0 +1,19 @@
+<?php
+require_once '../../setup.phtml';
+require_once 'contact_setup.inc';
+
+if(!isset($file)) $file = "";
+if(!isset($delimiter)) $delimiter = "";
+
+$qs = "INSERT 
+          INTO         query_db (query_name,query,file,delimiter) 
+         (select '$query_name',query,file,delimiter from query_db where query_name = '(current)' limit 1 offset 0)";
+if(!$DB->db_auto_exec($qs)) 
+       {
+               html_error(DB_ERROR_MSG.$qs,1);
+       }
+GLM_TOOLBOX::html_header("Saving Query","Saved","");
+?>
+Query is saved as <?echo $query_name?>
+<center><a href="#" onClick="window.close();return(false);">Close This
+Window</a></center>
diff --git a/userArea/Contact/query_save.phtml b/userArea/Contact/query_save.phtml
new file mode 100755 (executable)
index 0000000..61c4a0d
--- /dev/null
@@ -0,0 +1,18 @@
+<html>
+<body bgcolor=white>
+<table bgcolor="#e0e0e0" width=500 cellpadding=4 cellspacing=0 border=0>
+  <tr>
+    <td>Name of Report
+       
+       <form name="form2" action="query_db.phtml" method="POST">
+       <input type="hidden" name="query" value="<?echo $query_string?>">
+       <input type="hidden" name="delimiter" value="<?echo $delimiter?>">
+       <input type="hidden" name="file" value="<?echo $file?>">
+       <input name="query_name">
+       <input type="submit" name="Submit" value="Save">
+       </form>
+       </td>
+</tr>
+</table>
+</body>
+</html>
diff --git a/userArea/Contact/update_autoresponse.phtml b/userArea/Contact/update_autoresponse.phtml
new file mode 100755 (executable)
index 0000000..01f089c
--- /dev/null
@@ -0,0 +1,82 @@
+<?php
+require_once '../../setup.phtml';
+require_once 'contact_setup.inc';
+
+
+switch ($Command) {
+
+case "Update":// {{{
+    $location = "emails.php";
+    $dbh = Toolkit_Database::getInstance();
+    $id       = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);
+    if (!$id) {
+        break;
+    }
+    
+    $sql = "
+    UPDATE news_response 
+       SET subject = :subject,
+           response = :response,
+                  last_update = current_date
+     WHERE id = :id";
+    $update = $dbh->prepare($sql);
+    $update->bindParam(
+        ':subject',
+        stripslashes($subject),
+        PDO::PARAM_STR
+    );
+    $update->bindParam(
+        ':response',
+        stripslashes($response),
+        PDO::PARAM_STR
+    );
+    $update->bindParam(
+        ':id',
+        $id,
+        PDO::PARAM_INT
+    );
+    $update->execute();
+       break;// }}}
+
+case "Insert":// {{{
+    $dbh = Toolkit_Database::getInstance();
+    $sql = "
+    INSERT INTO news_response
+               (last_update,subject,response)
+               VALUES 
+    (current_date,:subject,:response)";
+    $insert = $dbh->prepare($sql);
+    $insert->bindParam(
+        ':subject',
+        stripslashes($subject),
+        PDO::PARAM_STR
+    );
+    $insert->bindParam(
+        ':response',
+        stripslashes($response),
+        PDO::PARAM_STR
+    );
+    $insert->execute();
+       $location = "emails.php"; 
+
+       break;// }}}
+
+case "Cancel":// {{{
+       $location = "emails.php"; 
+       break;// }}}
+
+case "Delete":// {{{
+    $query = "
+    DELETE FROM news_response 
+    WHERE id = $id;";
+    $DB->db_exec( $query );
+    $location = "emails.php"; 
+       break;// }}}
+
+default:// {{{
+       GLM_TOOLBOX::html_error("incorrect value for Command",1);
+       break;// }}}
+}
+
+header("Location: $location");
+?>
diff --git a/userArea/Contact/update_contact.phtml b/userArea/Contact/update_contact.phtml
new file mode 100755 (executable)
index 0000000..84b9e1b
--- /dev/null
@@ -0,0 +1,39 @@
+<?php
+require_once '../../setup.phtml';
+require_once 'contact_setup.inc';
+$location = "list_contact.phtml?back=1&start=" . $start;
+
+if (is_array($contact_type)) {
+       $contact_type = ":".implode(":",$contact_type).":";
+}
+if (is_array($interest)) {
+       $interest = ":".implode(":",$interest).":";
+}
+GLM_TOOLBOX::http_strip($url);
+
+$LAST = count($DB_fields)-1;
+if ($REQUEST_METHOD == "POST" || $Command == "Delete") {
+       switch ($Command) {
+       case "Delete":
+               $qs = "DELETE FROM ".TABLE."
+                          WHERE ".ID." = $id";
+
+               if (!$DB->db_auto_exec($qs)) {
+                       $ERRORS .= pg_errormessage($dbd).$qs;
+        }
+        $location .= '&Action=Contact+Deleted';
+       
+           break;
+
+       case "Cancel":
+           break;
+
+       default:
+                $ERRORS .= "incorrect value for Command";
+           break;
+       
+       }
+
+    header("Location: $location");
+}
+?>
diff --git a/userArea/Contact/update_inquiry.phtml b/userArea/Contact/update_inquiry.phtml
new file mode 100755 (executable)
index 0000000..4d75d05
--- /dev/null
@@ -0,0 +1,118 @@
+<?php
+include "../../setup.phtml";
+include "contact_setup.inc";
+switch ($Command) {
+case "Move":
+    $qs = "select pos,id from contact_inq where id = $id";
+    if (!$result = $DB->db_exec($qs)) {
+        GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+    }
+    $data = $DB->db_fetch_array($result, 0, PGSQL_ASSOC);
+    $pos = $data['pos'];
+    if ($newpos < $pos) {
+        $qs = "select id,pos from contact_inq where pos < $pos and pos >= $newpos and groupid = $groupid order by pos";
+        if(!$res = $DB->db_exec($qs)) {
+            GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+        }
+        $counter = ($newpos + 1);
+        $totalNum = $DB->db_numrows($res);
+        for ($i = 0;$i < $totalNum; $i++) {
+            $res_data = $DB->db_fetch_array($res, $i, PGSQL_ASSOC);
+            $res_id = $res_data['id'];
+            $res_pos = $res_data['pos'];
+            $qs = "update contact_inq set pos = $counter where id = $res_id";
+            if (!$DB->db_exec($qs)) {
+                GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+            }
+            $counter++;
+        }
+    } else {
+        $qs = "select pos,id from contact_inq where pos > $pos and pos <= $newpos and groupid = $groupid order by pos";
+        if (!$res = $DB->db_exec($qs)) {
+            GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+        }
+        $counter = ($pos);
+        $totalNum = $DB->db_numrows($res);
+        for ( $i = 0; $i < $totalNum; $i++) {
+            $res_data = $DB->db_fetch_array($res, $i, PGSQL_ASSOC);
+            $res_id = $res_data['id'];
+            $res_pos = $res_data['pos'];
+            $qs = "update contact_inq set pos = $counter where id = $res_id";
+            if (!$DB->db_exec($qs)) {
+                GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+            }
+            $counter++;
+        }
+    }
+    $qs = "update contact_inq set pos = $newpos where id = $id";
+    if (!$DB->db_exec($qs)) {
+        GLM_TOOLBOX::html_error(DB_ERROR_MSG.$qs, 0);
+    }
+    break;
+
+case "Edit":
+    if ($_POST['new_group']) {
+        $query = "select id from inq_group where name = '".$_POST['new_group']."'";
+        if ($newData = $DB->db_auto_get_data($query)) {
+            // already exists use the id returned
+            $groupid = $newData[0]['id'];
+        } else {
+            $query = "
+            INSERT INTO inq_group
+            (name)
+            VALUES
+            ('{$_POST['new_group']}')
+            RETURNING id";
+            if ($newData = $DB->db_auto_get_data($query)) {
+                $groupid = $newData[0]['id'];
+            }
+        }
+    }
+    $qs = "update contact_inq set header = '$header',image = '$image_name',description = '$description',groupid = $groupid where id = $id;";
+    $DB->db_exec($qs);
+    break;
+
+case "Add":
+    if ($_POST['new_group']) {
+        $query = "select id from inq_group where name = '".$_POST['new_group']."'";
+        if ($newData = $DB->db_auto_get_data($query)) {
+            // already exists use the id returned
+            $groupid = $newData[0]['id'];
+        } else {
+            $query = "
+            INSERT INTO inq_group
+            (name)
+            VALUES
+            ('{$_POST['new_group']}')
+            RETURNING id";
+            if ($newData = $DB->db_auto_get_data($query)) {
+                $groupid = $newData[0]['id'];
+            }
+        }
+    }
+    $qs = "select MAX(pos) as maxpos from contact_inq where groupid = $groupid";
+    $res = $DB->db_exec($qs);
+    $row = $DB->db_fetch_array($res,0,PGSQL_ASSOC);
+    $nextpos = $row[maxpos];
+    $nextpos++;
+    $qs = "insert into contact_inq (header,description,image,pos,groupid) values ('$header','$description','$image_name',$nextpos,$groupid);";
+    $DB->db_exec($qs);
+    break;
+
+case "Delete":
+    $qs = "delete from contact_inq where id = $id";
+    $DB->db_exec($qs);
+    if ($_REQUEST['old_groupid']) {
+       $qs = "select pos,id from contact_inq where pos > $oldpos and groupid = $old_groupid order by pos";
+        $res = $DB->db_exec($qs);
+        $oldcatid_counter = $oldpos;
+        $totalNum = $DB->db_numrows($res);
+        for ($i = 0; $i < $totalNum; $i++) {
+            $row = $DB->db_fetch_array($res, $i, PGSQL_ASSOC);
+            $qs = "update contact_inq set pos = $oldcatid_counter where id = $row[id]";
+        }
+        $DB->db_exec($qs); 
+    }
+    break;
+}
+header("Location: contact_inquiry.phtml");
diff --git a/userArea/Contact/verify.js b/userArea/Contact/verify.js
new file mode 100755 (executable)
index 0000000..a254639
--- /dev/null
@@ -0,0 +1,72 @@
+function isblank(s) {
+       for(var i = 0; i < s.length; i++) {
+               var c = s.charAt(i);
+               if((c != ' ') && (c != '\n') && (c != '\t'))
+                       return(false);
+       }
+       return(true);
+}
+
+function verify(f) {
+       var msg;
+       var empty_fields = "";
+       var errors = "";
+
+       for(var i = 0; i < f.length; i++) {
+               var e = f.elements[i];
+               if(((e.type == "text") || (e.type == "textarea")) && !e.optional) {
+                       if((e.value == null) || (e.value == "") || isblank(e.value)) {
+                               empty_fields += "\n             " + e.r;
+                               continue;
+                       }
+
+                       if(e.d) {
+                               if(isNaN(Date.parse(e.value)))
+                                       errors += "- The field " +e.r+" must be formated like 01/17/2001\n";
+                       }
+                       if(e.numeric || (e.min != null) || (e.max != null)) {
+                               if(e.i) {
+                                       var v = parseInt(e.value);
+                                       if(v != e.value) {
+                                               errors += "- The field " +e.r + " must be a ";
+                                               errors += "number with no decimal\n";
+                                               continue;
+                                       }
+                               }
+                               else
+                                       var v = parseFloat(e.value);
+                               if(isNaN(v) ||
+                                       ((e.min != null) && (v < e.min)) ||
+                                       ((e.max != null) && (v > e.max))) {
+
+                                       errors += "- The field " + e.r + " must be a number";
+                                       if(e.min != null)
+                                               errors += " that is greater than " + e.min;
+                                       if(e.max != null && e.min != null)
+                                               errors += " and less than " + e.max;
+                                       else if (e.max != null)
+                                               errors += " that is less than " + e.max;
+                                       errors += ".\n";
+                               }
+                       }
+               }
+       }
+
+       if(!empty_fields && !errors)
+               return(true);
+
+       msg = "_____________________________________________________\n\n";
+       msg +="The form was not submitted because of the following error(s).\n";
+       msg +="Please correct these error(s) and re-submit.\n";
+       msg +="_____________________________________________________\n\n";
+
+       if(empty_fields) {
+               msg += "- The following required field(s) are empty:"
+                               + empty_fields + "\n";
+               if(errors)
+                       msg += "\n";
+       }
+       msg += errors;
+       alert(msg);
+       return(false);
+}
diff --git a/userArea/Contact/view_newsletter.phtml b/userArea/Contact/view_newsletter.phtml
new file mode 100755 (executable)
index 0000000..1c13387
--- /dev/null
@@ -0,0 +1,22 @@
+<?php
+require_once '../../setup.phtml';
+require_once 'contact_setup.inc';
+define("STYLE","main.css");
+if ($_REQUEST['id'] == '') {
+    $_REQUEST['id'] = 1;
+}
+
+GLM_TOOLBOX::top("AutoReponse for Newsletter", HELP_BASE."response.phtml?key=edit+section");
+GLM_TOOLBOX::html_nav_table($nav,$navWidth);   
+
+echo'<iframe src="preview.phtml?id='.$_REQUEST['id'].'"
+width="780" height="480"
+align="center">
+</iframe>
+
+  </td>
+</tr>
+</table>';
+
+GLM_TOOLBOX::footer();
+?>
diff --git a/userArea/Contact/wm.js b/userArea/Contact/wm.js
new file mode 100755 (executable)
index 0000000..7a7323e
--- /dev/null
@@ -0,0 +1,13 @@
+function glm_open(o) {
+       var x = (screen.width/2) - (o.width/2);
+       var y = (screen.height/2) - (o.height/2);
+       var args = "width="+o.width+",height="+o.height+",screenX="+x+",screenY="+y+",top="+y+",left="+x;
+       if(o.scroll == true)
+               args += ",scrollbars=1";
+       //args += "\'";
+       //alert(args);
+       pow=window.open(o.url,o.name,args);
+       //confirm(args);
+       if (pow.opener == null)
+               pow.opener = self;
+}
diff --git a/userArea/banners.php b/userArea/banners.php
new file mode 100644 (file)
index 0000000..6734e28
--- /dev/null
@@ -0,0 +1,44 @@
+<?php
+require_once '../setup.phtml';
+define('BANNERS_ADMIN_FILE',MEDIA_BASE_URL . 'userArea/banners.php');
+
+require_once './setup.php';
+
+$templateOptions  = $GLOBALS['flexyOptions'];
+$templateOptions['templateDir'] = BASE . 'Toolkit/Banners/templates/';
+$templateOptions['compileDir']  = BASE . 'Toolkit/Banners/templates/compiled/';
+
+$bannerConf = new Config;
+$bannerRoot
+       =& $bannerConf->parseConfig(BASE . 'Toolkit/Banners/config.ini', 'IniFile');
+
+$registry = new Toolkit_Registry;
+$registry->baseUrl =MEDIA_BASE_URL;
+$registry->dbh = Toolkit_Database::getInstance();
+$registry->templateOptions = $templateOptions;
+$registry->logger = Toolkit_Logger::getLogger();
+$registry->config = $bannerRoot;
+$registry->router = new Toolkit_Router($registry);
+$registry->router->setPath(BASE . 'Toolkit/Banners');
+$registry->router->setApplication('Banners');
+
+$navigation = new Toolkit_Banners_Navigation(
+       new HTML_Menu(),
+       new HTML_Menu_DirectRenderer()
+);
+
+$navArray = $navigation->getNavStructure($bannerRoot);
+$navHtml  = $navigation->renderPageNav($navArray, 'rows');
+
+$html = $registry->router->loader();
+
+$appName
+       = $bannerRoot->getItem('section', 'conf')
+       ->getItem('directive', 'applicationName')
+       ->getContent();
+
+$GLOBALS['styleSheets'][] =MEDIA_BASE_URL . 'userArea/main.css';
+GLM_TOOLBOX::top($appName, '', null, false);
+echo $navHtml;
+echo $html;
+GLM_TOOLBOX::footer();
diff --git a/userArea/css/banner.css b/userArea/css/banner.css
new file mode 100644 (file)
index 0000000..226a472
--- /dev/null
@@ -0,0 +1,37 @@
+table.banners,
+table.banners tr {
+       border: 1px solid #17186A;
+       border-collapse: collapse;
+}
+table.banners {
+       border: none;
+       border: 1px solid #17186A;
+       width: 100%;
+       margin: 5px 2px;
+}
+table.banners td.status {
+       text-align: center;
+}
+table.banners a img {
+       border: none;
+}
+table.banners thead th {
+       text-align: center;
+       background: #1D58A5;
+       border: 1px solid #17186A;
+       color: #FFF;
+       padding: 2px 6px;
+}
+table.banners thead a {
+       color: #FFF;
+}
+table.banners tbody tr td {
+       padding: 5px 5px;
+}
+table.banners tbody tr:hover {
+       background: #E3E3E3;
+}
+table.banners a:hover {
+       text-decoration: none;
+}
+
diff --git a/userArea/css/contactform.css b/userArea/css/contactform.css
new file mode 100644 (file)
index 0000000..54ba941
--- /dev/null
@@ -0,0 +1,272 @@
+/* Back end */
+#contact,
+.webform {margin: 10px;}
+
+.req {color: #f00;}
+
+/* Main table */
+#contact table,
+.webform table {
+/*     background-color: #fff;
+       background-color: rgba(255, 255, 255, .3); */
+       border: 1px solid #eee;
+       border-collapse: collapse;
+       padding: 10px;
+       }
+/* Any Table inside the form */
+#contact table table,
+.webform table table {
+       width: 100%;
+       margin-left: 0;
+       border: 0px solid #ddd;
+       }
+#contact table table td,
+.webform table table td        {
+       border: 0px solid #ddd;
+       }
+
+/* TD's */
+#contact td,
+.webform td {
+       padding: 3px;
+       color: #000;
+       border: 1px solid #eee;
+       border-collapse: collapse;
+       padding: 5px;
+       }
+/* Left Cells */
+.labelcell {
+       background-color: transparent;
+       text-align: right;
+       padding-right: 10px;
+       padding-top: 3px;
+       white-space:nowrap;
+       width: 140px;
+       }
+/*Right Cells */
+.fieldcell {
+       padding-left: 4px;
+       width: 250px;
+       }
+
+/* Misc */
+textarea {width: 95%; height: 100px; display:block;}
+
+/* WARNINGS */
+#form-warning-top {
+       margin-top: 1em;
+       margin-bottom: 0.5em;
+       color: #f00;
+       font-size: 14px;
+       font-weight: bold;
+       }
+/* SHow hide instruction div */
+#contact table tr td .form-warning-inside,
+.webform table tr td .form-warning-inside {
+       display: none;
+       }
+#contact table tr.req td .form-warning-inside,
+.webform table tr.req td .form-warning-inside {
+       display: block;
+       background-image: url('../../../../images/error.gif');
+       background-repeat:no-repeat;
+       background-position: top left;
+       padding: 2px 2px 2px 22px;
+}
+
+/* Showing hiding rows */
+/*invisible*/
+#contact table tr td.instructioncell,
+.webform table tr td.instructioncell {
+       width: 200px;
+       white-space: nowrap;
+       color: #fff;
+       }
+
+/*visible*/
+table tr.req {
+       border: 2px solid #f00;
+       background-color:#FCD6D4;
+       border-collapse: separate;
+       border-collapse: collapse;
+}
+/*color*/
+table tr.req td                        { background-color: #fcd6d4;}
+table tr.req td.labelcell      { background-color: #FCD6D4; }
+table tr.req td.fieldcell      { background-color: #FCD6D4; }
+table tr.req td.instructioncell        { background-color: #FCD6D4; }
+table tr.req td.instructioncell {
+       padding: 4px;
+       padding-left: 20px;
+       background-image: url('../../../../images/error.gif');
+       background-repeat:no-repeat;
+       background-position: center left;
+       border-width: 0;
+       color: #000;
+       }
+.glmCheckBox {
+       width: 200px;
+       float: left;
+}
+.single-checkbox label.glmCheckBox {
+    width: auto;
+    float: none;
+}
+
+/* Front here from here */
+#toolbox #contact,
+#toolbox .webform {margin: 10px;}
+
+#toolbox .req {color: #f00;}
+
+/* Main table */
+#toolbox #contact table,
+#toolbox .webform table {
+/*     background-color: #fff;
+       background-color: rgba(255, 255, 255, .1); */
+       border: 0px solid #eee;
+       border-collapse: collapse;
+       padding: 10px;
+       }
+/* Any Table inside the form */
+#toolbox #contact table table,
+#toolbox .webform table table {
+       width: 100%;
+       margin-left: 0;
+       border: 0px solid #ddd;
+       }
+#toolbox #contact table table td,
+#toolbox .webform table table td       {
+       border: 0px solid #ddd;
+       }
+
+/* TD's */
+#toolbox #contact td,
+#toolbox .webform td {
+       padding: 3px;
+       color: #000;
+       border: 0px solid #eee;
+       border-collapse: collapse;
+       padding: 5px;
+       /*color: #656565;*/
+       }
+/* Left Cells */
+#toolbox .labelcell {
+       background-color: transparent;
+       text-align: right;
+       padding-right: 10px;
+       padding-top: 3px;
+       white-space:nowrap;
+       width: 140px;
+       }
+#toolbox .labelcell label {
+       color: white !important;
+       }
+/*Right Cells */
+#toolbox .fieldcell {
+       padding-left: 4px;
+       width: 250px;
+       }
+
+/* Misc */
+#toolbox textarea {width: 95%; height: 100px; display:block;}
+
+/* WARNINGS */
+#toolbox #form-warning-top {
+       margin-top: 1em;
+       margin-bottom: 0.5em;
+       color: #f00;
+       font-size: 14px;
+       font-weight: bold;
+       }
+/* SHow hide instruction div */
+#toolbox #contact table tr td .form-warning-inside,
+#toolbox .webform table tr td .form-warning-inside {
+       display: none;
+       }
+#toolbox #contact table tr.req td .form-warning-inside,
+#toolbox .webform table tr.req td .form-warning-inside {
+       display: block;
+       background-image: url('../../../../images/error.gif');
+       background-repeat:no-repeat;
+       background-position: top left;
+       padding: 2px 2px 2px 22px;
+}
+
+/* Showing hiding rows */
+/*invisible*/
+#toolbox #contact table tr td.instructioncell,
+#toolbox .webform table tr td.instructioncell {
+       width: 200px;
+       white-space: nowrap;
+       color: #fff;
+       }
+
+/*visible*/
+#toolbox table tr.req {
+       border: 2px solid #f00;
+       background-color:#FCD6D4;
+       border-collapse: separate;
+       border-collapse: collapse;
+}
+/*color*/
+#toolbox table tr.req td                       { background-color: #fcd6d4;}
+#toolbox table tr.req td.labelcell     { background-color: #FCD6D4; }
+#toolbox table tr.req td.fieldcell     { background-color: #FCD6D4; }
+#toolbox table tr.req td.instructioncell       { background-color: #FCD6D4; }
+#toolbox table tr.req td.instructioncell {
+       padding: 4px;
+       padding-left: 20px;
+       background-image: url('../../../../images/error.gif');
+       background-repeat:no-repeat;
+       background-position: center left;
+       border-width: 0;
+       color: #000;
+       }
+#toolbox .glmCheckBox {
+       width: 200px;
+       float: left;
+}
+#toolbox .single-checkbox label.glmCheckBox {
+    width: auto;
+    float: none;
+}
+/* Tooltip */
+#toolbox .tooltip {
+       font-size: 13px;
+       font-size: 1.3rem;
+       border-bottom: 1px dashed white;
+       color: #ccc;
+       margin-left: 5px;
+       }
+/* Headers */
+#toolbox .hdr td {
+       font-weight: bold;
+       padding: 15px 10px 10px 10px;
+       background: rgba(255, 255, 255, .1);
+       }
+
+/* EMployment form */
+form#employment_form td.labelcell {
+       white-space: normal;
+       width: 250px !important;
+       }
+form#employment_form td.fieldcell {
+       width: 300px;
+       }
+form#employment_form td input[type=text] {
+       width: 290px;
+       }
+form#employment_form td textarea {
+       width: 290px;
+       }
+form#employment_form td select {
+       clear: left;
+       display: block;
+       }
+form#employment_form td {
+       border: 1px solid rgba(255, 255, 255, .05) !important;
+       }
+form#employment_form .captcha img {
+       padding-left: 150px;
+       }
diff --git a/userArea/css/main.css b/userArea/css/main.css
new file mode 100755 (executable)
index 0000000..7028212
--- /dev/null
@@ -0,0 +1,128 @@
+
+.clearer {
+ height:1px;
+ overflow:hidden;
+ margin-top:-1px;
+ clear:left;
+}
+h1 {font-size: 18px; color: #777;}
+form {margin: 0; padding: 0;}
+/* TOOLBOX NAV */
+ul#toolbox {list-style-position:inside;list-style-type:circle;}
+ul#toolbox li {list-style-type:circle}
+ul#toolbox li.toolboxArrow {list-style-type:none;padding-left:0;margin-left:-7px;}
+* html ul#toolbox li.toolboxArrow {margin-left:-20px;} /*style for IE*/
+/* APP  Nav*/
+ul.admin_nav 
+{
+margin: 0;
+list-style-type: none;
+padding: 5px 0;
+}
+ul.admin_nav li { display: inline; }
+ul.admin_nav li a
+{
+border-top: 1px solid #eee;
+border-right: 1px solid #ccc;
+border-bottom: 1px solid #ccc;
+border-left: 1px solid #eee;
+text-decoration: none;
+background-color: #ddd;
+color: #000;
+padding: 2px 6px;
+margin: 0 1px;
+font-weight: bold;
+font-size: 12px;
+}
+ul.admin_nav.current { color: #111 }
+#admin-list-table {clear:left;width:500px;}
+#admin-list-table td {
+       border: 2px solid #ccc;
+       border-collapse: collapse;
+       background: #eee;
+       padding: 4px;}  
+/*#admin-list-table img {border: 0; text-align: center; margin: 0 auto; display: block;}*/
+#admin-list-table a:link {color: #666;}
+#admin-list-table a:visited {color: #666;}
+#admin-list-table a:active {color: #666;}
+#admin-list-table a:hover {color: #000;}
+
+/*event-edit-table */
+#admin-edit-table {
+       clear:left;
+       font-family: arial, helvetica, sans-serif;
+       border: 2px solid #ccc;
+       border-collapse: collapse;
+       font-size: 12px;
+       }
+#admin-edit-table td {
+       border: 2px solid #ccc;
+       border-collapse: collapse;
+       background: #eee;       padding: 4px;}          
+#admin-list-table table td {border:none;padding:0;margin:0;}
+#admin-edit-table table td {border:none;padding:0;margin:0;}
+#admin-edit-table select,
+#admin-edit-table input,
+#admin-edit-table option {font-size: 12px;}
+#glm-manual {position:absolute;right:200px;top:10px;width:300px;}
+#glm-manual a {padding:5px 2px;width:149px;background-color:#DDDDDD;color:#000;}
+div.fileupload { border:1px solid black;float:left;margin:5px; padding:5px;background-color:white; color:black; }
+div.fileupload p { margin:0; padding:0;float:left; }
+div.fileupload span { background-color:#c0c0c0;  }
+.level-0 {
+        font-weight: bold;
+        padding-left: 0;
+        background-color: #ccc;
+}
+.level-1 {
+        padding-left: 20px;
+        background-color: #ddd;
+        }
+.level-2 {padding-left: 40px;}
+.level-3 {padding-left: 60px;}
+.level-4 {padding-left: 80px;}
+.level-5 {padding-left: 100px;}
+.level-6 {padding-left: 120px;}
+.pager {
+       text-align: center;
+       background: #F6F6F6;
+       border-color: #DDD;
+       border-style: solid;
+       border-width: 1px 0;
+       margin: 1.0em 0;
+       padding: 8px 0;
+       text-align: center;
+       width: 100%;
+       font-size: 12px;
+
+}
+.pager b {
+       border: 1px solid #CCC;
+       border: 1px solid #17186A;
+       background: #FFF;
+       padding: 5px 7px;
+}
+.pager a {
+       background: #FFF;
+       border: 1px solid #CCC;
+       padding: 5px 7px;
+       text-decoration: none;
+       color: #000;
+}
+.pager a:hover {
+       border: 1px solid #999;
+       border: 1px solid #17186A;
+}
+#form-wrap legend {
+       color: #fff;
+       background: #1D58A5;
+       border: 1px solid #17186A;
+       padding: 2px 6px;
+}
+#form-wrap p {margin:1px;}
+#form-wrap label {
+       float: none;
+       margin-right: 0;
+       display: inline;
+       clear: left;
+}
\ No newline at end of file
diff --git a/userArea/index.php b/userArea/index.php
new file mode 100644 (file)
index 0000000..518a364
--- /dev/null
@@ -0,0 +1,102 @@
+<?php
+require_once '../setup.phtml';
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+if (defined('DEVELOPMENT') && DEVELOPMENT) {
+    require_once 'FirePHPCore/FirePHP.class.php';
+    $firephp = FirePHP::getInstance(true);
+    $firephp->registerErrorHandler();
+    $firephp->registerExceptionHandler();
+    Registry::add($firephp);
+}
+
+$authContainer = new Toolkit_UserArea_Auth_Container(
+    Toolkit_Database::getInstance()
+);
+
+$userAuth = new Toolkit_UserArea_Auth(
+    $authContainer,
+    '',
+    true
+);
+//var_dump($userAuth);exit;
+$userAuth->setIdle();
+ob_start();
+$userAuth->start();
+$loginForm = ob_get_contents();
+ob_end_clean();
+
+Registry::add($userAuth);
+
+if (isset($_GET['logout'])) {
+    $userAuth->logout();
+    header('Location: ' .MEDIA_BASE_URL . 'userArea/index.php');
+    exit;
+}
+
+if ($userAuth->checkAuth()) {
+    $flexyOptions = $GLOBALS['flexyOptions'];
+    $flexyOptions['templateDir'] = BASE . 'userArea/templates';
+    $flexyOptions['compileDir']  = BASE . 'userArea/templates/compiled';
+    $tpl = new HTML_Template_Flexy($flexyOptions);
+    $page = new stdClass();
+    $page->siteName = SITENAME;
+    $page->pageUrl = isset($_GET['page']) ? $_GET['page'] : 'splash.php';
+    $tpl->compile('frameSet.html');
+    $tpl->outputObject($page);
+} else {
+
+    //    Create a new registry so we don't pollute the global namespace
+    $registry = new Toolkit_Registry;
+
+    $registry->cacheOptions = $GLOBALS['cacheOptions'];
+    $registry->flexyOptions = $GLOBALS['flexyOptions'];
+    $registry->catid        = HOME_ID;
+    $registry->dbh          = Toolkit_Database::getInstance();
+    $registry->logger       = Toolkit_Logger::getLogger();
+
+    //    Initiate HTML_Template_Flexy.
+    $template = new HTML_Template_Flexy($registry->flexyOptions);
+    $keywordReplacement = new Toolkit_Template_KeywordReplacement(
+        new Toolkit_Toolbox_PageGatewayPublish(
+            $registry->dbh
+        )
+    );
+    $breadCrumbsFactory = new Toolkit_BreadCrumbsFactory(
+        new Toolkit_Toolbox_PageGatewayPublishFactory(
+            $registry->dbh
+        )
+    );
+
+    //    Page object used for merging with the flexy template object.
+    //    now using the page class from toolkit
+    $glmPage = new Toolkit_Page(
+        new Toolkit_Template_Page(),
+        $breadCrumbsFactory,
+        new Toolkit_Toolbox_PageGatewayPublishFactory(
+            $registry->dbh
+        ),
+        new Toolkit_Toolbox_ParagraphGatewayPublishFactory(
+            $registry->dbh
+        ),
+        new Toolkit_Template_Navigation_Factory(),
+        $keywordReplacement,
+        $registry->catid
+    );
+$_REQUEST['sitemap'] = true;
+    $glmPage->fetchPage();
+
+    $glmPage->toolboxContent = $loginForm;
+//die('hello');
+    $glmPage->topScripts
+        = Toolkit_Common::getScripts($GLOBALS['topScripts']);
+    $glmPage->bottomScripts
+        = Toolkit_Common::getScripts($GLOBALS['bottomScripts']);
+    $glmPage->styles        = Toolkit_Common::getStyleSheets();
+
+    //    Compile the template.html from the templates directory.
+    $template->compile('template.html');
+    //    Merge compiled template with the $glmPage object.
+    echo $template->outputObject($glmPage);
+}
diff --git a/userArea/login.php b/userArea/login.php
new file mode 100644 (file)
index 0000000..800076a
--- /dev/null
@@ -0,0 +1,34 @@
+<?php
+include_once '../setup.phtml';
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+$authContainer = new Toolkit_UserArea_Auth_Container(
+       Toolkit_Database::getInstance()
+);
+
+$userAuth = new Toolkit_UserArea_Auth(
+       $authContainer,
+       '',
+       false
+);
+$userAuth->setIdle();
+$userAuth->start();
+
+if (isset($_GET['logout'])) {
+       $userAuth->logout();
+    header('Location: ' .MEDIA_BASE_URL . 'userArea/index.php');
+    exit;
+}
+
+if (!$userAuth->checkAuth()) {
+       //      Manually adjust the authentication status for empty credentials
+       if (empty($_POST['username']) || empty($_POST['password'])) {
+               $status = -3;
+       }
+       $status = $userAuth->getStatus();
+//    var_dump($status);exit;
+       header('Location: ' .MEDIA_BASE_URL . 'userArea/index.php?status=' . $status);
+} else {
+    header('Location: ' .MEDIA_BASE_URL . 'userArea/index.php');
+}
\ No newline at end of file
diff --git a/userArea/main.css b/userArea/main.css
new file mode 100644 (file)
index 0000000..e3346d5
--- /dev/null
@@ -0,0 +1,132 @@
+body {
+       padding-left: 50px;
+       font-family: arial, helvetica, sans-serif;
+       font-size: 12px;
+       }
+.clearer {
+ height:1px;
+ overflow:hidden;
+ margin-top:-1px;
+ clear:left;
+}
+h1 {font-size: 18px; color: #777;}
+form {margin: 0; padding: 0;}
+/* TOOLBOX NAV */
+ul#toolbox {list-style-position:inside;list-style-type:circle;}
+ul#toolbox li {list-style-type:circle}
+ul#toolbox li.toolboxArrow {list-style-type:none;padding-left:0;margin-left:-7px;}
+* html ul#toolbox li.toolboxArrow {margin-left:-20px;} /*style for IE*/
+/* APP  Nav*/
+ul.admin_nav 
+{
+margin: 0;
+list-style-type: none;
+padding: 5px 0;
+}
+ul.admin_nav li { display: inline; }
+ul.admin_nav li a
+{
+border-top: 1px solid #eee;
+border-right: 1px solid #ccc;
+border-bottom: 1px solid #ccc;
+border-left: 1px solid #eee;
+text-decoration: none;
+background-color: #ddd;
+color: #000;
+padding: 2px 6px;
+margin: 0 1px;
+font-weight: bold;
+font-size: 12px;
+}
+ul.admin_nav.current { color: #111 }
+#admin-list-table {clear:left;width:500px;}
+#admin-list-table td {
+       border: 2px solid #ccc;
+       border-collapse: collapse;
+       background: #eee;
+       padding: 4px;}  
+/*#admin-list-table img {border: 0; text-align: center; margin: 0 auto; display: block;}*/
+#admin-list-table a:link {color: #666;}
+#admin-list-table a:visited {color: #666;}
+#admin-list-table a:active {color: #666;}
+#admin-list-table a:hover {color: #000;}
+
+/*event-edit-table */
+#admin-edit-table {
+       clear:left;
+       font-family: arial, helvetica, sans-serif;
+       border: 2px solid #ccc;
+       border-collapse: collapse;
+       font-size: 12px;
+       }
+#admin-edit-table td {
+       border: 2px solid #ccc;
+       border-collapse: collapse;
+       background: #eee;       padding: 4px;}          
+#admin-list-table table td {border:none;padding:0;margin:0;}
+#admin-edit-table table td {border:none;padding:0;margin:0;}
+#admin-edit-table select,
+#admin-edit-table input,
+#admin-edit-table option {font-size: 12px;}
+#glm-manual {position:absolute;right:200px;top:10px;width:300px;}
+#glm-manual a {padding:5px 2px;width:149px;background-color:#DDDDDD;color:#000;}
+div.fileupload { border:1px solid black;float:left;margin:5px; padding:5px;background-color:white; color:black; }
+div.fileupload p { margin:0; padding:0;float:left; }
+div.fileupload span { background-color:#c0c0c0;  }
+.level-0 {
+        font-weight: bold;
+        padding-left: 0;
+        background-color: #ccc;
+}
+.level-1 {
+        padding-left: 20px;
+        background-color: #ddd;
+        }
+.level-2 {padding-left: 40px;}
+.level-3 {padding-left: 60px;}
+.level-4 {padding-left: 80px;}
+.level-5 {padding-left: 100px;}
+.level-6 {padding-left: 120px;}
+.pager {
+       text-align: center;
+       background: #F6F6F6;
+       border-color: #DDD;
+       border-style: solid;
+       border-width: 1px 0;
+       margin: 1.0em 0;
+       padding: 8px 0;
+       text-align: center;
+       width: 100%;
+       font-size: 12px;
+
+}
+.pager b {
+       border: 1px solid #CCC;
+       border: 1px solid #17186A;
+       background: #FFF;
+       padding: 5px 7px;
+}
+.pager a {
+       background: #FFF;
+       border: 1px solid #CCC;
+       padding: 5px 7px;
+       text-decoration: none;
+       color: #000;
+}
+.pager a:hover {
+       border: 1px solid #999;
+       border: 1px solid #17186A;
+}
+#form-wrap legend {
+       color: #fff;
+       background: #1D58A5;
+       border: 1px solid #17186A;
+       padding: 2px 6px;
+}
+#form-wrap p {margin:1px;}
+#form-wrap label {
+       float: none;
+       margin-right: 0;
+       display: inline;
+       clear: left;
+}
\ No newline at end of file
diff --git a/userArea/members.php b/userArea/members.php
new file mode 100755 (executable)
index 0000000..a550042
--- /dev/null
@@ -0,0 +1,39 @@
+<?php
+require_once '../setup.phtml';
+define('MEMBERS_ADMIN_FILE', MEDIA_BASE_URL . 'userArea/members.php');
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start('MemberDB');
+
+$GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'Toolkit/Members/css/member-admin.css';
+$GLOBALS['topScripts'][] = MEDIA_APP_BASE_URL
+    . 'libjs/jqueryui/1.8.13/js/jquery-1.5.1.min.js';
+
+$controllerObject = new stdClass();
+$dbh = Toolkit_Database::getInstance();
+$membersConf = new Config;
+$membersRoot =& $membersConf->parseConfig(
+    BASE . 'Toolkit/Members/config.ini',
+    'IniFile'
+);
+
+$navigation = new Toolkit_Members_Admin_Navigation(
+    new HTML_Menu(),
+    new HTML_Menu_DirectRenderer()
+);
+$navArray = $navigation->getNavStructure($dbh, $membersRoot);
+$controllerObject->nav = $navigation->renderPageNav($navArray, 'rows');
+
+$registry = new Toolkit_Registry;
+$registry->dbh = $dbh;
+$registry->logger = Toolkit_Logger::getLogger();
+$registry->controllerObject = $controllerObject;
+$registry->tEngine = new HTML_Template_Flexy(Toolkit_Members::getFlexyOptions());
+$registry->config = $membersRoot;
+$registry->router = new Toolkit_Router($registry);
+$registry->router->setPath(BASE . 'Toolkit/Members/Admin');
+$registry->router->setApplication('Members/Admin');
+
+$html = $registry->router->loader();
+
+echo $navHtml;
+echo $html;
diff --git a/userArea/nav.php b/userArea/nav.php
new file mode 100644 (file)
index 0000000..eafb352
--- /dev/null
@@ -0,0 +1,114 @@
+<?php
+include_once '../setup.phtml';
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+$authContainer = new Toolkit_UserArea_Auth_Container(
+    Toolkit_Database::getInstance()
+);
+
+$userAuth = new Toolkit_UserArea_Auth(
+    $authContainer,
+    '',
+    false
+);
+$userAuth->setIdle();
+$userAuth->start();
+?>
+<!DOCTYPE HTML>
+<html lang="en">
+<head>
+<title>User Area Navigation</title>
+<style type="text/css">
+body {margin: 2px; font-family: arial, sans-serif; font-size: 12px; background-color: #fff;}
+a:link {color: #004C64;}
+a:visited {color: #004C64;}
+a:hover {color: #2C788F;}
+a:active {color: #004C64;}
+
+h1 {
+    font-weight: bold;
+    text-align: center;
+    font-size: 14px;
+    text-indent: -3000px;
+    width: 130px;
+    height: 53px;
+    margin-left: 10px;
+    }
+ul { margin: 0; padding: 0; list-style-type: none; }
+li { margin: 0; padding: 0; display: block;    }
+li a {
+    text-decoration: none;
+    display: block;
+    margin: 0;
+    padding: 4px 8px;
+    background-color: #004C64;
+    border-bottom: 1px solid #eee;
+    width: 136px;
+    }
+li a:link, li a:visited, li a:active { color: #EEE; }
+li a:hover { background-color: #2C788F; color: #fff; }
+</style>
+</head>
+<body>
+    <h1><a href="<?php echo MEDIA_BASE_URL.$url;?>" target="_top"><?php echo SITENAME;?></a></h1>
+<ul>
+<?php
+$dbh = Toolkit_Database::getInstance();
+$conf = new Config;
+
+$nav['Home'] =MEDIA_BASE_URL.'userArea/splash.php';
+try {
+    $sql = "
+    SELECT navigation_name
+      FROM toolbox.pages
+     WHERE id = :id";
+    $getPageName = $dbh->prepare($sql);
+} catch (PDOException $e) {
+    Toolkit_Common::handleError($e);
+}
+
+if ($userAuth->isUserActive($dbh)) {
+    $authData    = $userAuth->getAuthData();
+    $mapper      = new Toolkit_UserArea_Models_Mapper();
+    $user        = $mapper->fetchUserById($dbh, $authData['id']);
+    $userAppData = $mapper->fetchAllUserApps($dbh, $user);
+    $userApps    = array();
+    if ($userAppData) {
+        foreach ($userAppData as $uApp) {
+            $app = $mapper->fetchAppById($dbh, $uApp->getAppId());
+            if (  $uApp->getAppId() == Toolkit_UserArea_Admin_IndexController::TOOLBOX_APP_ID
+                && $uApp->getConfig()
+            ) {
+                $getPageName->bindParam(':id', $uApp->getConfig(), PDO::PARAM_INT);
+                $getPageName->execute();
+                $pageName = $getPageName->fetchColumn();
+                $nav['Toolbox - ' . $pageName] = $app->getPage()
+                    . '?pageId=' . $uApp->getConfig();
+            } else {
+                $nav[$app->getName()] = $app->getPage();
+            }
+        }
+    }
+}
+foreach ($nav as $name => $url) {
+    echo '
+        <li>
+            <a href="'.$url.'" target="Main">'.$name.'</a>
+        </li>';
+}
+?>
+<li>
+    <a href="<?php echo MEDIA_BASE_URL?>userArea/index.php?logout=1" target="_parent">Log Out</a>
+</li>
+</ul>
+
+<a
+    style="display: block; margin: 10px auto; text-align: center;"
+    href="http://www.gaslightmedia.com/"
+    target="_blank"><img alt=""
+        src="https://app.gaslightmedia.com/assets/poweredby.gif"
+        border="0"
+        title="Gaslight Media Website"></a>
+</body>
+</html>
diff --git a/userArea/photos.php b/userArea/photos.php
new file mode 100644 (file)
index 0000000..04d9864
--- /dev/null
@@ -0,0 +1,22 @@
+<?php
+require_once '../setup.phtml';
+require_once 'setup.php';
+// Registry Object to hold global objects and setting for application
+$registry = new Toolkit_Registry;
+// create a Zend Config Object and store into Registry
+$config = new Zend_Config_Ini(
+    BASE . 'Toolkit/Photos/application.ini',
+    strtolower($_ENV['GLM_HOST_ID'])
+);
+$registry->config = $config;
+$registry->page   = MEDIA_BASE_URL . 'userArea/photos.php';
+$appConfig        = $config->application->toArray();
+$registry->dbh    = Toolkit_Database::getInstance();
+$registry->logger = Toolkit_Logger::getLogger();
+$registry->router = new Toolkit_Router($registry);
+$registry->router->setPath($appConfig['path']);
+$registry->router->setApplication($appConfig['application']);
+
+$html = $registry->router->loader();
+
+echo $html;
diff --git a/userArea/setup.php b/userArea/setup.php
new file mode 100644 (file)
index 0000000..3d3f5ea
--- /dev/null
@@ -0,0 +1,38 @@
+<?php
+HTTP_Session2::useCookies(false);
+HTTP_Session2::start();
+
+if (defined('DEVELOPMENT') && DEVELOPMENT) {
+    require_once 'FirePHPCore/FirePHP.class.php';
+    $firephp = FirePHP::getInstance(true);
+    $firephp->registerErrorHandler();
+    $firephp->registerExceptionHandler();
+    Registry::add($firephp);
+}
+
+$authContainer = new Toolkit_UserArea_Auth_Container(
+    Toolkit_Database::getInstance()
+);
+
+$userAuth = new Toolkit_UserArea_Auth(
+    $authContainer,
+    '',
+    true
+);
+$userAuth->setIdle();
+ob_start();
+$userAuth->start();
+ob_end_clean();
+
+Registry::add($userAuth);
+
+if (isset($_GET['logout'])) {
+    $userAuth->logout();
+    header('Location: ' .MEDIA_BASE_URL . 'userArea/index.php');
+    exit;
+}
+
+if (!$userAuth->checkAuth()) {
+    header('Location: ' .MEDIA_BASE_URL . 'userArea/index.php');
+    exit;
+}
diff --git a/userArea/slideshow.php b/userArea/slideshow.php
new file mode 100644 (file)
index 0000000..566edae
--- /dev/null
@@ -0,0 +1,44 @@
+<?php
+require_once '../setup.phtml';
+require_once 'setup.php';
+define('SLIDESHOW_ADMIN_FILE', MEDIA_BASE_URL . 'userArea/slideshow.php');
+$rotatingImagesConf = new Config;
+$rotatingImagesRoot =& $rotatingImagesConf->parseConfig(
+    BASE . 'Toolkit/RotatingImages/config.ini',
+    'IniFile'
+);
+
+$registry = new Toolkit_Registry;
+$registry->dbh = Toolkit_Database::getInstance();
+$registry->logger = Toolkit_Logger::getLogger();
+$registry->config = $rotatingImagesRoot;
+$registry->router = new Toolkit_Router($registry);
+$registry->router->setPath(BASE . 'Toolkit/RotatingImages');
+$registry->router->setApplication('RotatingImages');
+
+$navigation = new Toolkit_RotatingImages_Navigation(
+    new HTML_Menu(),
+    new HTML_Menu_DirectRenderer()
+);
+
+$navArray = $navigation->getNavStructure($rotatingImagesRoot);
+$navHtml  = $navigation->renderPageNav($navArray, 'rows');
+
+$html = $registry->router->loader();
+
+$appName
+    = $rotatingImagesRoot->getItem('section', 'conf')
+    ->getItem('directive', 'applicationName')
+    ->getContent();
+$GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'userArea/main.css';
+if (filter_input(INPUT_GET, 'ac') == 'preview') {
+    GLM_TOOLBOX::top('', '', null, false);
+    echo $html;
+    GLM_TOOLBOX::footer();
+} else {
+    GLM_TOOLBOX::top($appName, '', null, false);
+    echo $navHtml;
+    echo $html;
+    GLM_TOOLBOX::footer();
+}
+?>
diff --git a/userArea/splash.php b/userArea/splash.php
new file mode 100644 (file)
index 0000000..f98b016
--- /dev/null
@@ -0,0 +1,22 @@
+<?php
+include '../setup.phtml';
+// require that the user is Authenticated to get pass this part.
+
+?>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+ "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+<link type="text/css" rel="stylesheet" href="main.css">
+<title>Welcome to GLM Toolbox - User Area</title>
+</head>
+<body>
+
+<div style="text-align: center;">
+<p><strong>Welcome To The <?php echo SITENAME;?> User Area</strong></p>
+<p>Please Choose The Area You Wish To Update.</p>
+<img src="<?php echo MEDIA_BASE_URL."images/logo.gif";?>">
+</div>
+
+</body>
+</html>
\ No newline at end of file
diff --git a/userArea/templates/frameSet.html b/userArea/templates/frameSet.html
new file mode 100644 (file)
index 0000000..c9037ce
--- /dev/null
@@ -0,0 +1,21 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
+ "http://www.w3.org/TR/html4/frameset.dtd">
+<html>
+<head>
+    <title>{siteName} Administration</title>
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+</head>
+<frameset cols="160,*">
+    <frame name="Nav" src="nav.php" frameborder="0">
+    <frame name="Main" src="{pageUrl:h}" frameborder="0">
+    <noframes>
+        <p>Admin Requires Frames Capable Browser</p>
+        You can get a Standard Compliant browser from:
+        <ul>
+            <li>Google <a href="http://www.google.com/chrome">Chrome</a></li>
+            <li>Mozilla's <a href="http://www.mozilla.org/products/firefox/">Firefox</a></li>
+            <li>Microsoft <a href="http://www.microsoft.com/windows/ie/">Internet Explorer</a></li>
+        </ul>
+    </noframes>
+</frameset>
+</html>
diff --git a/userArea/templates/loginPage.html b/userArea/templates/loginPage.html
new file mode 100644 (file)
index 0000000..5748d0a
--- /dev/null
@@ -0,0 +1,40 @@
+<!DOCTYPE HTML>
+<html lang="en">
+    <head>
+        <meta charset="utf-8">
+        <title>Login for User Area</title>
+        <link rel="stylesheet" href="css/main.css">
+        <link rel="stylesheet" href="css/contactform.css">
+    </head>
+    <body>
+        <div class="webform">
+
+        {form.javascript:h}
+        {form.outputHeader():h}
+        {form.hidden:h}
+        <table class="maintable" width="600" align="center">
+            <?php
+            if ($_REQUEST['status']) {
+                if ($_REQUEST['status'] == '-3') {
+                    echo '<tr><td colspan="2">
+                    <div id="form-warning-top">Wrong Login!</div>
+                    </td></tr>';
+                }
+            }
+            ?>
+            <tr>
+                <td>{form.username.label:h}</td>
+                <td>{form.username.html:h}</td>
+            </tr>
+            <tr>
+                <td>{form.password.label:h}</td>
+                <td>{form.password.html:h}</td>
+            </tr>
+            <tr>
+                <td colspan="2">{form.doLogin.html:h}</td>
+            </tr>
+        </table>
+    </form>
+    </div>
+</body>
+</html>
diff --git a/userArea/toolbox.php b/userArea/toolbox.php
new file mode 100644 (file)
index 0000000..cb44913
--- /dev/null
@@ -0,0 +1,46 @@
+<?php
+
+require_once '../setup.phtml';
+require_once './setup.php';
+if ($pageId = filter_var($_REQUEST['pageId'], FILTER_VALIDATE_INT)) {
+    $_SESSION['pageId'] = $pageId;
+    define('AUTH_USER_PAGE_ID', $pageId);
+} else if ($pageId = filter_var($_SESSION['pageId'], FILTER_VALIDATE_INT)) {
+    define('AUTH_USER_PAGE_ID', $pageId);
+} else {
+    var_dump($_SESSION);
+    return false;
+}
+$registry           = new Toolkit_Registry;
+$registry->dbh      = Toolkit_Database::getInstance();
+$registry->authUser = $userAuth;
+$registry->logger   = Toolkit_Logger::getLogger();
+$registry->router   = new Toolkit_Router($registry);
+$registry->router->setPath(BASE . 'Toolkit/UserArea');
+$registry->router->setApplication('UserArea');
+
+$tlbConf = new Config;
+$tbxRoot
+    = & $tlbConf->parseConfig(BASE . 'Toolkit/UserArea/config.ini', 'IniFile');
+
+$navigation = new Toolkit_UserArea_Navigation(
+    new HTML_Menu(), new HTML_Menu_DirectRenderer()
+);
+
+$navArray = $navigation->getNavStructure($tbxRoot);
+$navHtml  = $navigation->renderPageNav($navArray, 'rows');
+
+$html = $registry->router->loader();
+
+$appName
+    = $tbxRoot->getItem('section', 'conf')
+    ->getItem('directive', 'applicationName')
+    ->getContent();
+
+GLM_TOOLBOX::topUserArea($appName, '');
+echo '<div
+        style="position:absolute;top:2px;right:5px;padding:5px;float:right;width:165px;background-color:#dddddd;"><a style="color:#000000;"
+        href="http://app.gaslightmedia.com/docs/ToolboxHelpGuide.pdf" target="_blank">Printable Toolbox Help Guide</a></div>';
+echo $navHtml;
+echo $html;
+GLM_TOOLBOX::footer();
diff --git a/userArea/verify.js b/userArea/verify.js
new file mode 100755 (executable)
index 0000000..baef158
--- /dev/null
@@ -0,0 +1,107 @@
+function isblank(s) {
+       for(var i = 0; i < s.length; i++) {
+               var c = s.charAt(i);
+               if((c != ' ') && (c != '\n') && (c != '\t'))
+                       return(false);
+       }
+       return(true);
+}
+
+function verify(f) {
+       var msg;
+       var empty_fields = "";
+       var errors = "";
+
+       for(var i = 0; i < f.length; i++) {
+               var e = f.elements[i];
+               if(((e.type == "text") || (e.type == "password") ||(e.type == "textarea")) && !e.optional && e.r != undefined) {
+                       if((e.value == null) || (e.value == "") || isblank(e.value)) {
+                               empty_fields += "\n             " + e.r;
+                               continue;
+                       }
+
+                       if(e.d) {
+                               if(isNaN(Date.parse(e.value)))
+                                       errors += "- The field " +e.r+" must be formated like 01/17/2001\n";
+                       }
+            if(e.numeric && ((e.min != null) || (e.max != null))) {
+                               if(e.i) {
+                                       var v = parseInt(e.value);
+                                       if(v != e.value) {
+                                               errors += "- The field " +e.r + " must be a ";
+                                               errors += "number with no decimal\n";
+                                               continue;
+                                       }
+                               }
+                               else
+                                       var v = parseFloat(e.value);
+                               if(isNaN(v) ||
+                                       ((e.min != null) && (v < e.min)) ||
+                                       ((e.max != null) && (v > e.max))) {
+
+                                       errors += "- The field " + e.r + " must be a number";
+                                       if(e.min != null)
+                                               errors += " that is greater than " + e.min;
+                                       if(e.max != null && e.min != null)
+                                               errors += " and less than " + e.max;
+                                       else if (e.max != null)
+                                               errors += " that is less than " + e.max;
+                                       errors += ".\n";
+                               }
+                       }
+               }
+               if (e.options && !e.optional)
+               {
+                       if((e.value == null) || (e.value == "") || isblank(e.value)) 
+                       {
+                               empty_fields += "\n             " + e.r;
+                               continue;
+                       }
+               }
+       }
+
+       if(!empty_fields && !errors)
+               return(true);
+
+       msg = "_____________________________________________________\n\n";
+       msg +="The form was not submitted because of the following error(s).\n";
+       msg +="Please correct these error(s) and re-submit.\n";
+       msg +="_____________________________________________________\n\n";
+
+       if(empty_fields) {
+               msg += "- The following required field(s) are empty:"
+                               + empty_fields + "\n";
+               if(errors)
+                       msg += "\n";
+       }
+       msg += errors;
+       alert(msg);
+       return(false);
+}
+var chkDot = true;
+var usEmail = true;
+function validEmail(eAddr) 
+{ 
+   var lenSuffix = (usEmail) ? 4: 3;
+   var goodAddr = false;
+   var ndxAt = ndxDot = 0;
+   ndxAt  = eAddr.indexOf("@");
+   ndxDot = eAddr.indexOf(".");
+   ndxDot2 = eAddr.lastIndexOf(".");
+
+   if ( (ndxDot < 0) || (ndxAt < 0) )
+      return(goodAddr);//alert("Your email address lacks '.' or '@'.\n\nThe format is 'you@dom.suf'");  
+   else if (chkDot  && (ndxDot < ndxAt) )
+        chkDot =!( confirm("You entered a 'dot' before the '@'\n Are you sure that is right?"));
+   else if ( (ndxDot2 - 3) <= ndxAt)
+        return(goodAddr);//alert("You may be missing your domain name.\n\nThe format is 'you@dom.suf'");
+   else if ( eAddr.length < (ndxDot2 + lenSuffix) )
+      usEmail =!( confirm("You have fewer than 3 characters as a domain suffix.\nAre you sure that is right?"));
+   else
+      goodAddr = true;
+
+
+   return (goodAddr);                       
+} 
+
+
diff --git a/userArea/videos.php b/userArea/videos.php
new file mode 100644 (file)
index 0000000..c123186
--- /dev/null
@@ -0,0 +1,36 @@
+<?php
+require_once '../setup.phtml';
+define('VIDEOS_ADMIN_FILE', MEDIA_BASE_URL . 'userArea/videos.php');
+
+require_once './setup.php';
+
+//  application configuration
+$conf = new Config;
+$confRoot=& $conf->parseConfig(
+    BASE . 'Toolkit/Videos/config.ini',
+    'IniFile'
+);
+
+//  get reference to [conf] section of config file
+$appName
+    = $confRoot->getItem('section', 'conf')
+    ->getItem('directive', 'applicationName')
+    ->getContent();
+
+$navigation = new Toolkit_Videos_Navigation(
+    new HTML_Menu(),
+    new HTML_Menu_DirectRenderer()
+);
+
+$navArray = $navigation->getNavStructure($confRoot);
+$navHtml = $navigation->renderPageNav($navArray, 'rows');
+$c = new Toolkit_Videos_Controller();
+$videos = $c->toHtml(
+    Toolkit_Database::getInstance(),
+    $confRoot
+);
+$GLOBALS['styleSheets'][] = MEDIA_BASE_URL . 'userArea/main.css';
+GLM_TOOLBOX::top($appName, '', null, false);
+echo $navHtml;
+echo $videos;
+GLM_TOOLBOX::footer();