API Docs for: WebTemplate API v2.0
Show:

File: /data/www/webtemplate/wtv2/codedoc/wtPage.php

<?php

/**
 *  WebTemplate Core
 *
 *  @version 2.0
 *  @module WebTemplate Core
 */


$GLOBALS["WTPRERENDERHANDLERS"] = Array();


/**
 *  The class representing wtType Nodes
 *
 *  @class WTType
 *  @extends WTNode
 */
class WTPage extends WTNode 
{
  var $m_template = "";

  static function registerPreRenderHandler($function)
  {
    $GLOBALS["WTPRERENDERHANDLERS"][] = $function;
  }


  /**
   *  Get the visible text from a HTML document<br/> 
   *  This is used for generating search text
   *
   *  @method getVisibleTextFromHtml
   *  @static
   *  @param {String} text the HTML to get the text from
   *  @return {String} the text from the HTML
   */

  public static function getVisibleTextFromHtml( $text )
  {
    $text = preg_replace(
        array(
          // Remove invisible content
            '@<head[^>]*?>.*?</head>@siu',
            '@<style[^>]*?>.*?</style>@siu',
            '@<script[^>]*?.*?</script>@siu',
            '@<object[^>]*?.*?</object>@siu',
            '@<embed[^>]*?.*?</embed>@siu',
            '@<applet[^>]*?.*?</applet>@siu',
            '@<noframes[^>]*?.*?</noframes>@siu',
            '@<noscript[^>]*?.*?</noscript>@siu',
            '@<noembed[^>]*?.*?</noembed>@siu',
          // Add line breaks before and after blocks
            '@</?((address)|(blockquote)|(center)|(del))@iu',
            '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',
            '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
            '@</?((table)|(th)|(td)|(caption))@iu',
            '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
            '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
            '@</?((frameset)|(frame)|(iframe))@iu',
        ),
        array(
            ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
            "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0",
            "\n\$0", "\n\$0",
        ),
        $text );
    return strip_tags( $text );
  }


  function getFormAttributeHTML($attributeInfo, $values)
  {
    if($attributeInfo["Attribute Name"] == "Template") {
      $html = parent::getFormAttributeHTML($attributeInfo, $values);
      $html = str_replace('onchange="', 'onchange="setTemplate();', $html);
      return $html;
    }
    return parent::getFormAttributeHTML($attributeInfo, $values);
  }
  public static function create($parentGuid, $typeName, $attributes) 
  {
    if(!array_key_exists("URI", $attributes)) {
      $parent = $GLOBALS["WT"]->getNode($parentGuid); 
      $base = "";
      if($parent->m_typeName == "Page") {
        $base = $parent->getAttribute("URI") . "/";
      }
      $uri = strtolower($attributes["Menu Text"]);
      $uri = preg_replace('/[^a-z0-9]+/','-',$uri);
      $found = true;
      $count = 0;
      while($found) {
        $found = false;
        $sql = "SELECT
                  COUNT(*) 
                FROM
                  Page, wtNode
                WHERE
                  Page.__guid = wtNode.__guid
                  AND wtNode.__deleted = 0
                  AND Page.URI = '" . mysql_escape_string($base . $uri) . "'";
        $query = mysql_query($sql);
        $row = mysql_fetch_row($query);
        $found = $row[0] > 0;
        if($found) {
          $count++;
          $uri = strtolower($attributes["Menu Text"]) . "-$count";
          $uri = preg_replace('/[^a-z0-9]+/','-',$uri);
        }

      }

      $attributes["URI"] = $base . $uri;
    }
    $page = parent::create($parentGuid, $typeName, $attributes);
    //$GLOBALS["WT"]->logEvent("Page Created", "Page '{$attributes["Menu Text"]}' Created", $page->m_guid);
//    $page->logEvent("Page Created", "Page '{$attributes["Menu Text"]}' Created");
    return $page;
  }

/*
  function logEvent($event, $description) {
    $events = $GLOBALS["WT"]->getNode("/Events");
    if($events != NULL) {
      $event = $events->createChild("wtEvent", Array("Event" => $event, "Description" => $description, "Contact ID" => $GLOBALS["WT"]->m_contactGuid, "Node" => $this->m_guid));
      $eventGuid = $event->m_guid;

      if(WTConfig::get("Content Manager/Version Control Enabled") == "Yes") {
        $mode = $GLOBALS["WT"]->getMode();
        $GLOBALS["WT"]->setMode("view");
        $contents = $this->render();
        $GLOBALS["WT"]->setMode($mode);

        $versionDir = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/versions/";
        if(!file_exists($versionDir)) {
          mkdir($versionDir);
        }
        $fd = fopen($versionDir . $eventGuid . ".html", "w");
        fwrite($fd, $contents);
        fclose($fd);


        $nodeData = $this->export($this->m_typeGuid);
        $fd = fopen($versionDir . $eventGuid . ".node", "w");
        fwrite($fd, serialize($nodeData));
        fclose($fd);

        $event->setAttributes(Array("Version ID" => $eventGuid));
      }
    }
  }
*/


