Fun with PHP, join me!

Ye' old general discussion board. Basically, for everything that isn't covered elsewhere. Come here to shoot the breeze, shoot your mouth off, or whatever suits your fancy.
This forum is not for asking programming related questions.

Moderator: General Moderators

jason
Site Admin
Posts: 1767
Joined: Thu Apr 18, 2002 3:14 pm
Location: Montreal, CA
Contact:

Post by jason »

Well, the HELO part is a programmer joke, especially if you have ever done any socket work.

As far as the ! part, that is what I was referring to when I said "Could have gone much further...". However, if you would like me to implement that.... give me a minute here
jason
Site Admin
Posts: 1767
Joined: Thu Apr 18, 2002 3:14 pm
Location: Montreal, CA
Contact:

Post by jason »

Sorry for any confusion. Here is the more fully fleshed out version:

Code: Select all

<?php
header('Content-type: text/html');
header("Cache-Control: "no-cache, must-revalidate"");
header("Pragma: "no-cache"");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("X-PROGRAM-TYPE: HELO-WORLD");

$samplePhrasebook = array (
	'en-us' => array (
			'HELLO' => 'Hello $name!',
			'HI' => 'Hi $name!',
			'BYE' => 'Goodbye $name.',
			'CYA' => 'See you around, $name.'
	)
);

class Phrasebook
{
	var $_book;
	var $_chapter;
	
	function Phrasebook ( &$book )
	{
		$this->_book =& $book;
	}
	
	function loadChapter ( $name )
	{
		if ( $this->chapterExists($name) )
			$this->_chapter = $name;
	}
	
	function chapterExists ( $name )
	{
		return isset($this->_book[$name]);
	}
	
	function phrase ( $phrase_name, $values )
	{
		return $this->_compilePhrase($this->_book[$this->_chapter][$phrase_name], $values);
	}
	
	function _compilePhrase ( $phrase, $values )
	{
		$keys = array_keys($values);
		for ( $x = 0, $i = count($keys); $x < $i; $x++ ) {
			$keys[$x] = '$'.$keys[$x];
		}
		return str_replace($keys, $values, $phrase);
	}
}

class Person
{
   var $_name;
   var $_talking_to;
   var $_listening_to;
   var $_phrasebook;

   function Person ( $name, &$language )
   {
      $this->setName($name);
      $this->_phrasebook = new Phrasebook($language);
      $this->_phrasebook->loadChapter('en-us');
   }

   function getName ()
   {
      return $this->_name;
   }

   function setName ( $name )
   {
      $this->_name = $name;
   }

   function talkTo ( &$person )
   {
      $this->_talking_to =& $person;
      $this->_listening_to =& $person;
      $this->_talking_to->listenTo($this);
      $this->say($this->_phrasebook->phrase('HELLO', array('name'=>$this->_talking_to->getName())));
   }

   function say ( $string )
   {
      $this->_talking_to->hear($string);
   }

   function listenTo ( &$person )
   {
      $this->_listening_to =& $person;
   }

   function hear ( $string )
   {
      echo $string, "\n";
   }
}

?>
<html><head><title>Complex Hello World</title></head><body>
<?php
$jason = new Person('Jason', $samplePhrasebook);
$world = new Person('World', $samplePhrasebook);
$jason->talkTo($world);
?>
</body></html>
User avatar
HungryMind
Forum Commoner
Posts: 41
Joined: Fri Jun 20, 2003 10:33 am
Location: Alameda, CA

Post by HungryMind »

Beautiful, awesome! I can't wait until someone adds onto THAT. I wouldn't even know where to begin :? .
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Post by nigma »

Don't delete these posts / replies please! I am coming up with a master plan to blow all of you away..... just wait....
User avatar
HungryMind
Forum Commoner
Posts: 41
Joined: Fri Jun 20, 2003 10:33 am
Location: Alameda, CA

Post by HungryMind »

I look forward to your idea, nigma! Until then, this will have to do. I basically just added a giant "do, while" statement around the area that prints the "Hello World!" string to the screen.

Code: Select all

<?php
header('Content-type: text/html');
header("Cache-Control: "no-cache, must-revalidate"");
header("Pragma: "no-cache"");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("X-PROGRAM-TYPE: HELO-WORLD");


$printcounter = 0;
$samplePhrasebook = array (
   'en-us' => array (
         'HELLO' => 'Hello $name!',
         'HI' => 'Hi $name!',
         'BYE' => 'Goodbye $name.',
         'CYA' => 'See you around, $name.'
   )
);

class Phrasebook
{
   var $_book;
   var $_chapter;

   function Phrasebook ( &$book )
   {
      $this->_book =& $book;
   }

   function loadChapter ( $name )
   {
      if ( $this->chapterExists($name) )
         $this->_chapter = $name;
   }

   function chapterExists ( $name )
   {
      return isset($this->_book[$name]);
   }

   function phrase ( $phrase_name, $values )
   {
      return $this->_compilePhrase($this->_book[$this->_chapter][$phrase_name], $values);
   }

