Location: PHPKode > projects > Mac's MVC Framework > Application/plugins/CMS/controllers/CMS.php
<?php
  /**
   * This Plugin provides the CMS ( Macs CMS ) for the framework and handles all requests and responses made in the CMS
   *
   * @author Macdonald Terrence Robinson
   * @package Plugin
   *
   */
  require_once dirname(__FILE__).'/../../BasePlugin.php';

  class CMS extends BasePlugin
  {
    /** @var Roles_Model */
    private $rolesModel = NULL;

    /** @var Users_Model */
    private $usersModel = NULL;

    /** @var PageComments_Model */
    private $pageCommentsModel = NULL;

    private static $isCMSModelLoaded = false;

    public function __construct(MainController $controller)
    {      
      parent::__construct($controller);

      if( $this->isAdminLoggedIn() )
        $this->loadModels();
    }

    /** @return Roles_Model */
    public function getRolesModel()
    {
      $this->rolesModel;
    }

    /** @return Users_Model */
    public function getUsersModel()
    {
      $this->usersModel;
    }

    /** @return PageComments_Model */
    public function getPageCommentsModel()
    {
      $this->pageCommentsModel;
    }

    public function allowOnlyAdmins()
    {
      if( !$this->isAdminLoggedIn() )
          $this->returnContent('You are not Logged In');
    }

    public function index()
    {
      $adminFunction = URI::getParam(0);
      if(!Utility::isFunctionInObject($this, $adminFunction))
        $this->redirectToHome();
      else
        $this->$adminFunction();
    }

    private function loadModels()
    {
      if( !self::$isCMSModelLoaded )
      {
        require_once $this->getCurrentPluginPath().'models/CMS_Model.php';
        self::$isCMSModelLoaded = true;
      }
      
      if( $this->rolesModel == NULL )
        $this->rolesModel = $this->loadModel('Roles_Model');

      if( $this->usersModel == NULL )
        $this->usersModel = $this->loadModel('Users_Model');

      if( $this->pageCommentsModel == NULL )
        $this->pageCommentsModel = $this->loadModel('PageComments_Model');      
    }

    private function isValidLogin($username, $password)
    {
      $this->loadModels();
      
      $loggedIn = false;

      foreach (Config::$editInPlaceAdmins as $key=>$account)
      {
        if(( $account['username'] == $username) && ($account['password'] == $password ) )
        {
          $loggedIn = true;
          Session::set('AdminLoggedIn', $account);
          break;
        }
      }

      $users = $this->usersModel->getAllUsers();

      foreach ($users as $user)
      {
        if(( $user->Username == $username) && ($user->Password == $password ) )
        {
          $loggedIn = true;
          Session::set('AdminLoggedIn', $user);
          break;
        }
      }

      if(!$loggedIn)
        $this->logoutAdmin();

      return $loggedIn;
    }

    private function encrypt( $string )
    {      
      return md5($string);
    }

    public static function isAdminLoggedIn()
    {
      if( Session::isExists('AdminLoggedIn') )
      {        
        $account = Session::getByKey('AdminLoggedIn');

        if( is_object($account) )
          return true;
        
        //return $this->isValidLogin($account->Username, $account->Password );        
      }

      return false;
    }

    public function logoutAdmin()
    {
      Session::remove('AdminLoggedIn');
      Cache::clear();
    }

    public function getAdminLogoutURL()
    {
      return Config::$siteURL.'index.php/'.Router::$controller.'/'.Config::$adminFunction.'/logout';
    }

    public function getAdminLoginURL()
    {
      return Config::$siteURL.'index.php/'.Router::$controller.'/'.Config::$adminFunction.'/login';
    }

    public function getForgotPasswordURL()
    {
      return Config::$siteURL.'index.php/'.Router::$controller.'/'.Config::$adminFunction.'/forgotPassword';
    }

    public function getForgotPasswordProcessURL()
    {
      return Config::$siteURL.'index.php/'.Router::$controller.'/'.Config::$adminFunction.'/forgotPasswordProcess';
    }

    public function getPagePropertiesURL()
    {
      return Config::$siteURL.'index.php/'.Router::$controller.'/'.Config::$adminFunction.'/pageProperties';
    }

    public function getResetPasswordURL($emailAddress, $tempPassword)
    {
      return Config::$siteURL.'index.php/'.Router::$controller.'/'.Config::$adminFunction.'/resetPassword?emailAddress='.$emailAddress.'&tempPassword='.$tempPassword;
    }

    public function generateAdminTools($AdminId, $spacer = '<span class="spacer">|</span>')
    {      
      $list1Html = '';
      if( $this->isAdminLoggedIn() )
        $list1Html = SiteMap::generate( SiteMap::getNode('root', Config::$adminFunction) , -1);

      $list2 = array();
      $attributes = array();

      if($this->isAdminLoggedIn())
      {
        $list2[] = 'Logout';
        $attributes['href'] = $this->getAdminLogoutURL();
      }
      else
      {
        $list2[] = 'Login';
        $attributes['href'] = $this->getAdminLoginURL();
      }

      foreach ($list2 as $key=>$value)
        Utility::prepareArrayItem($list2, $key, $value, $attributes);

      $list2Html = HTML::generateList($list2);

      $allLists[] = $list1Html;
      $allLists[] = $list2Html;

      $finalList = HTML::mergeLists($allLists, 'ul', $AdminId, $spacer);      
      return $finalList;
    }

    public function viewLogin()
    {      
      $contentVars['action'] = $this->getAdminLoginURL();
      $contentVars['forgotPassword'] = $this->getForgotPasswordURL();

      $this->templateVars['mainContent'] = $this->loadContent('login', $contentVars);
      
      $this->returnContent($this->templateVars['mainContent']);
    }

    public function forgotPassword()
    {
      $this->loadModels();
      $contentVars['forgotPasswordAction'] = $this->getForgotPasswordProcessURL();

      $forgotPasswordForm = $this->loadContent('forgotPassword', $contentVars);
      $this->returnContent($forgotPasswordForm);
    }

    public function forgotPasswordProcess()
    {
      $this->loadModels();
      $emailAddress = Post::getByKey('emailAddress');

      $user = $this->usersModel->getUserByEmailAddress($emailAddress);

      if(!is_object($user))
        $this->returnContent("Cannot find user with Email address: $emailAddress");

      $password = Utility::generatePassword();
      $user->TempPassword = $this->encrypt($password);
      $this->usersModel->updateUserObject($user);
      
      $contentVars['resetLink'] =  $this->getResetPasswordURL($emailAddress, $user->TempPassword);
      $forgotPasswordEmail = $this->loadContent('forgotPasswordEmail', $contentVars);

      require_once Config::$siteDir.'libs/standalone/Mailer.php';

      $fromAddress = Config::$siteEmailAddress;
      $fromName = Config::$siteEmailName;

      $mailer =  new Mailer($fromAddress, $fromName);

      $toAddresses = array();
      $toAddresses['Name'] = $emailAddress;

      $mailer->setAddresses( $toAddresses );

      $mailer->setSubject( 'Password Reset Request for site: '.Config::$siteURL );
      $mailer->setMessage( $forgotPasswordEmail );

      $mailer->send();
      $mailer->displayErrorMessages();      
      
      $this->returnContent("A Password reset link was sent to: $emailAddress");
    }

    public function resetPassword()
    {
      $this->loadModels();

      $tempPassword = Get::getByKey('tempPassword');
      $emailAddress = Get::getByKey('emailAddress');

      if(($tempPassword == '') || ($emailAddress == ''))
        $this->redirectToHome();

      $user = $this->usersModel->getUserByTempPassword($emailAddress, $tempPassword);

      if(!is_object($user))
        $this->returnContent('Cannot find user or the link has expired');            

      if( Post::isExists('newPassword') )
      {
        $user->Password = $this->encrypt(Post::getByKey('newPassword'));
        $user->TempPassword = '';
        $this->usersModel->updateUserObject($user);
        $this->returnContent('Your password has been set. You can now login using your new password, <a href="'.$this->getAdminLoginURL().'">Click Here</a> to Login');
      }
      else
        $this->returnContent($this->loadContent('resetPasswordForm', array()));
    }

    public function pageProperties()
    {
      $contentVars['action'] = $this->getPagePropertiesURL();

      $this->templateVars['mainContent'] = $this->loadContent('pageProperties', $contentVars);
      $this->display($this->templateVars);
    }

    public function login()
    {      
      if($this->isValidLogin(Post::getByKey('username'), $this->encrypt(Post::getByKey('password')) ) || ( $this->isAdminLoggedIn() ))
        $this->redirectToHome();
      else
      {
        if( !$this->isAjaxRequest() )
          $this->viewLogin();
        else
          $this->returnContent('Invalid Username or Password');
      }
    }

    public function logout()
    {
      $this->logoutAdmin();
      $this->redirectToHome();
    }

    public function getContent()
    {
      $this->allowOnlyAdmins();

      $contentType = Get::getByKey('contentType');
      $contentName = Get::getByKey('contentName');

      $controller = Get::getByKey('controller');
      $function = Get::getByKey('function');
      $uniquePerPage = Get::getByKey('uniquePerPage');

      if($uniquePerPage == 'true')
        $uniquePerPage = true;
      else
        $uniquePerPage = false;
      
      $content = '';
      switch(strtolower($contentType))
      {
        case 'maincontents':
          $content = $this->loadMainContent($contentName, array(),false);
        break;

        case 'contentbuckets':
          $content = $this->loadContentBucket($contentName, array(), false, $uniquePerPage, $controller, $function);
        break;
      }
      $this->returnContent($content);
    }

    public function getChildNodesNav( $node )
    {
      return SiteMap::generate( $node, 0, '', true, '  - <strong><a class="deleteChildPage" href="javascript:void(false)" controller="{controller}" function="{function}">Delete</a> | <a class="viewChildPage" href="{siteURL}{controller}/{function}">View</a></strong>');
    }

    public function addNewLanguage()
    {
      $this->allowOnlyAdmins();
      $language = strtolower(Get::getByKey('newLanguage'));

      if( !in_array($language, Config::$siteLanguages ) )
      {
        Config::$siteLanguages[] = $language;
        Config::saveCustomConfig();

        $this->returnContent('New language: '.$language.' was added successfully');
      }
      else
        $this->returnContent('Language with the name: '.$language.' already exists');
    }

    public function renameLanguage()
    {
      $this->allowOnlyAdmins();
      $oldName = strtolower(Get::getByKey('oldName'));
      $newName = strtolower(Get::getByKey('newName'));

      if( in_array($oldName, Config::$siteLanguages ) )
      {
        if( FileSystem::dirExists( Config::$editInPlaceDir.$oldName ) )
        {
          if(!FileSystem::renameDir(Config::$editInPlaceDir.$oldName, Config::$editInPlaceDir.$newName))
            $this->returnContent('There was an error while trying to renaming the directory: '.Config::$editInPlaceDir.$oldName.' to '+Config::$editInPlaceDir.$newName);
        }

        foreach( Config::$siteLanguages as $key=>$value )
        {
          if($value == $oldName)
            Config::$siteLanguages[$key] = $newName;
        }

        Config::saveCustomConfig();

        $this->returnContent('Language: '.$oldName.' was successfully renamed to :'+$newName);
      }
      else
        $this->returnContent('Language with the name: '.$oldName.' does not exist');
    }


    public function deleteLanguage()
    {
      $this->allowOnlyAdmins();
      $language = strtolower(Get::getByKey('language'));

      if( in_array($language, Config::$siteLanguages ) )
      {
        foreach( Config::$siteLanguages as $key=>$value )
        {
          if($value == $language)
          {
            unset(Config::$siteLanguages[$key]);
            
            if($language == Config::$siteLanguage)
            {
              Session::remove('lang');
              Config::$siteLanguage = Config::$siteLanguages[0];
            }
          }
        }

        Config::saveCustomConfig();

        $this->returnContent('Language: '.$language.' was successfully deleted');
      }
      else
        $this->returnContent('Language with the name: '.$language.' does not exist');
    }

    public function getPageProperties()
    {      
      $this->allowOnlyAdmins();      

      $controller = Get::getByKey('controller');
      $function = Get::getByKey('function');

      $node = SiteMap::getNode($controller, $function);

      if($node == NULL)
        $this->returnContent('This page does not exist in the SiteMap XML file');

      $contentVars = array();

      $contentVars['controller'] = $controller;
      $contentVars['function'] = $function;
      $contentVars['pageTitle'] = (string)SiteMap::getAttr($node, 'pageTitle');
      $contentVars['title'] = (string)SiteMap::getAttr($node, 'title');
      $contentVars['sefTitle'] = (string)SiteMap::getAttr($node, 'sefTitle');
      $contentVars['metaDesc'] = (string)SiteMap::getAttr($node, 'metaDesc');
      $contentVars['metaKeys'] = (string)SiteMap::getAttr($node, 'metaKeys');
      $contentVars['bannerURL'] = (string)SiteMap::getAttr($node, 'bannerURL');
      $contentVars['allowVisitorComments'] = (string)SiteMap::getAttr($node, 'allowVisitorComments');
      $contentVars['showVisitorComments'] = (string)SiteMap::getAttr($node, 'showVisitorComments');
      $contentVars['enableCommentModeration'] = (string)SiteMap::getAttr($node, 'enableCommentModeration');
      $contentVars['commentsModeratorEmailAddress'] = (string)SiteMap::getAttr($node, 'commentsModeratorEmailAddress');

      if($contentVars['commentsModeratorEmailAddress'] == '')
        $contentVars['commentsModeratorEmailAddress'] = Config::$customConfigs['commentsModeratorEmailAddress'];

      if( $contentVars['showVisitorComments'] == 'on' )
        $contentVars['showVisitorComments'] = 'checked="checked"';

      if( $contentVars['allowVisitorComments'] == 'on' )
        $contentVars['allowVisitorComments'] = 'checked="checked"';

      if( $contentVars['enableCommentModeration'] == 'on' )
        $contentVars['enableCommentModeration'] = 'checked="checked"';

      $pageTemplate = ((string)SiteMap::getAttr($node, 'pageTemplate') === '') ? 'Default' : (string)SiteMap::getAttr($node, 'pageTemplate');

      $templates = FileSystem::scanDir( Config::$templatesDir );
      $templates = array_merge( array('Default') , $templates);

      $contentVars['selectPageTemplate'] = HTML::generateSelect( 'pageTemplate', $templates , $pageTemplate );

      $contentVars['childNodes'] = $this->getChildNodesNav($node);
      $returnParams = $this->loadContent('pageProperties', $contentVars);
      
      $this->returnContent($returnParams);
    }

    public function getUsersList()
    {
      $this->allowOnlyAdmins();

      require_once 'libs/standalone/Pagination.php';
      $pagination = new Pagination('usersList', 5);

      $users = $this->usersModel->getAllUsers();
      $pagination->setResults($users);

      $pageIndex = Get::isExists('pageIndex') ? Get::getByKey('pageIndex') : 0;

      $contentVars = array();
      $contentVars['pagination'] = $pagination;
      $contentVars['pageIndex'] = $pageIndex;
      $contentVars['rolesModel'] = $this->rolesModel;

      $content = $this->loadContent('usersList', $contentVars);

      if( Get::isExists('pageIndex') )
        echo $content;
      else
        return $content;
    }

    public function getRolesList()
    {
      $this->allowOnlyAdmins();

      require_once 'libs/standalone/Pagination.php';
      $pagination = new Pagination('rolesList', 5);
      
      $roles = $this->rolesModel->getAllRoles();
      $pagination->setResults($roles);

      $pageIndex = Get::isExists('pageIndex') ? Get::getByKey('pageIndex') : 0;

      $contentVars = array();
      $contentVars['pagination'] = $pagination;
      $contentVars['pageIndex'] = $pageIndex;

      $content = $this->loadContent('rolesList', $contentVars);

      if( Get::isExists('pageIndex') )
        echo $content;
      else
        return $content;      
    }

    private function getSelectedRole()
    {
      return Session::getByKey('selectedRole');
    }

    private function setSelectedRole($user)
    {
      return Session::set('selectedRole', $user);
    }

    private function removeSelectedRole()
    {
      return Session::remove('selectedRole');
    }


    private function getSelectedUser()
    {
      return Session::getByKey('selectedUser');
    }

    private function setSelectedUser($user)
    {
      return Session::set('selectedUser', $user);
    }

    private function removeSelectedUser()
    {
      return Session::remove('selectedUser');
    }

    public function addNewUser()
    {
       $this->allowOnlyAdmins();
       $this->removeSelectedUser();
       
       $contentVars = array();
       $contentVars['rolesModel'] = $this->rolesModel;
       $contentVars['formTitle'] = 'Add New User';

       $this->returnContent( $this->loadContent('editUser', $contentVars) );
    }

    public function addNewRole()
    {
       $this->allowOnlyAdmins();
       $this->removeSelectedRole();

       $contentVars = array();
       $contentVars['rolesModel'] = $this->rolesModel;
       $contentVars['formTitle'] = 'Add New Role';

       $this->returnContent( $this->loadContent('editRole', $contentVars) );
    }

    public function editRole()
    {
      $this->allowOnlyAdmins();

      if(!Get::isExists('roleId') )
        return;

      $roleId = Get::getByKey('roleId');

      $contentVars = array();
      $contentVars['selectedRole'] = $this->rolesModel->getRoleByID($roleId);

      if( is_object($contentVars['selectedRole']) )
        $this->setSelectedRole($contentVars['selectedRole']);
      else
        return;

      $contentVars['rolesModel'] = $this->rolesModel;
      $contentVars['formTitle'] = 'Editing User: '.$contentVars['selectedRole']->Name;
      $this->returnContent( $this->loadContent('editRole', $contentVars) );
    }

    public function editUser()
    {
      $this->allowOnlyAdmins();

      if(!Get::isExists('userId') )
        return;

      $userId = Get::getByKey('userId');

      $contentVars = array();
      $contentVars['selectedUser'] = $this->usersModel->getUserByID($userId);

      if( is_object($contentVars['selectedUser']) )
        $this->setSelectedUser($contentVars['selectedUser']);
      else
        return;

      $contentVars['rolesModel'] = $this->rolesModel;
      $contentVars['formTitle'] = 'Editing User: '.$contentVars['selectedUser']->Username;
      $this->returnContent( $this->loadContent('editUser', $contentVars) );
    }

    public function deleteUser()
    {
      $this->allowOnlyAdmins();

      if(!Get::isExists('userId') )
        return;

      $userId = Get::getByKey('userId');

      $found = $this->usersModel->getUserByID($userId);
      $allAdmins = $this->usersModel->getUsersByRoleID('1');

      if( count($found) == 0 )
        $this->returnContent("The user with ID: $userId ( $found->Username ) does not exist");
      else if( (count($allAdmins) == 1 ) && ($found->Username == $allAdmins[0]->Username  ))
        $this->returnContent("You cannot delete the only administrator.");

      $this->usersModel->deleteUserByID($userId);

      $this->returnContent("User: $found->Username was deleted successfully. <a class='getEditSiteProperties' href='javascript:void(0)'>Click Here</a> to update your view");
    }

    public function deleteRole()
    {
      $this->allowOnlyAdmins();

      if(!Get::isExists('roleId') )
        return;

      $roleId = Get::getByKey('roleId');

      if(intval($roleId) == 1)
        $this->returnContent("The role with ID: $roleId ( Admin ) cannot be deleted");

      $found = $this->rolesModel->getRoleByID($roleId);

      if( count($found) == 0 )
        $this->returnContent("The role with ID: $roleId does not exist");
      else if( count($this->usersModel->getUsersByRoleID($roleId) ) > 0 )
        $this->returnContent("The role with ID: $roleId ( $found->Name ) has users associated with it, please delete the users associated with this role prior to deleting this role.");

      $this->rolesModel->deleteRoleByID($roleId);

      $this->returnContent("Role: $found->Name was deleted successfully. <a class='getEditSiteProperties' href='javascript:void(0)'>Click Here</a> to update your view");
    }

    public function saveRole()
    {
      $this->allowOnlyAdmins();

      $selectedRole = $this->getSelectedRole();

      $name = Post::getByKey('name');
      $description = Post::getByKey('description');

      if(($name == '') || ($description == ''))
        $this->returnContent('Some of the required fields are empty.');

      if( is_object($selectedRole) )
        $this->returnContent($this->updateRole($selectedRole, $name, $description));
      else
        $this->returnContent($this->saveNewRole($name, $description));
    }

    private function saveNewRole($name, $description)
    {
      $found = $this->rolesModel->getRoleByName($name);

      if( count($found) > 0 )
        return 'A Role with the same name already exists. Please choose a different username and try again.';

      $this->rolesModel->insertRole($name, $description);

      return "Role: $name was added successfully. <a class='getEditSiteProperties' href='javascript:void(0)'>Click Here</a> to update your view";
    }

    private function updateRole($selectedRole, $name, $description)
    {
      $this->rolesModel->updateRole($selectedRole, $name, $description);
      
      return "Role: $name was updated successfully. <a class='getEditSiteProperties' href='javascript:void(0)'>Click Here</a> to update your view";
    }

    public function saveUser()
    {
      $this->allowOnlyAdmins();

      $selectedUser = $this->getSelectedUser();

      $username = Post::getByKey('username');
      $password = Post::getByKey('password');
      $confirmPassword = Post::getByKey('confirmPassword');
      $emailAddress = Post::getByKey('emailAddress');
      $roleId = Post::getByKey('roleId');

      if( is_object($selectedUser) )
      {
        if(($username == '') || ($emailAddress == '') || ($roleId == '') )
          $this->returnContent('Some of the required fields are empty.');
      }
      else
      {
        if(($username == '') || ($password == '') || ($emailAddress == '') || ($confirmPassword == '') || ($roleId == '') )
          $this->returnContent('Some of the required fields are empty.');
      }

      $password = $this->encrypt(Post::getByKey('password'));
      $confirmPassword = $this->encrypt(Post::getByKey('confirmPassword'));

      if( $password != $confirmPassword )
        $this->returnContent('The password and the confirm password fields do not match');

      if( !is_object($this->rolesModel->getRoleByID($roleId)) )
        $this->returnContent('The Role that was entered does not exist');

      if( is_object($selectedUser) )
      {
        if(Post::getByKey('password') == '')
          $password = $selectedUser->Password;
        
        $this->returnContent($this->updateUser($selectedUser, $username, $password, $emailAddress, $roleId));
      }
      else
        $this->returnContent($this->saveNewUser($username, $password, $emailAddress, $roleId));
    }

    private function saveNewUser( $username, $password, $emailAddress, $roleId)
    {
      $found =  $this->usersModel->getUserByUsername($username);

      if( count($found) > 0 )
        return 'A User with the same name already exists. Please choose a different username and try again.';

      $this->usersModel->insertUser($username, $password, $emailAddress, $roleId);
      return "User: $username was added successfully. <a class='getEditSiteProperties' href='javascript:void(0)'>Click Here</a> to update your view";
    }

    private function updateUser($selectedUser, $username, $password, $emailAddress, $roleId)
    {
      $this->usersModel->updateUser($selectedUser, $username, $password, $emailAddress, $roleId);
      return "User: $username was updated successfully. <a class='getEditSiteProperties' href='javascript:void(0)'>Click Here</a> to update your view";
    }


    public function getSiteProperties()
    {
      $this->allowOnlyAdmins();

      $contentVars = array();

      $contentVars['siteName'] = htmlentities(Config::$siteName, ENT_QUOTES);
      $contentVars['siteLanguageDropDown'] = HTML::generateSelect( 'siteLanguage', Config::$siteLanguages, Config::$defaultSiteLanguage );
      $contentVars['selectDefaultTemplate'] = HTML::generateSelect( 'defaultTemplate', FileSystem::scanDir( Config::$templatesDir ), Config::$defaultTemplate );
      $contentVars['siteLanguages'] =  HTML::generateSelect( 'siteLanguages',  Config::$siteLanguages, Config::$defaultSiteLanguage, true );

      $contentVars['usersList'] = $this->getUsersList();
      $contentVars['rolesList'] = $this->getRolesList();

      $returnParams = $this->loadContent('siteProperties', $contentVars);

      $this->returnContent($returnParams);
    }

    public function saveContent()
    {
      $this->allowOnlyAdmins();

      $contentType = Get::getByKey('contentType');
      $contentName = Get::getByKey('contentName');

      $controller = Get::getByKey('controller');
      $function = Get::getByKey('function');
      $uniquePerPage = Get::getByKey('uniquePerPage');

      if($uniquePerPage == 'true')
        $uniquePerPage = true;
      else
        $uniquePerPage = false;

      $newContent = stripslashes(Post::getByKey('newContent'));

      $filePath = $this->getContentPath($contentType, $contentName, $controller, $function, $uniquePerPage);

      if(!FileSystem::dirExists(dirname($filePath)))
        FileSystem::makeDir(dirname($filePath), true, 0777);

      FileSystem::saveData($filePath, $newContent, true, 0777);

      $this->clearCache();      
      $this->returnContent('Your changes have been made. Please <a href="javascript:void(0)" onclick="window.location.reload();">Click Here</a> to refresh the page and see your changes.');
    }

    public function deleteChildPage()
    {
      $this->allowOnlyAdmins();

      $controller = Get::getByKey( 'controller');
      $function = Get::getByKey('function');

      $node = SiteMap::getNode($controller, $function);
      $parentNode = SiteMap::getParentNode($node);

      if($node == null)
        return false;

      SiteMap::delete($node);
      SiteMap::save();
      $this->clearCache();

      $this->returnContent( $this->getChildNodesNav($parentNode) );
    }

    public function addNewChildPage()
    {
      $this->allowOnlyAdmins();

      $controller = Get::getByKey('controller');
      $function = Get::getByKey('function');
      $newPage = Get::getByKey('newPage');

      $newFunction = stripslashes( strip_tags($newPage) ) ;
      $newFunction = strtolower(str_replace(array('-',' ', '"' ,"'", '\\','/','`', '#'), array('_','_', '', '','','','',''), $newPage));

      $node = SiteMap::getNode($controller, $function);
      $childNode = SiteMap::getNode($controller, $newFunction);

      if($childNode == NULL)
      {
        SiteMap::add($node, $controller, $newFunction, $newPage, $newPage, $newPage, $newPage);
        SiteMap::save();

        $this->clearCache();
      }

      $this->returnContent( $this->getChildNodesNav($node) );
    }

    public function applyNewSortOrder()
    {
      $this->allowOnlyAdmins();

      $controller = Get::getByKey( 'controller');
      $function = Get::getByKey('function');
      $order = Get::getByKey('order');

      $node = SiteMap::getNode($controller, $function);
      $orderArray = explode('|', $order);

      $oldNode = clone $node;

      SiteMap::deleteAllChilds($node);

      foreach ($orderArray as $index)
      {
        if( !is_numeric($index) )
          continue;

        $newNode = $oldNode->node[(int)$index];
        XML::addChildNode($node, $newNode);
      }

      SiteMap::save();

      $this->returnContent( $this->getChildNodesNav($node) );
    }

    public function savePageProperties()
    {
      $this->allowOnlyAdmins();

      $controller = Get::getByKey( 'controller');
      $function = Get::getByKey('function');

      if(Post::getByKey('title') == '')
        $this->returnContent('Title is required');
      
      $node = SiteMap::getNode($controller, $function);

      $sefTitle = Post::getByKey('sefTitle');
      
      if( trim($sefTitle) == '' )
      {
        $sefTitle = trim(stripslashes(strip_tags(Post::getByKey('title'))));
        $sefTitle = str_replace(array(' ','\'','"'),array('-', '', ''), $sefTitle);
        $sefTitle = strtolower($sefTitle);
      }

      $allowVisitorComments = (Post::getByKey('allowVisitorComments') == '')? 'off': Post::getByKey('allowVisitorComments') ;
      $showVisitorComments = (Post::getByKey('showVisitorComments') == '')? 'off': Post::getByKey('showVisitorComments') ;
      $enableCommentModeration = (Post::getByKey('enableCommentModeration') == '')? 'off': Post::getByKey('enableCommentModeration') ;

      SiteMap::setAttr($node, 'pageTitle', Post::getByKey('pageTitle'));
      SiteMap::setAttr($node, 'title', Post::getByKey('title'));
      SiteMap::setCommonAttr($node, 'sefTitle', $sefTitle);
      SiteMap::setAttr($node, 'metaDesc', Post::getByKey('metaDesc'));
      SiteMap::setAttr($node, 'metaKeys', Post::getByKey('metaKeys'));
      SiteMap::setAttr($node, 'bannerURL', Post::getByKey('bannerURL'));
      SiteMap::setAttr($node, 'pageTemplate', Post::getByKey('pageTemplate'));
      SiteMap::setAttr($node, 'allowVisitorComments', $allowVisitorComments);
      SiteMap::setAttr($node, 'showVisitorComments', $showVisitorComments);
      SiteMap::setAttr($node, 'enableCommentModeration', $enableCommentModeration);

      if( Post::getByKey('commentsModeratorEmailAddress') != Config::$customConfigs['commentsModeratorEmailAddress'] )
        SiteMap::setAttr($node, 'commentsModeratorEmailAddress', Post::getByKey('commentsModeratorEmailAddress'));

      SiteMap::save();
      $this->clearCache();

      $this->returnContent('Your changes have been made. Please <a href="javascript:void(0)" onclick="window.location.reload();">Click Here</a> to refresh the page and see your changes.');
    }

    public function saveSiteProperties()
    {
      $this->allowOnlyAdmins();

      $postConfig = Post::getAll();

      foreach($postConfig as $key=>$value)
      {
        if( isset(Config::$$key ) && ( (is_string($value) && trim($value) !='') || $key=='customConfigs' ) && (!isset(MainConfig::$$key) ))
          Config::$$key = $value;
      }
      
      Config::saveCustomConfig();
      $this->clearCache();      

      $this->returnContent('Your changes have been made. Please <a href="javascript:void(0)" onclick="window.location.reload();">Click Here</a> to refresh the page and see your changes.');
    }

    public function deleteComment()
    {
      $this->allowOnlyAdmins();
      $commentId = Get::getByKey('commentId');
      
      $this->pageCommentsModel->deleteCommentByID($commentId);

      $this->returnContent('Comment was deleted successfully. <a href="javascript:void(0)" onclick="window.location.reload();">Click Here</a> to refresh the page and see your changes.');
    }

    public function allowComment()
    {
      $this->allowOnlyAdmins();

      $commentId = Get::getByKey('commentId');

      $this->pageCommentsModel->allowCommentByID($commentId);
      $this->returnContent('Comment will now be posted on the site.');
    }
    
    public function addComment()
    {
      $this->loadModels();
      
      $controller = Post::getByKey('controller');
      $function = Post::getByKey('function');

      $name = trim(Post::getByKey('name'));
      $subject = trim(Post::getByKey('subject'));
      $url = trim(Post::getByKey('url'));
      $emailAddress = trim(Post::getByKey('emailAddress'));
      $comment = trim(Post::getByKey('comment'));
      $captchaCode = trim(Post::getByKey('captcha_code'));

      if(!strstr($url, '://'))
        $url = 'http://'.$url;

      require_once Config::$siteDir.'libs/standalone/Captcha.php';
      $captcha = new Captcha();

      if(($name == '') || ($subject == '') || ($emailAddress == '') || (!$captcha->check($captchaCode)) )
        $this->returnContent('There was an error posting your comment. Please make sure that you have filled in all the required fields correctly. Inorder to retry <a href="javascript:void(0);" onclick="document.getElementById(\'captcha\').src = \''.Config::$siteURL.'libs/standalone/securimage/securimage_show.php?\' + Math.random(); $(\'#postMessage\').html(\'\'); return false">Click Here</a><br /><br />');
      else
      {
        $node = SiteMap::getNode($controller, $function);
        $enableCommentModeration = (SiteMap::getAttr($node, 'enableCommentModeration') == 'on')? true: false;

        $showOnSite = false;
        $isAdminComment = false;

        if((!$enableCommentModeration) || ($this->isAdminLoggedIn()))
          $showOnSite = true;

        if($this->isAdminLoggedIn())
          $isAdminComment = true;

        $return = $this->pageCommentsModel->insertPageComment($controller, $function, Config::$siteLanguage ,$name, $subject, $url, $emailAddress, $comment, $showOnSite, $isAdminComment);

        if(!$return)
          $this->returnContent('Error Inserting comment.<br /><br />');

        $pageURL = SiteMap::getURL($node);

        $contentVars = array();
        $contentVars['name'] = $name;
        $contentVars['subject'] = $subject;
        $contentVars['url'] = $url;
        $contentVars['emailAddress'] = $emailAddress;
        $contentVars['comment'] = $comment;
        $contentVars['pageURL'] = $pageURL;

        $message =  $this->loadContent('commentsNotificationEmail', $contentVars) ;
        
        require_once Config::$siteDir.'libs/standalone/Mailer.php';

        $fromAddress = Config::$siteEmailAddress;
        $fromName = Config::$siteEmailName;

        $mailer =  new Mailer($fromAddress, $fromName);

        $toEmail = SiteMap::getAttr($node, 'commentsModeratorEmailAddress');
        if($toEmail == '')
          $toEmail = Config::$customConfigs['commentsModeratorEmailAddress'];
        
        $toAddresses = array();
        $toAddresses[] = $toEmail;

        $mailer->setAddresses( $toAddresses );

        $mailer->setSubject( 'A comment was posted at: '.$pageURL );
        $mailer->setMessage( $message );

        $mailer->send();

        if(($enableCommentModeration) && (!$isAdminComment))
          $this->returnContent('The moderation feature has been turned on. Your comment will be viewed by an administrator before being posted on the site.<br /><br />');
        else
          $this->returnContent('Your comment was added successfully. <a href="javascript:void(0);" onclick="window.location.reload()">Click Here</a> to reload this page<br /><br />');
      }
    }

    public function _getCommentsForm($controller, $function)
    {
      if(($controller == '') && ( Get::isExists('controller') ))
        $controller = Get::getByKey('controller');

      if(($function == '') && ( Get::isExists('function') ))
        $function = Get::getByKey('function');

      if(( $controller == '') || ( $function == '' ))
        return '';

      $node = SiteMap::getNode($controller, $function);

      $allowVisitorComments = (SiteMap::getAttr($node, 'allowVisitorComments') == 'on')? true: false;

      if(!$allowVisitorComments)
        return;

      $commentsVars = array();
      $commentsVars['captchaGenerator'] = Config::$siteURL.'libs/standalone/securimage/securimage_show.php';
      
      return $this->loadContent('commentsForm', $commentsVars);
    }

    public function _getComments($controller, $function)
    {      
      $this->loadModels();      
      
      if(($controller == '') && ( Get::isExists('controller') ))
        $controller = Get::getByKey('controller');

      if(($function == '') && ( Get::isExists('function') ))
        $function = Get::getByKey('function');

      if(( $controller == '') || ( $function == '' ))
        return '';
      
      $node = SiteMap::getNode($controller, $function);
      
      $showVisitorComments = (SiteMap::getAttr($node, 'showVisitorComments') == 'on')? true: false;
      $enableCommentModeration = (SiteMap::getAttr($node, 'enableCommentModeration') == 'on')? true: false;

      if(!$showVisitorComments)
        return '';

      $comments = NULL;
      
      if((!$this->isAdminLoggedIn()) && ($enableCommentModeration))
        $comments = $this->pageCommentsModel->getModeratedPageComments($controller, $function, Config::$siteLanguage);
      else
        $comments = $this->pageCommentsModel->getPageComments($controller, $function, Config::$siteLanguage);      
      
      $commentsVars['comments'] = $comments;
      $commentsVars['isAdminLoggedIn'] = $this->isAdminLoggedIn();
      $commentsVars['currentController'] = $controller;
      $commentsVars['currentFunction'] = $function;

      $commentsVars['showVisitorComments'] = $showVisitorComments;
      $commentsVars['enableCommentModeration'] = $enableCommentModeration;      
      
      return $this->loadContent('comments', $commentsVars);
    }

    public function getCommentsForm()
    {
      $controller = Get::getByKey('controller');
      $function = Get::getByKey('function');

      if(!$this->isAjaxRequest())
        $this->redirectTo( $controller, $function, URI::getQueryString() );

      $this->returnContent( $this->_getCommentsForm($controller, $function) );
    }

    public function getComments()
    {
      $controller = Get::getByKey('controller');
      $function = Get::getByKey('function');

      if(!$this->isAjaxRequest())
        $this->redirectTo( $controller, $function, URI::getQueryString() );

      $onlyModerated = true;

      if( $this->isAdminLoggedIn())
        $onlyModerated = false;

      $this->returnContent( $this->_getComments($controller, $function) );
    }

    public function getContentPath($contentType, $contentName, $controller='', $function='', $uniquePerPage=true)
    {
      switch($contentType)
      {
        case 'contentBuckets':
          if($uniquePerPage)
            $contentName = $function.'-'.$contentName;
        break;
      }
      $path = $this->getEditInPlacePath($contentType, $contentName);

      return $path;
    }

    public function clearCache()
    {
      Cache::clear();
    }

  }

?>
Return current item: Mac's MVC Framework