  /**
   *  Copy the page
   *
   *  @method copyPage
   *  @param {String} parentPath The page will be created as a child of this path
   *  @param {String} menuText The Menu Text for the new page
   *  @param {boolean} [copySubPages=false] If set to true, subpages will also be copied
   *  @return {Object} The object for the new page node
   */
  function copyPage($parentPath, $menuText, $copySubPages = false) {
    $pageAttributes = $this->getAttributes();
    $parentNode = $GLOBALS["WT"]->getNode($parentPath);

    $pageType = $GLOBALS["WT"]->getNode("/Config/Node Types/Page");
    $pageTypeGuid = 0;
    if($pageType) {
      $pageTypeGuid = $pageType->m_guid;
    }

    if($copysubpages == "yes") {
      $pageTypeGuid = -1;
    }
    
    if($parentNode) {
      $pageAttributes["Title"] = $menuText;
      $pageAttributes["Menu Text"] = $menuText;
      unset($pageAttributes["URI"]);

      $newPage = $parentNode->createChild("Page", $pageAttributes);
      $GLOBALS["WT"]->copyNodeChildren($this->m_guid, $newPage->m_guid, $pageTypeGuid);

      return $newPage;
    }

    return NULL;
  }
  
  function save() {
  }

  /**
   *  Restore a page from a previous version
   *
   *  @method restore
   *  @param {int} eventID The id of the event representing the version
   */

  function restore($eventID) {
//    $event = $GLOBALS["WT"]->getNode($eventID);
    $versionID = 0;
    $sql = "SELECT
              `Version ID`
            FROM
              wtEvent
            WHERE
              __luid = $eventID";

    $query = mysql_query($sql);
    if($row = mysql_fetch_row($query)) {
      $versionID = $row[0];
    }

    if($versionID) {
//      $versionID = $event->getAttribute("Version ID");
      $nodeFile = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/versions/" . $versionID . ".node";
      if(file_exists($nodeFile)) {
        $fp = fopen($nodeFile, "r");
        $nodeData = fread($fp, filesize($nodeFile));
        fclose($fp);
        $node = unserialize($nodeData);

        $this->restoreNode($node, $this->m_typeGuid);
      }
    }
  }

  /**
   *  Set the uri for the page using the Menu Text
   *
   *  @method setURI
   *  @param {String} [base=""] A value to attach to the base of the URI
   *  @param {String} [uriAttribute="Menu Text"] The attribute of the page to use to generate the URI
   */

  function setURI($base = "", $uriAttribute = "Menu Text")
  {
    if($this->getAttribute("Use SEO Defaults") == "No") {
      return;
    }


    $parent = $GLOBALS["WT"]->getNode($this->m_parentGuid);
    if($parent->m_typeName == "Page") {
      $base = $parent->getAttribute("URI");
    }

    if($base != "") {
      $base .= "/";
    }
   
     
    $uri = strtolower($this->getAttribute($uriAttribute, true));


    $uri = preg_replace('/[^a-z0-9]+/','-',$uri);
    $found = true;
    $count = 0;
    while($found) {
      $found = false;
      $sql = "SELECT
                COUNT(*) 
              FROM
                Page, wtNode
              WHERE
                Page.__guid = wtNode.__guid
                AND wtNode.__deleted = 0
                AND Page.URI = '" . mysql_escape_string($base . $uri) . "'
                AND Page.__guid <> " . $this->m_guid;
      $query = mysql_query($sql);
      $row = mysql_fetch_row($query);
      $found = $row[0] > 0;
      if($found) {
        $count++;
        $uri = strtolower($this->getAttribute($uriAttribute)) . "-$count";
        $uri = preg_replace('/[^a-z0-9]+/','-',$uri);
      }       
    }

    //$this->setAttributes(Array("URI" => $base . $uri));

    $sql = "UPDATE
              Page
            SET
              URI = '" . mysql_escape_string($base . $uri) . "'
            WHERE
              __latest = 1
              AND __guid = " . $this->m_guid;
    mysql_query($sql);
    print mysql_error();
    $this->m_dirty = true;
  }