   function _compilePhrase ( $phrase, $values )
   {
      $keys = array_keys($values);
      for ( $x = 0, $i = count($keys); $x < $i; $x++ ) {
         $keys[$x] = '$'.$keys[$x];
      }
      return str_replace($keys, $values, $phrase);
   }
}

class Person
{
   var $_name;
   var $_talking_to;
   var $_listening_to;
   var $_phrasebook;

   function Person ( $name, &$language )
   {
      $this->setName($name);
      $this->_phrasebook = new Phrasebook($language);
      $this->_phrasebook->loadChapter('en-us');
   }

   function getName ()
   {
      return $this->_name;
   }

   function setName ( $name )
   {
      $this->_name = $name;
   }

   function talkTo ( &$person )
   {
      $this->_talking_to =& $person;
      $this->_listening_to =& $person;
      $this->_talking_to->listenTo($this);
      $this->say($this->_phrasebook->phrase('HELLO', array('name'=>$this->_talking_to->getName())));
   }

   function say ( $string )
   {
      $this->_talking_to->hear($string);
   }

   function listenTo ( &$person )
   {
      $this->_listening_to =& $person;
   }

   function hear ( $string )
   {
      echo $string, "\n";
   }
}

?>
<html><head><title>Complex Hello World</title></head><body>
<?php

do
{
$jason = new Person('Jason', $samplePhrasebook);
$world = new Person('World', $samplePhrasebook);
$jason->talkTo($world);
$printcounter++;
}while($printcounter < 1)

?>
</body></html>
User avatar
m@ndio
Forum Regular
Posts: 163
Joined: Fri Jun 06, 2003 12:09 pm
Location: UK

Post by m@ndio »

oh! go on then..

Code: Select all

<?php 
$letters = array("first_letter"=>"h",
"second_letter"=>"e",
"third_letter"=>"l",
"forth_letter"=>"l",
"fifth_letter"=>"o",
"sixth_letter"=>"w",
"seventh_letter"=>"o",
"eighth_letter"=>"r",
"nineth_letter"=>"l",
"tenth_letter"=>"d",
"eleventh_letter"=>"!");

for($i=0;$i<count($letters);$i++)
{
   echo
$letters["first_letter"][$i].
$letters["second_letter"][$i].
$letters["third_letter"][$i].
$letters["forth_letter"][$i].
$letters["fifth_letter"][$i].
" ".
$letters["sixth_letter"][$i].
$letters["seventh_letter"][$i].
$letters["eighth_letter"][$i].
$letters["nineth_letter"][$i].
$letters["tenth_letter"][$i].
$letters["eleventh_letter"][$i];
}

?>
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

hm, thought this is about extending the given code .?.

Code: Select all

<?php
header('Content-type: text/html');
header("Cache-Control: "no-cache, must-revalidate"");
header("Pragma: "no-cache"");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("X-PROGRAM-TYPE: HELO-WORLD");


$printcounter = 0;
$samplePhrasebook = array (
   'en-us' => array (
         'HELLO' => 'Hello $name!',
         'HI' => 'Hi $name!',
         'BYE' => 'Goodbye $name.',
         'CYA' => 'See you around, $name.'
   )
);

class Phrasebook
{
   var $_book;
   var $_chapter;

   function Phrasebook ( &$book )
   {
      $this->_book =& $book;
   }

   function loadChapter ( $name )
   {
      if ( $this->chapterExists($name) )
         $this->_chapter = $name;
   }

   function chapterExists ( $name )
   {
      return isset($this->_book[$name]);
   }

   function phrase ( $phrase_name, $values )
   {
      return $this->_compilePhrase($this->_book[$this->_chapter][$phrase_name], $values);
   }

   function _compilePhrase ( $phrase, $values )
   {
      $keys = array_keys($values);
      for ( $x = 0, $i = count($keys); $x < $i; $x++ ) {
         $keys[$x] = '$'.$keys[$x];
      }
      return str_replace($keys, $values, $phrase);
   }
}

class Person
{
   var $_name;
   var $_talking_to;
   var $_listening_to;
   var $_phrasebook;

   function Person ( $name, &$language )
   {
      $this->setName($name);
      $this->_phrasebook = new Phrasebook($language);
      $this->_phrasebook->loadChapter('en-us');
   }

   function getName ()
   {
      return $this->_name;
   }

   function setName ( $name )
   {
      $this->_name = $name;
   }

   function talkTo ( &$person )
   {
      $this->_talking_to =& $person;
      $this->_listening_to =& $person;
      $this->_talking_to->listenTo($this);
      $this->say($this->_phrasebook->phrase('HELLO', array('name'=>$this->_talking_to->getName())));
   }

   function say ( $string )
   {
      $this->_talking_to->hear($string);
   }

   function listenTo ( &$person )
   {
      $this->_listening_to =& $person;
   }

   function hear ( $string )
   {
      echo $string, "\n";
   }
}

class ObjectDispatch
{
	var $objects = array();
	