  function setKeywords() {
    if($GLOBALS["WTSITEID"] != 11357 && $GLOBALS["WTSITEID"] != 11358 && $GLOBALS["WTSITEID"] != 11632) {
      parent::setKeywords();
    }
  }
  function setAttributes($attributes)
  {
    $oldMenuText = $this->getAttribute("Menu Text");
    $oldURI = $this->getAttribute("URI");
    $retVal = parent::setAttributes($attributes);

    if($attributes["Menu Text"] && $attributes["Menu Text"] != $oldMenuText) {
      $this->setURI();
    }

    $newURI = $this->getAttribute("URI");
    if($oldURI != $newURI) {
      // find if there are any related product pages...
      $template = $this->getAttribute("Template");
      $linkedContentID = $this->getAttribute("Linked Content ID");
      if($template == "Product Category") {
        if($linkedContentID) {
          $sql = "UPDATE
                    Category
                  SET
                    URI = '" . mysql_escape_string($newURI) . "'
                  WHERE
                    __guid = $linkedContentID";
          mysql_query($sql);
        }      
      }
      if($template == "Product") {
        if($linkedContentID) {
          $sql = "UPDATE
                    Product
                  SET
                    URI = '" . mysql_escape_string($newURI) . "'
                  WHERE
                    __guid = $linkedContentID";
          mysql_query($sql);
        }
      }

    }
  }

  /**
   *  Get the URI for the page
   *
   *  @method getURI
   *  @param {boolean} [absolute=false] If true, return the absolute URI
   *  @param {boolean} [latest=false] If true, return the latest URI (possibly draft version or non approved)
   *  @return {String} the URI for the page
   */
  function getURI($absolute = false, $latest = false) {
    if($GLOBALS["WTURIPERNODE"]) {
      return  parent::getURI($absolute, $latest) ;
    }

    $languageID = $this->getLanguageID();
    if($languageID != 0) {
      $sql = "SELECT
                __translationOfGuid
              FROM
                wtNode
              WHERE
                __guid = " . $this->m_guid;
      $query = mysql_query($sql);
      if($row = mysql_fetch_row($query)) {
        $guid = $row[0];
        $node = $GLOBALS["WT"]->getNode($guid);
        return $node->getURI();
      }
    }

    $latest = true;
    if($absolute) {
      return $GLOBALS["WT"]->getSiteSetting("Site URL") . "?page=" . $this->getAttribute("URI", $latest);
    } else {
      if($GLOBALS["WT"]->getSiteSetting("Path Mode") == "rewrite") {

        return  $this->getAttribute("URI", $latest);
      } else {
        return "?page=" . $this->getAttribute("URI", $latest);
      }
    }
  }

  /**
   *  This function is called just before the output for the page is to be produced<br/>
   *  It can be overridden to provide custom functionality before a page is shown
   *
   *  @method preRender
   */

  function preRender() 
  {
  }


  /**
   *  This function is called just before a template is rendered<br/>
   *  It can be overridden and used to send custom data to the template
   *
   *  @method preEvaluateTemplate
   *  @param {String} template The template about to be evaluated
   *  @param {Array} templateData The data to send to the template. Modify this array to change the data to be passed to the template
   *  @param {Array} args Extra Data
   
   */

  function preEvaluateTemplate($template, &$templateData, $args) 
  {
  }


/*  function SetAttributes($attributes) {
    
  }*/
  /**
   *  Return the HTML for the page
   *
   *  @method render
   *  @return {String} The HTML for the page
   */

  function render() {

//    $GLOBALS["WT"]->pushRenderContext($this->m_guid);

/*    if($GLOBALS["WT"]->getMode() == "edit") {
      $this->setKeywords();
    }
*/
//    $this->pushContext($this->getPath());
    $GLOBALS["WT"]->m_currentPage = $this;


    if($GLOBALS["WT"]->getMode() == "edit" || $GLOBALS["WT"]->getMode() == "moderate" || $GLOBALS["WTPREVIEWMODE"]) {
      $data = $this->getAttributes(true);
    } else {
      $data = $this->getAttributes();
    }

 
    $pageData = Array();
    if($data["Data"] != "") {
      $pageData = unserialize($data["Data"]);
    }
//    parse_str($data["Data"], $pageData);

    foreach($pageData as $key => $value) {
      $GLOBALS["WTVARS$key"] = $value;
    }



//    $this->m_template = $data["Template"];

    if(!$data["Template ID"]) {
      return;
    }

    $template = $GLOBALS["WT"]->getNode($data["Template ID"]);

    
    if($template == NULL) {
      return;
    }

    $this->m_template = $template->getPath();


    foreach($GLOBALS["WTPRERENDERHANDLERS"] as $preRenderHandler) {
      call_user_func($preRenderHandler, $this);
    }

    $this->preRender();

    $template = $GLOBALS["WT"]->getNode($this->m_template);

    $pageDataNode = $this;

    $data = Array();

    $languageID = WTSession::get("WTLANGUAGEID");
    if($languageID) {
      $translationNode = $this->getTranslationNode($languageID);
      if($translationNode) {
        $pageDataNode = $translationNode;
      } 
    }   


    $data = $pageDataNode->getAttributes();
    $attributes = $this->getAttributes();
    foreach($attributes as $key => $value) {
      if($data[$key] == "") {
        $data[$key] = $value;
      }
    }

    $data["Template"] = $template->getName();
    $data["Template ID"] = $template->m_guid;

    $data["__guid"] = $this->m_guid;
    if($GLOBALS["WTMENUTEXT"]) {
      $data["Menu Text"] = $GLOBALS["WTMENUTEXT"];
    }
  
    if($template != NULL) { 
//      $this->PreEvaluateTemplate($template->getPath(), $data, NULL);

      $this->preEvaluateTemplate($this->m_template, $data, NULL);
      $data["Content"] =  $template->evaluate($data);
    } else {
      return "Template doesn't exist: " . $this->m_template . "<br>";
    }

    if($GLOBALS["WTMENUTEXT"]) {
      $data["Menu Text"] = $GLOBALS["WTMENUTEXT"];
    }       


    if(array_key_exists("WTPAGELAYOUT", $GLOBALS)) {
      if($GLOBALS["WTPAGELAYOUT"] == "") {
        $content = $data["Content"];
      } else {
        $holder = $GLOBALS["WT"]->getNode("Templates/Page Layouts/{$GLOBALS["WTPAGELAYOUT"]}");
        if($holder != NULL) {
          $this->preEvaluateTemplate($holder->getPath(), $data, NULL);
          $content = $holder->evaluate($data);
        }
      }
    } else {
      $holder = $GLOBALS["WT"]->getNode("Templates/Page Layouts/Holder");
      $this->preEvaluateTemplate($holder->getPath(), $data, NULL);
      $content = $holder->evaluate($data);
    }

    if($GLOBALS["WT"]->getMode() == "edit") {
// commented out set keywords cos its causint problems
      if($GLOBALS["WTSITEID"] != 11473) {
        $this->setKeywords();
      }
    }

//    $this->popContext();
//    $GLOBALS["WT"]->popRenderContext();

    return $content;
//    return $templatePath;
  }

  /**
   *  Get the keywords for the page<br/>
   *  Useful for indexing the page
   *
   *  @method getKeywords
   */

  function getKeywords() {
    $content = "";
    $mode = $GLOBALS["WT"]->getMode();
    $GLOBALS["WT"]->setMode("index"); 
    $template = $this->getAttribute("Template");
    if($template != "") {
      $content = $this->render();
    }
    $GLOBALS["WT"]->setMode($mode);

    if(array_key_exists("WTINDEX", $GLOBALS)) {
      if($GLOBALS["WTINDEX"] == "no") {
        return "";
      }
    }

//    return strip_tags($content, '<script><style>');
    return WTPage::getVisibleTextFromHtml($content);
  }


  /**
   * Force a page to switch to secure mode
   *
   * @method forceSecure
   *
   */
  function forceSecure() {
    if(array_key_exists("WTINOFFICE", $_SESSION) && $_SESSION["WTINOFFICE"]) {
      return;
    }

    if(!array_key_exists("HTTPS", $_SERVER) || strtolower($_SERVER["HTTPS"]) != "on") {
      $secureURL = WTConfig::get("Site Details/Site Secure URL");
      if(strpos($secureURL, "https") === false) {
        $currentURL = "http://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        if(strpos($currentURL, $secureURL) !== false) {
          return;
        }

      }
      if($secureURL) {// && strpos($secureURL, "https") !== false) {
        $pagePath = $_SERVER["REQUEST_URI"];
        $pagePath = substr($pagePath, strlen($GLOBALS["WT"]->getSiteSetting("Site Base")));
        $secureURL .= "__session/" . WTSession::getKey() . "/" .$pagePath;
//            print "secure url = $secureURL";
        header("Location: $secureURL");
        exit("");
      }
    }
  }

}

?>