	function createInstance($classname, $arguments, $uid)
	{
		if( !class_exists($classname) )
			return 'class ' . $classname . ' does not exists';
		elseif( isset($this->objects[$uid]) )
			return 'uid "' . $uid . '" already in use';
		else
		{
			if ( is_array($arguments) && count($arguments) > 0 )
				$argString = '$arguments[''' . join('''], $arguments[''', array_keys($arguments)) . ''']';
			else
				$argString = '$arguments';
			eval( '$this->objects[$uid] = new $classname('.$argString.');' );
			return true;
		}
	}
	
	function invoke($uid, $method, $arguments)
	{
		if ( !isset($this->objects[$uid]) )
			return 'no object assigned to uid "'.$uid.'"';
		elseif(!method_exists($this->objects[$uid], $method))
			return 'object "'.$uid.'" does not have a method called"'.$method.'"';
		else
		{
			if ( !is_array($arguments) )
				$arguments = array($arguments);
			return array(
					'uid' => $uid,
					'method' => $method,
					'retval' => call_user_func_array(array($this->objects[$uid], $method), $arguments)
				);
		}
	}
	
	function getObject($uid)
	{
		if( isset($this->objects[$uid]) )
			return $this->objects[$uid];
		else
			return NULL;
	}
}

?>
<html><head><title>Complex Hello World</title></head><body>
<?php

do
{
	$dispatch = new ObjectDispatch;
	
	$dispatch->createInstance('Person', array('Jason', $samplePhrasebook), 'jason');
	$dispatch->createInstance('Person', array('World', $samplePhrasebook), 'world');
	
	$dispatch->invoke('jason', 'talkTo', $dispatch->getObject('world'));

	$printcounter++;
}while($printcounter < 1)

?>
</body></html>
Judas
Forum Commoner
Posts: 67
Joined: Tue Jun 10, 2003 3:34 pm
Location: Netherlands

Arty dude

Post by Judas »

:arrow: Kick off

Code: Select all

<?php
//fase een
//
function maakKnop($font_file,$fontsize,$imageheight,$achtergrond_kleur,$font_kleur,$tekst,$file){
$thetextbox = ImageTTFBBox ($fontsize, 0, "ttf/$font_file", "$tekst");
$imagewidth = $thetextbox[2]+6;
$myimg=ImageCreate($imagewidth, $imageheight);
if ($achtergrond_kleur=='zwart'){$col1=ImageColorAllocate($myimg, 0, 0, 0);}
elseif($achtergrond_kleur=='rood'){$col1=ImageColorAllocate($myimg, 255, 0, 0);}
elseif($achtergrond_kleur=='wit'){$col1=ImageColorAllocate($myimg, 255, 255, 255);}
if ($font_kleur=='zwart'){$col2=ImageColorAllocate($myimg, 0, 0, 0);}
elseif($font_kleur=='rood'){$col2=ImageColorAllocate($myimg, 255, 0, 0);}
elseif($font_kleur=='wit'){$col2=ImageColorAllocate($myimg, 255, 255, 255);}
$xpos = 2;
$ypos = 2+$fontsize;
ImageTTFText ($myimg, $fontsize, 0, $xpos, $ypos, $col2, "ttf/$font_file", "$tekst");
ImageJpeg($myimg, "$file");
ImageDestroy($myimg);
}

$tekst='Hallo wereld';
$font_file='ARIAL.TTF';
$fontsize=18;
$imageheight=22;
$achtergrond_kleur='wit';
$font_kleur='zwart';
$file='images/hallo_wereld.jpg';


maakKnop($font_file,$fontsize,$imageheight,$achtergrond_kleur,$font_kleur,$tekst,$file);

$tmp=getimagesize ($file);
$tag=$tmp[3];

echo '<img src="'.$file.'" '.$tag.'>';
?>
Will render.
Image
(say's "Hello world" in dutch)
User avatar
HungryMind
Forum Commoner
Posts: 41
Joined: Fri Jun 20, 2003 10:33 am
Location: Alameda, CA

Post by HungryMind »

volka wrote:hm, thought this is about extending the given code .?.
Thats what I was initially thinking. Let's just see how complex we can make ONE script and let's keep the output the same:

Hello World!

By the way, the previous poster's code was really creative. I love it!
[]InTeR[]
Forum Regular
Posts: 416
Joined: Thu Apr 24, 2003 6:51 am
Location: The Netherlands

Post by []InTeR[] »

If it's about the size :) include more other scripts....

Code: Select all

<?php
/*****************************************************************************
  Yapter 2.11 - Yet Another PHP Template Engine ®
  Copyright (C) 2001-2002 Vincent Driessen

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

  For more information, visit http://www.yapter.com/ or contact us at
  info@yapter.com.
  The full terms of the GNU Lesser General Public License that apply to Yapter
  can be found at http://www.yapter.com/LICENSE
 *****************************************************************************/

class Template {
	var $_ROOT = "__DOCUMENT_ROOT";
	var $parseMode = FALSE;		// Defines whether unknown variables should be removed or left alone
	var $blox = array();		// $blox[blockname]["content"]  holds the template's content
								// $blox[blockname]["numlines"] holds the number of lines in the block
								// $blox[blockname]["parsed"]   holds a string with the parsed data
								// $blox[$_ROOT]                always holds the main template
	var $blockDefs = array();	// Keeps track of all block-definitions from which multiple blocks...
								// ...can be created instances of
	
	var $vars = array();		// This array contains all variables. All are accessible from all blocks.

	var $log;					// Keep a log of all actions
	var $prelog;	
	var $debug;					// Specifies whether the exection should be for debugging puposes (keep a logfile)
	var $startTime;				// Holds the start time of the script, so that it can compare it to the...
								// ...end time to calculate the execution time. (For debugging purposes only.)
	
	function Template($file, $debugmode = FALSE) {
		$this->debug = $debugmode;
		$this->startTime = $this->getmicrotime();
		if ($this->debug) {
			$this->prelog = "";
			$this->log = "<b>Starting debug sequence...</b><br>\n";
			$this->log .= "<br>$this->prelog<b>Template(<i>$file</i>)</b><br>\n";
			$this->callSubFunc("$this->prelog<font color="green">...calling addBlockFromFile($this->_ROOT, $file)</font><br>\n");
		}
		$this->addBlockFromFile($this->_ROOT, $file);
		if ($this->debug) {
			$this->returnSubFunc();
		}
	}
	
	function setParseMode($parseUnknownVars) {
		$this->parseMode = $parseUnknownVars;
	}
	
	/* addBlock(): adds a new block to the blox-array */
	function addBlock($blockname, $content) {
		if ($this->debug) {
			$this->log .= "<br>$this->prelog<b>addBlock()</b><br>\n";
		}
		if ($this->debug) {
			$this->log .= "$this->prelog...setting new block <i>$blockname</i> to:<menu><font color="maroon">" . htmlspecialchars(implode("", $content)) . "</font></menu>\n";
		}
		$this->blox[$blockname]["content"] = $content;
		$this->blox[$blockname]["numlines"] = sizeof($this->blox[$blockname]["content"]);
		$this->blox[$blockname]["parsed"] = "";
		if ($this->debug) {
			$this->callSubFunc("$this->prelog<font color="green">...calling prepare() function for new block <i>$blockname</i></font><br>\n");
		}
		$this->prepare($blockname);
		if ($this->debug) {
			$this->returnSubFunc();
		}
	}
	
	/* addBlockFromFile(): adds a new block, filling it with the specified's file contents */
	function addBlockFromFile($blockname, $file) {
		if ($this->debug) {
			$this->log .= "<br>$this->prelog<b>addBlockFromFile()</b><br>\n";
			$this->log .= "$this->prelog...opening file <i>$file</i><br>\n";
		}
		$content = @file($file) or $this->error("Cannot open template file <b>$file</b>!");
		if ($blockname != $this->_ROOT) {
			$this->addBlockDef($blockname, $content);
		}
		if ($this->debug) {
			$this->callSubFunc("$this->prelog<font color="green">...calling addBlock() function for the file block</font><br>\n");
		}
		$this->addBlock($blockname, $content);
		if ($this->debug) {
			$this->returnSubFunc();
		}
	}
	
	/* addBlockDef(): adds a block definition to the block-definition array from which other blocks can be copied */
	function addBlockDef($blockdef, $content) {
		if ($this->debug) {
			$this->log .= "<br>$this->prelog<b>addBlockDef(<i>$blockdef</i>, [content])</b><br>\n";
			$this->log .= "$this->prelog...trying to set block definition <i>$blockdef</i> to:<menu><font color="maroon">" . htmlspecialchars(implode("", $content)) . "</font></menu>\n";
		}
		$this->blockDefs[$blockdef] = $content;
	}
	
	/* addBlockFromDef(): copies a block from the block definition array */
	function addBlockFromDef($blockname, $blockdef) {
		if ($this->debug) {
			$this->log .= "<br>$this->prelog<b>addBlockFromDef(<i>$blockname</i>, <i>$blockdef</i>)</b><br>\n";
			$this->callSubFunc("$this->prelog<font color="green">...calling addBlock() function for the block definition <i>$blockname</i></font><br>\n");
		}
		$content = $this->blockDefs[$blockdef];
		$this->addBlock($blockname, $content);
		if ($this->debug) {
			$this->returnSubFunc();
		}
	}
	
	/* error(): handles error messages and displays them on the screen */
	function error($err) {
		if ($this->debug) {
			echo $this->log;
		}
		die("<b>Yapter error</b>: $err");
	}
	
	/* prepare(): handles subprocessing of templates found in the main template file */
	function prepare($blockname) {
		if ($this->debug) {
			$this->log .= "<br>$this->prelog<b>prepare(<i>$blockname</i>)</b><br>\n";
		}
		$block = &$this->blox[$blockname];
		for ($i = 0; $i < $block["numlines"]; $i++) {
			if (isset($block["content"][$i])) {
				$line = $block["content"][$i];
			} else {
				continue;
			}
			
			// Try to find a tag-definition on this line
			if (preg_match("/\[(INCLUDE|BLOCK|END|REUSE|SET) ([A-Za-z0-9_.\/-]+)( AS ([A-Za-z0-9_-]+))?]/", $line, $matches)) {
				$type = $matches[1];
				$name = (!empty($matches[4])) ? $matches[4] : $matches[2];
				if ($type == "END" && $matches[2] == $currblockdef) {
					if (isset($matches[4])) {
						$this->error("Given "AS"-parameter not allowed in END-tags!");
					}
					
					// End the current block definition: add the block to the blox-array
					if ($this->debug) {
						$this->log .= "$this->prelog...END-tag (<i>$name</i>) found on line $i</b><br>\n";
						$this->callSubFunc("$this->prelog<font color="green">...calling addBlockDef() for this block <i>$currblockname</i></font><br>\n");
					}
					$this->addBlockDef($currblockdef, $currblockcontents);
					if ($this->debug) {
						$this->log .= "$this->prelog<font color="green">...calling addBlockFromDef() for this block <i>$currblockname</i></font><br>\n";
					}
					$this->addBlockFromDef($currblockname, $currblockdef);
					if ($this->debug) {
						$this->returnSubFunc();
					}
					
					// Now, try to remove the block from the template definition, replacing it with a var
					if ($this->debug) {
						$this->log .= "$this->prelog...trying to delete lines $currblockstart through $i<br>\n";
					}
					for ($j = $i; $j >= $currblockstart; $j--) {
						if ($j == $currblockstart && $currblocktype == "BLOCK") {
							$block["content"][$j] = "\{$currblockname}\n";
						} else {
							unset($block["content"][$j]);
						}
					}
					
					// unset these thingies for further preparing
					unset($currblocktype);
					unset($currblockstart);
					unset($currblockname);
					unset($currblockdef);
					unset($currblockcontents);
					
				} elseif (($type == "SET" || $type == "BLOCK") && !isset($currblockname)) {
					
					if ($type == "BLOCK") {
						
						if ($this->debug) {
							$this->log .= "$this->prelog...BLOCK-tag (<i>$matches[2]</i> AS <i>$name</i>) found on line $i<br>\n";
							$this->log .= "$this->prelog...\$currblockname set to <i>$name</i><br>\n";
							$this->log .= "$this->prelog...\$currblockdef set to <i>$matches[2]</i><br>\n";
						}
						// Start block definition
						$currblocktype  = $type;
						$currblockstart = $i;
						$currblockname  = $name;
						$currblockdef   = $matches[2];
						
					} else {		// SET-tag
						
						if ($this->debug) {
							$this->log .= "$this->prelog...SET-tag (<i>$matches[2]</i>) found on line $i<br>\n";
						}
						// Start block definition
						if (isset($matches[4])) {
							$this->error("Given "AS"-parameter not allowed in SET-tags!");
						}
						if ($this->debug) {
							$this->log .= "$this->prelog...\$currblockname set to <i>$matches[2]</i><br>\n";
							$this->log .= "$this->prelog...\$currblockdef set to <i>$matches[2]</i><br>\n";
						}
						$currblocktype  = $type;
						$currblockstart = $i;
						$currblockname  = $matches[2];
						$currblockdef   = $matches[2];
						
					}
					
				} elseif ($type == "INCLUDE" && !isset($currblockname)) {
					
					if ($this->debug) {
						$this->log .= "$this->prelog...INCLUDE-tag (<i>$matches[2]</i> AS <i>$name</i>) found on line $i<br>\n";
					}
					
					// Make this line a variable...
					if ($this->debug) {
						$this->log .= "$this->prelog...turning line $i into variable (<i>\{$name}</i>)<br>\n";
					}
					$block["content"][$i] = "\{$name}\n";
					
					// ...and include the given file...
					if ($this->debug) {
						$this->callSubFunc("$this->prelog<font color="green">...calling addBlockFromFile() for this INCLUDE-tag</font><br>\n");
					}
					$this->addBlockFromFile($name, $matches[2]);
					if ($this->debug) {
						$this->returnSubFunc();
					}
					
				} elseif ($type == "REUSE" && !isset($currblockname)) {
					
					if (!isset($matches[4])) {
						$this->error("Missing "AS"-parameter in [REUSE <b>$name</b>] tag!");
					}
					
					// Make this line a variable...
					if ($this->debug) {
						$this->log .= "$this->prelog...REUSE-tag found on line $i<br>\n";
						$this->log .= "$this->prelog...turning line $i into variable (<i>\{$name}</i>)<br>\n";
					}
					$block["content"][$i] = "\{$matches[4]}\n";
					
					// ...and get this REUSE value from the block definition list...
					if ($this->debug) {
						$this->callSubFunc("$this->prelog<font color="green">...calling addBlockFromDef() for this tag</font><br>\n");
					}
					$this->addBlockFromDef($matches[4], $matches[2]);
					if ($this->debug) {
						$this->returnSubFunc();
					}
					
				} elseif ($currblockname != $name) {
					if ($currblockname) {
						$currblockcontents[] = $line;
					}
				}
			} else {
				// No tag-definition... just normal text so do nothing here
				if (!empty($currblockname)) {
					$currblockcontents[] = $line;
				}
			}
		}
	}
	
	/* parse(): parses the specified block, filling variables and nested blockdefs */
	function parse($blockname = "") {
		if (!$blockname) $blockname = $this->_ROOT;
		if ($this->debug) {
			$this->log .= "<br>$this->prelog<b>parse(<i>$blockname</i>)</b><br>\n";
		}
		$block = &$this->blox[$blockname];
		$parsed = $block["content"];
		
		// Loop through all the lines of the template and parse variables one-by-one
		for ($i = 0; $i < $block["numlines"]; $i++) {
			if (!isset($parsed[$i])) {
				continue;
			}
			$line = $parsed[$i];
			
			// Look for variables in this line, processing it character-by-character
			unset($start);
			unset($buffer);
			for ($j = 0; $j < strlen($line); $j++) {
				$char = $line[$j];
				if (!isset($start) && $char == '{') {
					$start = $j;
					if ($this->debug) {
						$this->log .= "$this->prelog...variable-start found at line $i, offset $start<br>\n";
					}
				} elseif (isset($start) && $char == '}') {
					// The sequence {} is not a valid variable value
					if (!isset($buffer)) {
						if ($this->debug) {
							$this->log .= "$this->prelog...variable-end found at line $i, offset $j, but not a valid var (empty set)<br>\n";
						}
						unset($start);
						unset($buffer);
						continue;
					} else {
						// Gotcha! Now replace this variable with its contents
						// First, check to see if it's a variable or a block that has to be parsed
						if ($this->debug) {
							$this->log .= "$this->prelog...variable-end found at line $i, offset $j --> variable is <i>$buffer</i><br>\n";
						}
						if (isset($this->vars[$buffer])) {
							if ($this->debug) {
								$this->log .= "$this->prelog...set variable <i>$buffer</i> found in variables array<br>\n";
							}
							$value = $this->vars[$buffer];
						} elseif ($this->blox[$buffer]) {
							if ($this->debug) {
								$this->log .= "$this->prelog...block definition of <i>$buffer</i> found<br>\n";
							}
							if ($this->blox[$buffer]["parsed"]) {
								if ($this->debug) {
									$this->log .= "$this->prelog...block <i>$buffer</i> had been parsed already, no parsing needed<br>\n";
								}
								// The value must be filled with the parsed data from the $buffer block
								$value = @implode("", $this->blox[$buffer]["parsed"]);
							} else {
								if ($this->debug) {
									$this->callSubFunc("$this->prelog...block <i>$buffer</i> had not been parsed yet, so start parsing <i>$buffer</i> now<br>\n");
								}
								// Make the recursive call now
								$value = @implode("", $this->parse($buffer));
								if ($this->debug) {
									$this->returnSubFunc();
								}
							}
						} else {
							if ($this->parseMode) {
								// Unable to find variable, leave this one alone...
								if ($this->debug) {
									$this->log .= "$this->prelog...variable nor block definition named <i>$buffer</i> found... removing this one<br>\n";
								}
								$value = "";
							} else {
								// Unable to find variable, leave this one alone...
								if ($this->debug) {
									$this->log .= "$this->prelog...variable nor block definition named <i>$buffer</i> found... leaving this one alone<br>\n";
								}
								unset($start);
								unset($buffer);
								continue;
							}
						}
						$part1 = substr($line, 0, $start);
						$part2 = substr($line, $start + strlen($buffer) + 2);
						$line = $part1 . $value . $part2;
						$j += strlen($value) - (strlen($buffer) + 2);
						unset($start);
						unset($buffer);
					}
				} elseif (isset($start)) {
					// Check to see $char is a proper character (range: [A-Za-z0-9_.-])
					if (($char >= 'a' && $char <= 'z') || ($char >= '0' && $char <= '9') || ($char >= 'A' && $char <= 'Z') || ($char == '_') || ($char == '.') || ($char == '-')) {
						if (!empty($buffer)) {
							$buffer .= $char;
						}
						else {
							$buffer = $char;
						}
					} else {
						unset($start);
						unset($buffer);
					}
				}
			}
			$parsed[$i] = $line;
		}
		
		$this->blox[$blockname]["parsed"] = array_merge($this->blox[$blockname]["parsed"], $parsed);
		if ($this->debug) {
			$this->log .= "$this->prelog...parsed content for <i>$blockname</i> now contains:<menu><font color="navy">" . htmlspecialchars(implode("", $this->blox[$blockname]["parsed"])) . "</font></menu>\n";
		}
		return $this->blox[$blockname]["parsed"];
	}
	
	/* set(): assigns a value to a variabele inside curly brackets ("{" and "}") */
	function set($varname, $value) {
		if ($this->debug) {
			$this->log .= "<br>$this->prelog<b>set(<i>$varname</i>, [content])</b><br>\n";
			$this->log .= "$this->prelog...setting variable value of <i>$varname</i> to:<menu><font color="purple">" . htmlspecialchars($value) . "</font></menu>\n";
		}
		$this->vars[$varname] = $value;
	}
	
	/* setFile(): assigns the contents of a file to a variabele inside curly brackets ("{" and "}") */
	function setFile($varname, $filename) {
		if ($this->debug) {
			$this->log .= "<br>$this->prelog<b>setFile(<i>$varname</i>, <i>$filename</i>)</b><br>\n";
		}
		$value = implode("", file($filename));
		if ($this->debug) {
			$this->callSubFunc("$this->prelog<font color="green">...calling set() function to do the actual variabele assignment</font><br>\n");
		}
		$this->set($varname, $value);
		if ($this->debug) {
			$this->returnSubFunc();
		}
	}
	
	/* getVar(): returns the value of the "varname" variable */
	function getVar($varname) {
		if ($this->vars[$varmane]) {
			return $this->vars[$varname];
		} else {
			return "";
		}
	}
	
	/* getBlock(): returns the content of the "blockname" block */
	function getBlockContent($blockname) {
		if ($this->$blox[$blockname]["content"]) {
			return @implode("", $this->$blox[$blockname]["content"]);
		} else {
			return "";
		}
	}
	
	/* replace(): replaces the content of one block by another */
	function replace($block, $byblock) {
		$this->blox[$block] = $this->blox[$byblock];
	}
	
	/* clear(): resets the parsed data to a null-string again and defines the block as "unparsed" */
	function clear($blockname) {
		if ($this->debug) {
			$this->log .= "<br>$this->prelog<b>clear(<i>$blockname</i>)</b><br>\n";
			$this->log .= "$this->prelog...clearing parsed data from block <i>$blockname</i><br>\n";
		}
		$this->blox[$blockname]["parsed"] = "";
		unset($this->vars[$blockname]);	// often, a variabele is set whenever a block should be discarded...
										// ...now reset such a variable to make sure the block is not overriden
	}
	
	/* getContents(): gets the final contents to be outputted on the screen */
	function getContents($blockname = "") {
		if ($blockname == "") $blockname = $this->_ROOT;
		if ($this->debug) {
			$this->log .= "<br>$this->prelog<b>getContents(<i>$blockname</i>)</b><br>\n";
			$this->log .= "...setting \$blockname to <i>$blockname</i><br>\n";
		}
		$parsed = $this->blox[$blockname]["parsed"];
		if ($parsed) {
			if ($this->debug) {
				$this->log .= "...parsed content found in <i>$blockname</i>:<menu><font color="navy">" . htmlspecialchars(implode("", $this->blox[$blockname]["parsed"])) . "</font></menu>\n";
			}
			return implode("", $parsed);
		} else {
			return "";
		}
	}
	
	/* spit(): ouputs contents to screen */
	function spit() {
		if ($this->debug) {
			echo $this->log;
		} else {
			echo $this->getContents();
		}
	}
	
	/* some fancy debugging routines */
	function callSubFunc($value) {
		$this->log .= $value;
		$this->prelog .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	}
	
	function returnSubFunc() {
		$this->prelog = substr($this->prelog, 0, -54);
	}
	
	function getmicrotime() {
		/* I got this getmicrotime()-function from the PHP.net website, but it seems to be
		   buggy, while it sometimes displays a negative execution time when you substract
		   the current time with the starting time of the script... I only noticed it at
		   my Windows localhost machine, not on Linux servers. Is anybody familiar with this
		   behaviour? Any information about this is welcome at info@yapter.com. I thank you
		   for your co-operation. */
		list($usec, $sec) = explode(" ", microtime());
		return ((float)$usec + (float)$sec);
	}
	
	function execTime() {
		return round($this->getmicrotime() - $this->startTime,5);
	}
	
	function executionTime() {
		echo "<p>\n\nThe execution time is <b>" . $this->execTime() . "</b> seconds.<br>\n";
	}
}

header('Content-type: text/html');
header("Cache-Control: "no-cache, must-revalidate"");
header("Pragma: "no-cache"");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("X-PROGRAM-TYPE: HELO-WORLD");
$template = new Template("helloworld.htm");

$printcounter = 0;
$samplePhrasebook = array (
   'en-us' => array (
         'HELLO' => 'Hello $name!',
         'HI' => 'Hi $name!',
         'BYE' => 'Goodbye $name.',
         'CYA' => 'See you around, $name.'
   )
);

class Phrasebook
{
   var $_book;
   var $_chapter;

   function Phrasebook ( &$book )
   {
      $this->_book =& $book;
   }

   function loadChapter ( $name )
   {
      if ( $this->chapterExists($name) )
         $this->_chapter = $name;
   }

   function chapterExists ( $name )
   {
      return isset($this->_book[$name]);
   }

   function phrase ( $phrase_name, $values )
   {
      return $this->_compilePhrase($this->_book[$this->_chapter][$phrase_name], $values);
   }

   function _compilePhrase ( $phrase, $values )
   {
      $keys = array_keys($values);
      for ( $x = 0, $i = count($keys); $x < $i; $x++ ) {
         $keys[$x] = '$'.$keys[$x];
      }
      return str_replace($keys, $values, $phrase);
   }
}

class Person
{
   var $_name;
   var $_talking_to;
   var $_listening_to;
   var $_phrasebook;

   function Person ( $name, &$language )
   {
      $this->setName($name);
      $this->_phrasebook = new Phrasebook($language);
      $this->_phrasebook->loadChapter('en-us');
   }

   function getName ()
   {
      return $this->_name;
   }

   function setName ( $name )
   {
      $this->_name = $name;
   }

   function talkTo ( &$person )
   {
      $this->_talking_to =& $person;
      $this->_listening_to =& $person;
      $this->_talking_to->listenTo($this);
      $this->say($this->_phrasebook->phrase('HELLO', array('name'=>$this->_talking_to->getName())));
   }

   function say ( $string )
   {
      $this->_talking_to->hear($string);
   }

   function listenTo ( &$person )
   {
      $this->_listening_to =& $person;
   }

   function hear ( $string )
   {
      GLOBAL $template; // <--------------- I'M NOT HAPPY WITH THIS. Somebody????
      $template->set("helloword",$string."\n");
   }
}

class ObjectDispatch
{
	var $objects = array();
	
	function createInstance($classname, $arguments, $uid)
	{
		if( !class_exists($classname) )
			return 'class ' . $classname . ' does not exists';
		elseif( isset($this->objects[$uid]) )
			return 'uid "' . $uid . '" already in use';
		else
		{
			if ( is_array($arguments) && count($arguments) > 0 )
				$argString = '$arguments[''' . join('''], $arguments[''', array_keys($arguments)) . ''']';
			else
				$argString = '$arguments';
			eval( '$this->objects[$uid] = new $classname('.$argString.');' );
			return true;
		}
	}
	
	function invoke($uid, $method, $arguments)
	{
		if ( !isset($this->objects[$uid]) )
			return 'no object assigned to uid "'.$uid.'"';
		elseif(!method_exists($this->objects[$uid], $method))
			return 'object "'.$uid.'" does not have a method called"'.$method.'"';
		else
		{
			if ( !is_array($arguments) )
				$arguments = array($arguments);
			return array(
					'uid' => $uid,
					'method' => $method,
					'retval' => call_user_func_array(array($this->objects[$uid], $method), $arguments)
				);
		}
	}
	
	function getObject($uid)
	{
		if( isset($this->objects[$uid]) )
			return $this->objects[$uid];
		else
			return NULL;
	}
}

do
{
	$dispatch = new ObjectDispatch;
	
	$dispatch->createInstance('Person', array('Jason', $samplePhrasebook), 'jason');
	$dispatch->createInstance('Person', array('World', $samplePhrasebook), 'world');
	
	$dispatch->invoke('jason', 'talkTo', $dispatch->getObject('world'));
    $template->parse("say");
	$printcounter++;
}while($printcounter < 1);
 $template->parse();
 $template->spit();
?>
helloword.htm

Code: Select all

&lt;html&gt;&lt;head&gt;&lt;title&gt;Complex Hello World&lt;/title&gt;&lt;/head&gt;&lt;body&gt;
&#1111;BLOCK say]
&#123;helloword&#125;
&#1111;END say]
&lt;/body&gt;&lt;/html&gt;
Last edited by []InTeR[] on Tue Jun 24, 2003 7:18 am, edited 1 time in total.
lcidw
Forum Commoner
Posts: 58
Joined: Mon Apr 28, 2003 8:55 am
Location: Netherlands

Post by lcidw »

You forgot a ';'.

Code: Select all

// &#1111;FIND]
&#125;while($printcounter < 1)

// &#1111;REPLACE WITH]
&#125;while($printcounter < 1);
[]InTeR[]
Forum Regular
Posts: 416
Joined: Thu Apr 24, 2003 6:51 am
Location: The Netherlands

Post by []InTeR[] »

Last edited by []InTeR[] on 24-06-2003 14:18:48, edited 1 time in total
User avatar
miller2300
Forum Newbie
Posts: 5
Joined: Wed Jun 18, 2003 2:14 pm
Location: Royersford, PA

Post by miller2300 »

Just how much free time do you people have ?

:D
pootergeist
Forum Contributor
Posts: 273
Joined: Thu Feb 27, 2003 7:22 am
Location: UK

Post by pootergeist »

and now write an application for transfering the American national debt contributions into my bank account daily at 9am GMT using less lines of code.
User avatar
m@ndio
Forum Regular
Posts: 163
Joined: Fri Jun 06, 2003 12:09 pm
Location: UK

Post by m@ndio »

hehe :o
Post Reply