• 0

[PHP/MySQL] $15 Contest for the most complex code


Question

Ok, so the rules are simple. Just post the most complex php/mysql code (within reason don't post some mysql string that takes up 500 pages) that takes up of a maximum of 2 pages of code (printed). It doesn't even have to be yours (as long as you have a right to post it). Just post it and explain what it does. The winner will be chosen by me and I'll paypal them $15. Contest ends Friday. Have fun! :)

btw: I'm doing this for a learning experience more than anything. I want to see really complex pieces of work so I can see where I'm at with my coding as far as queries go. Just to fill you in as you're probably wondering why on earth I decided to do this lol.

25 answers to this question

Recommended Posts

  • 0
<?php

class Blog {

	public $id;
	public $userId;
	public $title;
	public $body;
	public $views;
	public $comments;
	public $voteCount;
	public $voteAverage;
	public $voteTotal;
	public $voteUserIds;
	public $created;
	public $updated;
	public $autoLoad;

	function __construct($id, $userId, $title, $body=NULL, $views=NULL, $comments=NULL, $voteCount=NULL, $voteAverage=NULL, $voteTotal=NULL, $voteUserIds=NULL, $created=NULL, $updated=NULL, $autoLoad=array()) {
		$this->id 			= $id;
		$this->userId		= $userId;
		$this->title 		= stripslashes($title);
		$this->body 		= stripslashes($body);
		$this->views		= $views;
		$this->comments		= $comments;
		$this->voteCount 	= $voteCount;
		$this->voteAverage	= $voteAverage;
		$this->voteTotal	= $voteTotal;
		$this->voteUserIds	= $voteUserIds;
		$this->created 		= $created;
		$this->updated		= $updated;
		$this->autoLoad		= $autoLoad;
		$this->AutoLoad($this->autoLoad);
	}


	public function AutoLoad($autoLoad) {

		if(is_array($autoLoad)) {
			foreach($autoLoad as $load):
				switch($load):
					case 'comments' :
						$this->LoadComments();
					break;
					case 'tags' :
						$this->LoadTags();
					break;
				endswitch;
			endforeach;
		} else if ($autoLoad === true) {
			$this->LoadComments();
			$this->LoadTags();
		}
	}


	public static function Load($id, $autoLoad=array()) {

		try {
			$db = Database::GetInstance();
			$result = $db->query("SELECT * FROM Blog WHERE id = ".$id);

				if($result && $result->num_rows > 0) {
					$q = $result->fetch_object();
						if($Object = new self($q->id, $q->user_id, $q->title, $q->body, $q->views, $q->comments, $q->vote_count, $q->vote_average, $q->vote_total, $q->vote_user_ids, $q->created, $q->updated, $autoLoad)) {
							return $Object;
						}
					} else {
						throw new ApplicationException('Could not load blogId '.$id);
					}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}
	}


	public function LoadComments() {
		$this->Comments = Comment_Blog::LoadByBlogId($this->id);
	}


	public function LoadTags() {
		$this->Tags = Tag_Blog::LoadTagsByBlogId($this->id);
	}



	public function AddView() {

		try {
			$db = Database::GetInstance();
			$result = $db->query("UPDATE Blog SET views = views + 1 WHERE id = ".$this->id);

				if(!$result) {
					return false;
				} else if ($db->affected_rows >= 0) {
					return true;
				} else {
					return false;

				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public function HasVoted($userId) {
		$items = explode(',', $this->voteUserIds);
		return in_array($userId, $items) ? true : false;
	}

	public function TagsToString() {

			if(!empty($this->Tags)):
				$result = NULL;
					foreach($this->Tags as $tag):
						$result .= ', '.$tag->title;
					endforeach;
				return substr($result, 2);
			endif;
		return false;
	}


	public function Vote($rating) {
	global $User;

		try {
			$db = Database::GetInstance();

			if($User->id == $this->userId) {//my blog, cant vote
				return false;
			} else if ($this->HasVoted($User->id) == true) {//already voted
				return false;
			}

			$this->voteUserIds = $this->voteUserIds.",".$User->id;

			if($this->voteCount > 1) {
				$this->voteTotal 	= $this->voteTotal + $rating;
				$this->voteCount 	= $this->voteCount + 1;
				$this->voteAverage 	=  $this->voteTotal / $this->voteCount + 1;
			} else {
				$this->voteAverage = $rating;
			}

			$result = $db->query("UPDATE Blog SET vote_count = vote_count + 1, vote_average = '".$this->voteAverage."', vote_user_ids = '".$this->voteUserIds."', vote_total = vote_total + $rating WHERE id = ".$this->id);

				if(!$result) {
					return false;
				} else if ($db->affected_rows >= 0) {
					return true;
				} else {
					return false;

				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public function AddComment($blogId) {

		try {
			$db = Database::GetInstance();
			$result = $db->query("UPDATE Blog SET comments = comments + 1 WHERE id = ".$blogId);

				if(!$result) {
					return false;
				} else if ($db->affected_rows >= 0) {
					return true;
				} else {
					return false;

				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public function RemoveComment($blogId) {

		try {
			$db = Database::GetInstance();
			$result = $db->query("UPDATE Blog SET comments = comments - 1 WHERE id = ".$blogId);

				if(!$result) {
					return false;
				} else if ($db->affected_rows >= 0) {
					return true;
				} else {
					return false;

				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public function Save() {

		try {
			$db = Database::GetInstance();
			$result = $db->query("UPDATE Blog SET title = ".$db->safe($this->title).", body = ".$db->safe($this->body).", updated = ".time()." WHERE id = ".$this->id);

				if(!$result) {
					return false;
				} else if ($db->affected_rows >= 0) {
					return true;
				} else {
					return false;
				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public static function LoadAllByType($from, $to, $type=NULL, $extra=NULL, $count=0, $autoLoad=array()) {
	global $User;

		try {
			$db = Database::GetInstance();

			if($type == 'by_user') {
				$arg = " AND b.user_id = $extra ";
				$join = NULL;
			} else if ($type == 'by_tag') {
				$arg = ' AND t.title = '.$db->safe($extra);
				$join = "LEFT JOIN Tag_Blog tb ON (tb.blog_id = b.id) LEFT JOIN Tag t ON (tb.tag_id = t.id) ";
			} else if ($type == 'by_friends') {
				$arg = " AND b.user_id IN($extra) ";
				$join = NULL;
			} else {
				$arg = NULL;
				$join = NULL;
			}

			$sql = "SELECT b.*, u.username as username, ud.id as ud_id, ud.key, ud.value 
			FROM Blog b 
			JOIN User u ON (b.user_id = u.id) 
			LEFT OUTER JOIN User_Data ud ON (u.id = ud.user_id AND ud.key = 'Avatar') 
			$join 
			WHERE b.id > 0 
			$arg 
			ORDER BY b.created DESC
			LIMIT $from, $to";
			$query = $db->query($sql) or die($db->error." $sql");

				if($count == 1) {
					return $query->num_rows;
				}

				if($query && $query->num_rows > 0):
					$blogs = array();
						while ($q = $query->fetch_object()):
							$Object = new self($q->id, $q->user_id, $q->title, $q->body, $q->views, $q->comments, $q->vote_count, $q->vote_average, $q->vote_total, $q->vote_user_ids, $q->created, $q->updated, $autoLoad);
							$Object->User = new User($q->user_id, $q->username);
							if(!empty($q->key)):
								$Object->User->Avatar = new User_Data($q->ud_id, $q->user_id, $q->key, $q->value);
							endif;
							$blogs[] = $Object;
						endwhile;
					return $blogs;
				endif;
			return false;

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public static function Create($userId, $title, $body) {

		try {
			$db = Database::GetInstance();
			$time = time();
			$db->query("INSERT INTO Blog (user_id, title, body, created, updated) VALUES ($userId, ".$db->safe($title).", ".$db->safe($body).", $time, $time) ");
			$id = $db->insert_id;

				if($db->affected_rows > 0) {
					return self::Load($id);
				} else { 
					return false;
				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public function Delete() {

		try {
			Comment_Blog::DeleteByBlogId($this->id);
			$db = Database::GetInstance();
			return $db->query("DELETE FROM Blog WHERE id = ".$this->id);

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


}

?>

  • 0

PHP code obfuscator:

<?php
set_time_limit(0);

$web=isset($_POST['w']) ? 1 : 0;
$no_change=Array();
$no_change_funcs=Array();

if($web)
{
  $tmparr=isset($_POST['vrepl']) ? trim($_POST['vrepl']) : '';

  if($tmparr)
  {
	$tmparr=explode("\n",$tmparr);
	foreach($tmparr as $vname)
	{
	  $vname=str_replace("\r","",$vname);
	  if(!preg_match("/^\\$([a-zA-Z_\x7f-\xff]{1}[a-zA-Z0-9_\x7f-\xff]*)$/i",$vname))
		errpr("Error in non-replaceable variable list");

	  $no_change[]=$vname;
	}
  }



  $tmparr=isset($_POST['frepl']) ? trim($_POST['frepl']) : '';

  if($tmparr)
  {
	$tmparr=explode("\n",$tmparr);
	foreach($tmparr as $fname)
	{
	  $fname=str_replace("\r","",$fname);
	  if(!preg_match("/^([a-zA-Z0-9_]+)$/i",$fname))
		errpr("Error in non-replaceable function list");

	  $no_change_funcs[]=$fname;
	}
  }


  $tmparr=isset($_POST['ffrepl']) ? trim($_POST['ffrepl']) : '';

  if($tmparr)
  {
	$tmparr=explode("\n",$tmparr);
	foreach($tmparr as $fname)
	{
	  $fname=str_replace("\r","",$fname);
	  if(!preg_match("/^([a-zA-Z0-9_]+)$/i",$fname))
		errpr("Error in function list witn non-replaceable variables");

	  $no_str_repl[]=$fname;
	}
  }

  $sfuncname=isset($_POST['sfunc']) ? $_POST['sfunc'] : '';
  if($sfuncname)
  {
	if(!preg_match("/^([a-zA-Z0-9_]+)$/i",$sfuncname))
	  errpr("Wrong function name for crypt");
  }
}
else
{
print <<<HERE
<html><head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>PHP Obfuscator by DX 1.0</title>
<style>
td
{
border-width:1px 1px 1px 1px;
border-style:solid;
border-color:black;
}
INPUT
{
BORDER-RIGHT: rgb(50,50,50) 1px outset;
BORDER-TOP: rgb(50,50,50) 1px outset;
FONT-SIZE: 11px;
font-family:Arial;
BORDER-LEFT: rgb(50,50,50) 1px outset;
BORDER-BOTTOM: rgb(50,50,50) 1px outset;
}
button
{
BORDER-RIGHT: rgb(50,50,50) 1px outset;
BORDER-TOP: rgb(50,50,50) 1px outset;
FONT-SIZE: 10px;
BORDER-LEFT: rgb(50,50,50) 1px outset;
BORDER-BOTTOM: rgb(50,50,50) 1px outset;
width:50px;
}
textarea
{
BORDER-RIGHT: rgb(50,50,50) 1px outset;
BORDER-TOP: rgb(50,50,50) 1px outset;
BORDER-LEFT: rgb(50,50,50) 1px outset;
BORDER-BOTTOM: rgb(50,50,50) 1px outset;
FONT-SIZE: 13px;
font-family:Arial;
}
select
{
FONT-SIZE: 10px;
background-color:#f4f4ff;
}
a,a:active,a:visited
{
background: transparent;
color: #34498B;
text-decoration: none;
font-weight:700;
font-size:10;
font-family:Arial;
background-color:wheat;
}
a:hover
{
background: transparent;
color: blue;
font-weight:700;
font-family:Arial;
font-size:10;
text-decoration: none;
background-color:yellow;
}
</style>
</head>
<body>
<form action="?" method="post">
<input type="hidden" name="w" value="1">
<table style="border-width:1px 1px 1px 1px; border-style:solid; border-collapse:collapse; border-color:black; width:100%; height:100%">
<tr><td colspan=2 align=center style="font-size:18;height:10">PHP Obfuscator by DX 1.0</td></tr>
<tr valign=top><td>Source code (With <? and ?>)<hr>
<textarea style="width:99%;font-family:Lucida Console;" rows=35 name="src"></textarea>
<br><br><center><input type="submit" value="Obfuscate!"></center>
<hr><b>Important!</b><br>Please, don't use \$\$var_name and eval.<br>
</td><td style="width:350;font-face:Arial;font-size:12;">Obfuscation options<hr>
Function name for obfuscation (optional): <input type="text" name="sfunc" value=""><hr>
<input type="checkbox" name="obvars" checked> Replace variables<br>
<input type="radio" value="0" name="vtype" checked> Give short names to variables<br>
<input type="radio" value="1" name="vtype"> Give long names to variables<br>
<hr>
<input type="checkbox" name="obstrs" checked> Static strings obfuscation<br>(speed will decrease)<br>
<input type="radio" value="0" name="stype"> Simple obfuscation<br>
<input type="radio" value="1" name="stype" checked> Encode in base64<br>
<hr>
<input type="checkbox" name="obfuncs" checked> Replace functions<br>
<input type="radio" value="0" name="ftype" checked> Functions short names<br>
<input type="radio" value="1" name="ftype"> Functions long names<br>
<hr>
<input type="checkbox" name="cmpr" checked>Maximum compression<hr>
Non-replaceable variables:<br>
<textarea style="width:340;font-family:Lucida Console;" rows=10 name="vrepl">\$_GET
\$_POST
\$_COOKIE
\$_SERVER
\$_FILE
\$HTTP_GET_VARS
\$HTTP_POST_VARS
\$HTTP_COOIE_VARS
\$GLOBALS
\$HTTP_SERVER_VARS
\$HTTP_POST_FILES
\$_REQUEST
\$_SESSION
\$HTTP_SESSION_VARS
\$_ENV
\$HTTP_ENV_VARS
\$php_errormsg
\$HTTP_RAW_POST_DATA
\$http_response_header
\$argc
\$argv
\$this</textarea>
<br>Non-replaceable functions:<br>
<textarea style="width:340;font-family:Lucida Console;" rows=10 name="frepl">__destruct
__construct
__get
__set
__call
__callStatic
__isset
__unset
__sleep
__wakeup
__toString
__set_state
__clone</textarea>
<br>Functions with non-replaceable parameters:<br>
<textarea style="width:340;font-family:Lucida Console;" rows=10 name="ffrepl">set_error_handler
ob_gzhandler
ibase_set_event_handler
session_set_save_handler
set_exception_handler
xml_set_character_data_handler
xml_set_default_handler
xml_set_element_handler
xml_set_end_namespace_decl_handler
xml_set_external_entity_ref_handler
xml_set_notation_decl_handler
xml_set_processing_instruction_handler
xml_set_start_namespace_decl_handler
xml_set_unparsed_entity_decl_handler
xslt_set_error_handler
readline_callback_handler_install
runkit_sandbox_output_handler
sybase_set_message_handler</textarea>
</td>
</tr></table></body></html>
HERE;
  exit();
}


$replace_vars=isset($_POST['obvars']) ? 1 : 0;
$obf_strings=isset($_POST['obstrs']) ? 1 : 0;
$obf_funcs=isset($_POST['obfuncs']) ? 1 : 0;
$compress_file=isset($_POST['cmpr']) ? 1 : 0;

$vars_mode=isset($_POST['vtype']) ? $_POST['vtype'] : 0;
if($vars_mode!=="1" && $vars_mode!=="0")
  $vars_mode=0;

$string_mode=isset($_POST['stype']) ? $_POST['stype'] : 0;
if($string_mode!=="1" && $string_mode!=="0")
  $string_mode=0;

$func_mode=isset($_POST['ftype']) ? $_POST['ftype'] : 0;
if($func_mode!=="1" && $func_mode!=="0")
  $func_mode=0;

$f=isset($_POST['src']) ? $_POST['src'] : '';

if(ini_get('magic_quotes_gpc')==1)
  $f=stripslashes($f);

if(!$f)
  errpr("Enter php-file code");

$obfuscated=get_obf_code($f,$replace_vars,$vars_mode,$obf_strings,$string_mode,$obf_funcs,$func_mode,$sfuncname);


if($compress_file) $obfuscated=compress_php_src($obfuscated);

$obfuscated=htmlspecialchars($obfuscated);

print <<<HERE
<html><head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>PHP Obfuscator by DX 1.0</title>
</head>
<body>
<center><h3>Obfuskated code</h3></center><hr>
<textarea style="width:99%;font-family:Lucida Console;" rows=35>
$obfuscated
</textarea>
&lt;br&gt;&lt;a href="#" onclick="java script:history.go(-1)">Again</a>;/body&gt;&lt;/html&gt;
HERE;
exit();



function errpr($txt)
{
print &lt;&lt;&lt;HERE
&lt;html&gt;&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8"&gt;
&lt;title&gt;PHP Obfuscator by DX 1.0&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h3&gt;$txt&lt;/h3&gt;&lt;hr&gt;
&lt;a href="#" onclick="java script:history.go(-1)">Back</a>;/body&gt;&lt;/html&gt;
HERE;
exit();
}



function compress_php_src($src)
{
  static $IW=array();

  $tokens=@token_get_all($src);

  $new="";
  $c=sizeof($tokens);
  $iw=false;
  $ih=false;
  $ls="";
  $ot=null;
  for($i=0;$i&lt;$c;$i++)
  {
	$token=$tokens[$i];
	  if(is_array($token))
	  {
		list($tn,$ts)=$token;
		$tname=token_name($tn);
		if($tn==T_INLINE_HTML)
		{
		  $new.=$ts;
		  $iw=false;
		}
		else
		{
		  if($tn==T_OPEN_TAG)
		  {
			if(strpos($ts," ") || strpos($ts,"\n") || strpos($ts,"\t") || strpos($ts,"\r"))
			{
			  $ts=rtrim($ts);
			}

			$ts.=" ";
			$new.=$ts;
			$ot=T_OPEN_TAG;
			$iw = true;
		  }
		  elseif($tn==T_OPEN_TAG_WITH_ECHO)
		  {
			$new.=$ts;
			$ot=T_OPEN_TAG_WITH_ECHO;
			$iw=true;
		  }
		  elseif($tn==T_CLOSE_TAG)
		  {
			if($ot==T_OPEN_TAG_WITH_ECHO)
			{
			  $new=rtrim($new,"; ");
			}
			else
			{
			  $ts=" ".$ts;
			}

			$new.=$ts;
			$ot=null;
			$iw=false;
		  }
		  elseif(in_array($tn,$IW))
		  {
			$new.=$ts;
			$iw=true;
		  }
		  elseif($tn==T_CONSTANT_ENCAPSED_STRING || $tn==T_ENCAPSED_AND_WHITESPACE)
		  {
			if($ts[0]=='"')
			{
			  $ts=addcslashes($ts,"\n\t\r");
			}

			$new.=$ts;
			$iw=true;
		  }
		  elseif($tn==T_WHITESPACE)
		  {
			$nt=@$tokens[$i+1];
			if(!$iw &amp;&amp; (!is_string($nt) || $nt=='$') &amp;&amp; !in_array($nt[0],$IW))
			{
			  $new.=" ";
			}

			$iw = false;
		  }
		  elseif($tn==T_START_HEREDOC)
		  {
			$new.="&lt;&lt;&lt;S\n";
			$iw=false;
			$ih=true;
		  }
		  elseif($tn==T_END_HEREDOC)
		  {
			$new.="S;\n";
			$iw=true;
			$ih=false;

			for($j=$i+1;$j&lt;$c;$j++)
			{
			  if(is_string($tokens[$j]) &amp;&amp; $tokens[$j]==";")
			  {
				$i=$j;
				break;
			  }
			  else if($tokens[$j][0]==T_CLOSE_TAG)
			  {
				break;
			  }
			}
		  }
		  elseif($tn==T_COMMENT || $tn==T_DOC_COMMENT || $tn==T_ML_COMMENT)
		  {
			$iw = true;
		  }
		  else
		  {
			$new.=$ts;
			$iw = false;
		  }
		}

		$ls = "";
	  }
	  else
	  {
		if(($token!=";" &amp;&amp; $token!=":") || $ls!=$token)
		{
		  $new.=$token;
		  $ls=$token;
		}

		$iw=true;

	  }
  }

  return $new;
}



function get_obf_code($src,$obfvars,$varmode,$obfstrings,$strmode,$obffuncs,$funcmode,$sfuncname='')
{
  global $no_change;
  global $allvars;
  global $no_change_funcs;
  global $no_str_repl;

  $tokens=@token_get_all($src);
  $c=sizeof($tokens);

  $allvars[0]=Array();
  $allvars[1]=Array();
  $currvar=0;

  $allfuncs[0]=Array();
  $allfuncs[1]=Array();
  $currfunc=0;

  $lastconstr='';

  $classsk=0;

  $prev=0;

  $currstr=0;

  $ot=0;

  $newcode="";
  $bfr='';
  $addcode1="";
  $sfname=$sfuncname ? $sfuncname : '_'.mt_rand();


  $isstr=0;
  $ineval=0;
  $isfunc=0;

  for($i=0;$i&lt;$c;$i++)
  {
	$token=$tokens[$i];

	if(is_array($token))
	{
	  list($tn,$ts)=$token;

	  if(($tn==T_OPEN_TAG || $tn==T_OPEN_TAG_WITH_ECHO) &amp;&amp; !$ot)
		$ot=1;

	  if($tn==T_CLOSE_TAG &amp;&amp; $ot)
		$ot=0;


	  if($ot)
	  {
		if($tn==T_VAR || $tn==T_PROTECTED || $tn==T_PUBLIC || $tn==T_PRIVATE || $tn==T_CONST)
		  $classsk=1;

		if($tn==T_EVAL)
		  $ineval=1;


		if($isstr==1 &amp;&amp; $tn==T_END_HEREDOC)
		  $isstr=0;


		if($tn==T_START_HEREDOC)
		  $isstr=1;


		if($ineval) {$newcode.=$ts;continue;}


		if($obfvars &amp;&amp; $tn==T_VARIABLE &amp;&amp; !in_array($ts,$no_change))
		{
		  if(!in_array($ts,$allvars[0]))
		  {
			$tmp=$ts;
			$allvars[0][$tmp]=$ts;
			$ts=$varmode==0 ? '$_'.$currvar : '$_'.md5($ts);
			$allvars[1][$tmp]=$ts;
			$currvar++;
		  }
		  else
		  {
			$ts=$allvars[1][$ts];
		  }
		}


		if($tn==T_STRING &amp;&amp; $prev==T_OBJECT_OPERATOR)
		{
		  $ttt=$i+1;
		  $wbfunc=0;
		  while(isset($tokens[$ttt]))
		  {
			$nxt=$tokens[$ttt];

			if($nxt=='(' &amp;&amp; !$isstr)
			{
			  $wbfunc=1;
			  break;
			}

			if(($nxt==';' || $nxt=='=' || $nxt==')'  || is_array($nxt)) &amp;&amp; !$isstr)
			{
			  break;
			}
			$ttt++;
		  }
		}


		if($obfvars &amp;&amp; !$wbfunc &amp;&amp; $tn==T_STRING &amp;&amp; $prev==T_OBJECT_OPERATOR &amp;&amp; !in_array('$'.$ts,$no_change))
		{
		  if(!in_array('$'.$ts,$allvars[0]))
		  {
			$tmp='$'.$ts;
			$allvars[0][$tmp]='$'.$ts;
			$ts=$varmode==0 ? '_'.$currvar : '_'.md5('$'.$ts);
			$allvars[1][$tmp]='$'.$ts;
			$currvar++;
		  }
		  else
		  {
			$ts=substr($allvars[1]['$'.$ts],1);
		  }
		}


		if($tn==T_FUNCTION)
		  $isfunc=1;

		$prev= $tn==T_WHITESPACE ? $prev : $tn;


		if($obffuncs &amp;&amp; $isfunc &amp;&amp; !$fname &amp;&amp; $tn==T_STRING &amp;&amp; strtolower($ts)!='true' &amp;&amp; strtolower($ts)!='false' &amp;&amp; !in_array($ts,$no_change_funcs))
		{
		  if(!in_array($ts,$allfuncs[0]))
		  {
			$tmp=$ts;
			$allfuncs[0][$tmp]=$ts;
			$ts=$funcmode==0 ? '__'.$currfunc : '__'.md5($ts);
			$allfuncs[1][$tmp]=$ts;
			$currfunc++;
		  }
		  else
		  {
			$ts=$allfuncs[1][$ts];
		  }
		}


		if($classsk==0 &amp;&amp; $obfstrings &amp;&amp; !in_array($lastconstr,$no_str_repl) &amp;&amp; $tn==T_CONSTANT_ENCAPSED_STRING &amp;&amp; !$isfunc)
		{
		  if($strmode==0)
		  {
			$addcode1.=$ts.',';
			$ts=$sfname.'('.$currstr.')';
			$currstr++;
		  }
		  else
		  {
			eval('$tmp='.$ts.';');
			$addcode1.="'".base64_encode($tmp)."',";
			$ts=$sfname.'('.$currstr.')';
			$currstr++;
		  }
		}
	  }

	  if($tn==T_STRING)
		$lastconstr=$ts;


	  if($tn==T_END_HEREDOC)
		$ts.="\n";

	  $newcode.=$ts;
	  $bfr=$tn;
	}
	else
	{
	  $newcode.=$token;

	  if($isfunc &amp;&amp; $ot)
	  {
		if($token==')')
		  $isfunc=0;
	  }

	  if($ot)
	  {
		if($isstr==2 &amp;&amp; $token=="'")
		{
		  $isstr=0;
		  continue;
		}

		if($token=="'")
		  $isstr=2;

		if($isstr==3 &amp;&amp; $token=='"')
		{
		  $isstr=0;
		  continue;
		}

		if($token=='"')
		  $isstr=3;

		if($classsk==1)
		{
		  if($token==';')
			$classsk=0;
		}

		if($ineval &amp;&amp; $token==';')
		  $ineval=0;

		if($lastconstr &amp;&amp; $token==';')
		  $lastconstr='';
	  }

	}
  }



  if($obfstrings)
  {
	$addcode1=substr($addcode1,0,strlen($addcode1)-1);

	if($strmode==0)
	  $addcode1="&lt;? function $sfname(\$i)".'{'."\$a=Array($addcode1);return \$a[\$i];".'}'." ?&gt;";
	else
	  $addcode1="&lt;? function $sfname(\$i)".'{'."\$a=Array($addcode1);return base64_decode(\$a[\$i]);".'}'." ?&gt;";
  }


  $newcode.=$addcode1;

  $tokens=token_get_all($newcode);
  $c=sizeof($tokens);
  $newcode="";

  $isstr=0;

  for($i=0;$i&lt;$c;$i++)
  {
	$token=$tokens[$i];

	if(is_array($token))
	{
	  list($tn,$ts)=$token;

	  if(($tn==T_OPEN_TAG || $tn==T_OPEN_TAG_WITH_ECHO) &amp;&amp; !$ot)
		$ot=1;

	  if($tn==T_CLOSE_TAG &amp;&amp; $ot)
		$ot=0;

	  if($ot)
	  {
		if($isstr==1 &amp;&amp; $tn==T_END_HEREDOC)
		  $isstr=0;

		if($tn==T_START_HEREDOC)
		  $isstr=1;


		if($obffuncs &amp;&amp; $isstr==0 &amp;&amp; $tn==T_STRING)
		{
		  if(isset($allfuncs[0][$ts]))
		  {
			$ts=$allfuncs[1][$ts];
		  }
		}
	  }

	  if($tn==T_END_HEREDOC)
		$ts.="\n";

	  $newcode.=$ts;
	}
	else
	{
	  $newcode.=$token;

	  if($ot)
	  {
		if($isstr==2 &amp;&amp; $token=="'")
		{
		  $isstr=0;
		  continue;
		}

		if($token=="'")
		  $isstr=2;

		if($isstr==3 &amp;&amp; $token=='"')
		{
		  $isstr=0;
		  continue;
		}

		if($token=='"')
		  $isstr=3;
	  }
	}
  }

  return $newcode;
}

print "Done!";
?&gt;

  • 0

Well in the case of using PHP with MySQL, there's no reason the whole process has to be complex at all. A set of db container functions or even a db class that are unique to different types of databases could be created that make connecting, executing queries, and fetching data simple. One thing I loved about what I had pieced together was that the following line would connect if needed, execute a query, and fetch the results:

$users = dbFetchAll('SELECT * FROM users ORDER BY username;');

I mention this because, again, it doesn't have to be complex, nor should it be.

  • 0

Most complicated code is not always the best code. In fact, the most cleverly written code is not always the best either if no one can be clever enough to figure it out. The best code is simple, straight to the point, and easy to understand.

This contest = fail.

  • Like 1
  • 0

Sure. It's a cleaned up version of the original and there are things I would change (such as the function names). It also uses mysql_pconnect for persistent connections. Included is even a method to automatically backup the database and prompt a download.

&lt;?php
global $DB_HOST, $DB_DB, $DB_USER, $DB_PASS, $DB_PORT;
$DB_HOST	= 'localhost';
$DB_DB		= 'database';
$DB_USER	= 'username';
$DB_PASS	= 'password';
$DB_PORT	= 3306;

function db_connect()
{
	global $DB_HOST, $DB_DB, $DB_USER, $DB_PASS;

	if(!function_exists('mysql_pconnect'))
		die('MySQL, a critical component for this site, is not accessible through PHP. Contact your system administrator or web host for more details.');

	$_SESSION['db'] = @mysql_pconnect($DB_HOST, $DB_USER, $DB_PASS);

	if(!$_SESSION['db'])
		die('Unable to establish a connection to the database. Contact your system administrator.');

	@mysql_select_db($DB_DB, $_SESSION['db']);
}

function db_backup()
{
	$filename = $_SERVER['HTTP_HOST'] . '_' . date('YmdHi') . '.sql.gz';
	$file = '/tmp/'.$filename;

	passthru("mysqldump --user=$DB_USER --password=$DB_PASS --host=$DB_HOST $DB_DB | gzip &gt; $file");

	$file_part = explode('/', $file);

	header('Content-Description: File Transfer');
	header('Content-Type: application/octet-stream');
	header('Content-Length: ' . (string)(filesize($file)));
	header('Content-Disposition: attachment; filename=' . $file_part[(count($file_part) - 1)]);

	readfile($file);
}

function db_escape($var)
{
	return @mysql_escape_string($var);
}

function db_write($q)
{
	$rs = db_query($q);
	return $rs ? 1 : 0;
}

function db_query($q)
{
	if(!isset($_SESSION['db']) || !$_SESSION['db'])
		db_connect();

	if(!@is_resource($_SESSION['db']))
		db_error('Not connected to a database. Cannot execute query.');

	if(isset($_SESSION['queries']))
		$_SESSION['queries'][] = $q;

	if(!$return = @mysql_query($q, $_SESSION['db']))
		db_error('Could not execute the following query&lt;br /&gt;' . "\n" . '&lt;pre id="query"&gt;' . $q . '&lt;/pre&gt;' . mysql_error($_SESSION['db']));

	return $return;
}

function db_fetch_all($q, $fetch = DB_ASSOC)
{
	$rs = db_query($q);

	switch($fetch)
	{
		case DB_ROW:
			$function = 'mysql_fetch_row';
			break;
		case DB_ARRAY:
			$function = 'mysql_fetch_array';
			break;
		case DB_ASSOC:
		default:
			$function = 'mysql_fetch_assoc';
			break;
	}

	$return = array();

	while($row = @$function($rs))
		$return[] = $row;

	return $return;
}

function db_fetch_one($q)
{
	$rs = db_query($q);
	$row = @mysql_fetch_assoc($rs);

	return count($row) ? $row : 0;
}

function db_count($q)
{
	$rs = db_query($q);
	$row = @mysql_fetch_row($rs);

	return count($row) ? $row[0] : 0;
}

function db_error($err)
{
	// included a file that would read $err inside of the site's content
	exit;
}
?&gt;

  • 0

Hi, I would like to post some of my codes.. This codes are from my site ^^

  Quote
function blogwrite($title, $author, $date, $content, $postnumber) {

echo "<center><div align=\"left\" style=\"width: 540\"><a href=\"index.php?p=comment&post=".$postnumberclass=\"title\" ><b class=\"title\">".$title."</b></center></a>";

echo "<div class='stamp'>Post: ".$postnumber;

echo " - ".$date;

echo " - Written by: ".$author."</div>";

echo "<br >       <p ><font color=\"white\">".$content."</font></p></div></center><br >";

echo "<div align='right'><a class='B' href=\"index.php?p=comment&post=".$postnumber><b>Comments(";

$sqldata = mysql_query("SELECT * FROM comment WHERE page=$postnumber") or die("Can't Retrieve Data");

$rows = mysql_num_rows($sqldata);

echo $rows.")</b></a></div></div>";

echo '<br ><center><div style="border-top: 2px double white;width: 500;"></div></center><br >';

}

The above code is a function.. It is the one that writes on the blog.. How it is order, where title will be positioned, and such...

  Quote
$sqldata = mysql_query("SELECT * FROM blogtable") or die("Can't Retrieve Data");

$rows = mysql_num_rows($sqldata);

$a = $rows;

if (isset($_GET['pages'])) {

$a = $a - (($_GET['pages'] - 1) * 10);

if ($a < 10) {

$b = 0;

} else {

$b = $a - 10;

}

while ($a != $b) {

$sqldata = mysql_query("SELECT * FROM blogtable WHERE postnumber=$a");

$data = mysql_fetch_array($sqldata);

blogwrite($data['title'], $data['author'], $data['date'], $data['content'], $data['postnumber']);

$a--;

}

} elseif ($a > 10) {

$b = $a - 10;

while ($a != $b) {

$sqldata = mysql_query("SELECT * FROM blogtable WHERE postnumber=$a");

$data = mysql_fetch_array($sqldata);

blogwrite($data['title'], $data['author'], $data['date'], $data['content'], $data['postnumber']);

$a--;

}

}

else {

while ($a != 0) {

$sqldata = mysql_query("SELECT * FROM blogtable WHERE postnumber=$a");

$data = mysql_fetch_array($sqldata);

blogwrite($data['title'], $data['author'], $data['date'], $data['content'], $data['postnumber']);

$a--;

}

}

$c = $rows;

$d = 0;

echo "<br ><b><font size=\"1\"><div><center>|</b>";

while ($c != 0) {

$d++;

if ($d == 1 and !isset($_GET['pages'])) {

echo "<b>".$d."| </b>";

} elseif ($d == $_GET['pages']) {

echo "<b>".$d."| </b>";

} else {

echo "<b><a href=\"index.php?pages=".$d>".$d."</a> | </b>";

}

if ($c < 10) {

$c = 0;

} else {

$c = $c - 10;

}

}

The code above organizes the blog entries from pages to pages ^^

See the result of this code in my site http://media6.site88.net

  • 0

This is a part of my Kubix cms.. its over 2 years old, havn't worked on it lately.

&lt;?PHP
////////////////////////////////////////////////////////
//		KUBIX CMS		//						 //
//	  Copyright (C)	  // KUBIX IS FREE SOFTWARE! //
//	  KUBIX PROJECT	  //	 DONT PAY FOR IT	 //
//   ALL RIGHTS RESERVED   //						 //
////////////////////////////////////////////////////////

// Include core files
include "Core/connect.php";
include "Core/functions.php";

// Connect
connect($server, $user, $password, $database);

// Get the options from the kbx_options table
$GetOpts = mysql_query("SELECT * FROM kbx_options");
$SiteName = mysql_result($GetOpts, 0, "SiteName");
$SiteURL = mysql_result($GetOpts, 0, "SiteURL");
$DefaultCat = mysql_result($GetOpts, 0, "DefaultCat");
$DefaultTheme = mysql_result($GetOpts, 0, "DefaultTheme");
$Announcement = mysql_result($GetOpts, 0, "Announcement");
$GuestMSG = mysql_result($GetOpts, 0, "GuestMSG");
$AdSection1 = mysql_result($GetOpts, 0, "AdSection1");
$AdSection2 = mysql_result($GetOpts, 0, "AdSection2");
$AdSection3 = mysql_result($GetOpts, 0, "AdSection3");
$AdSection4 = mysql_result($GetOpts, 0, "AdSection4");

// Get the links from the databse
$GetLinks = mysql_query("SELECT * FROM kbx_links");
$num = mysql_num_rows($GetLinks);

$Links = "";

for($i = 0; $i &lt; $num; $i++)
{
	$LinkTitle = mysql_result($GetLinks, $i, "Title");
	$LinkURL = mysql_result($GetLinks, $i, "URL");

	$Links .= '&lt;a href="' . $LinkURL . '"&gt;' . $LinkTitle . '&lt;/a&gt;&lt;br /&gt;';
}

// Get the categories from the database
$GetCats = mysql_query("SELECT * FROM kbx_cats WHERE Type = 'news'");
$num = mysql_num_rows($GetCats);

$Cats = "";

for($i = 0; $i &lt; $num; $i++)
{
	$CatID = mysql_result($GetCats, $i, "ID");
	$CatName = mysql_result($GetCats, $i, "Name");

	$Cats .= '&lt;a href="index.php?cat=' . $CatID . '"&gt;' . $CatName . '&lt;/a&gt;&lt;br /&gt;';
}

// Get the menu from the databse
$GetMenu = mysql_query("SELECT * FROM kbx_menu");
$num = mysql_num_rows($GetMenu);

$Menu = "";

for($i = 0; $i &lt; $num; $i++)
{
	$MenuTitle = mysql_result($GetMenu, $i, "Title");
	$MenuLinks = mysql_result($GetMenu, $i, "Links");

	$MenuLinks = str_replace('{MENULINKS}', $Links, $MenuLinks);
	$MenuLinks = str_replace('{MENUCATS}', $Cats, $MenuLinks);

	$Menu .= '&lt;div class="menutitle"&gt;' . $MenuTitle . '&lt;/div&gt;';
	$Menu .= '&lt;div class="menu"&gt;' . $MenuLinks . '&lt;/div&gt;';
}

// Handel Logout
if(isset($_GET['act']) &amp;&amp; $_GET['act'] == "Logout")
	header("Location:Core/LoginAuth.php?act=Logout");

// Get user information
if(isLoggedIn())
{
	$uID = $_COOKIE['member_id'];	
	$GetUserInfo = mysql_query("SELECT * FROM kbx_members WHERE id = $uID");
	$uName = mysql_result($GetUserInfo, 0, 'Name');
	$uEmail = mysql_result($GetUserInfo, 0, 'Email');
	$uMSN = mysql_result($GetUserInfo, 0, 'MSN');
	$uYahoo = mysql_result($GetUserInfo, 0, 'Yahoo');
	$uAIM = mysql_result($GetUserInfo, 0, 'AIM');
	$uOtherIM = mysql_result($GetUserInfo, 0, 'OtherIM');
	$uJoined = mysql_result($GetUserInfo, 0, 'Joined');
	$uHomePage = mysql_result($GetUserInfo, 0, 'HomePage');
	$uLevel = mysql_result($GetUserInfo, 0, 'Level');

	if($uHomePage != 0 || $uHomePage != NULL)
		$DefaultCat = $uHomePage;

	// Prepare user level
	$getlev = mysql_query("SELECT * FROM kbx_levels WHERE ID = $uLevel");

	$userLevel = mysql_result($getlev, 0, "Title");
	$uViewSite = mysql_result($getlev, 0, "ViewSite");
	$uComment = mysql_result($getlev, 0, "Comment");
	$uAddNews = mysql_result($getlev, 0, "AddNews");
	$uEditNews = mysql_result($getlev, 0, "EditNews");
	$uEditOwnProfile = mysql_result($getlev, 0, "EditOwnProfile");
	$uEditOtherProfile = mysql_result($getlev, 0, "EditOtherProfile");
}

// Prepare guest message
if(!isLoggedIn())
{
	if($GuestMSG != "")
	{
		$WelcomeGuest = '&lt;div id="GuestMSG"&gt;' . $GuestMSG . '&lt;/div&gt;' . "\n";
	}
	else
		$WelcomeGuest = '';
}
else
	$WelcomeGuest = '';

// Prepare announcement
if($Announcement != "")
{
	if(isAdm())
		$AnnouncementAdm = '&lt;div class="fright"&gt;[&lt;a href="admin.php?mod=opts">Edit</a>;/div&gt;';
	else
		$AnnouncementAdm = '';

	$Announcement = '&lt;div class="alert"&gt;' . $AnnouncementAdm . $Announcement . '&lt;/div&gt;' . "\n";
}
else
	$Announcement = '';

// Prepare userbar
if(isLoggedIn())
{
	if(isMod())
		$UserBarLinks = '&lt;a href="cp/"&gt;Control Panel&lt;/a&gt; · ';
	else
		$UserBarLinks = '';

	$UserBar = '&lt;div class="fright"&gt;' . $UserBarLinks . '&lt;a href="index.php?act=Logout">Logout</a></div>Welcome;a href="profile.php">$uName . '&lt;/a&gt;';
}
else
	$UserBar = 'Welcome: Guest (&lt;a href="login.php">Login</a>lt;a href="register.php">Register</a>
include "Themes/$DefaultTheme/header.php";
?&gt;

  • 0
  Mathachew said:
Well in the case of using PHP with MySQL, there's no reason the whole process has to be complex at all. A set of db container functions or even a db class that are unique to different types of databases could be created that make connecting, executing queries, and fetching data simple. One thing I loved about what I had pieced together was that the following line would connect if needed, execute a query, and fetch the results:

$users = dbFetchAll('SELECT * FROM users ORDER BY username;');

I mention this because, again, it doesn't have to be complex, nor should it be.

Exactly... sometimes the complexity of the code and the skill level of the programmer is found in the simplicity of their code.

Amatuers always tend to find the most difficult way of doing things that are usually very simple. Why write 50 lines of code for something that can be done with 10?

  • 0

howdy.

Firstly hello.

Saw this contest was closed, but though a late entrant may be allowed.

The following is not my code, but is the most complex code I have seen. I've tried to decipher it line by line a few times but never had any success.

I stumbled across it whilst looking at latent semantic indexing. Something used by search engines.

Basically, you take a term/document matrix and calculate the singular value decomposition. You can then use the matrices calculated to identify similar documents -e.g. google's similar pages link.

This php version is only useful for small matrices, so wasn't useful for what I needed it for. Anyhow it works, is complex and fits on two pages if you remove comments and change the font size to about 4 :).

hope you like

&lt;?php
/**
* @package JAMA
*
* For an m-by-n matrix A with m &gt;= n, the singular value decomposition is
* an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and
* an n-by-n orthogonal matrix V so that A = U*S*V'.
*
* The singular values, sigma[$k] = S[$k][$k], are ordered so that
* sigma[0] &gt;= sigma[1] &gt;= ... &gt;= sigma[n-1].
*
* The singular value decompostion always exists, so the constructor will
* never fail.  The matrix condition number and the effective numerical
* rank can be computed from this decomposition.
*
* @author  Paul Meagher
* @license PHP v3.0
* @version 1.1
*/
class SingularValueDecomposition  {

  /**
  * Internal storage of U.
  * @var array
  */
  var $U = array();

  /**
  * Internal storage of V.
  * @var array
  */
  var $V = array();

  /**
  * Internal storage of singular values.
  * @var array
  */
  var $s = array();

  /**
  * Row dimension.
  * @var int
  */
  var $m;

  /**
  * Column dimension.
  * @var int
  */
  var $n;

  /**
  * Construct the singular value decomposition
  *
  * Derived from LINPACK code.
  *
  * @param $A Rectangular matrix
  * @return Structure to access U, S and V.
  */
  function SingularValueDecomposition ($Arg) {

	// Initialize.

	$A = $Arg-&gt;getArrayCopy();
	$this-&gt;m = $Arg-&gt;getRowDimension();
	$this-&gt;n = $Arg-&gt;getColumnDimension();
	$nu	  = min($this-&gt;m, $this-&gt;n);
	$e	   = array();
	$work	= array();
	$wantu   = true;
	$wantv   = true;	  
	$nct = min($this-&gt;m - 1, $this-&gt;n);
	$nrt = max(0, min($this-&gt;n - 2, $this-&gt;m));   

	// Reduce A to bidiagonal form, storing the diagonal elements
	// in s and the super-diagonal elements in e.

	for ($k = 0; $k &lt; max($nct,$nrt); $k++) {

	  if ($k &lt; $nct) {
		// Compute the transformation for the k-th column and
		// place the k-th diagonal in s[$k].
		// Compute 2-norm of k-th column without under/overflow.
		$this-&gt;s[$k] = 0;
		for ($i = $k; $i &lt; $this-&gt;m; $i++)
		  $this-&gt;s[$k] = hypo($this-&gt;s[$k], $A[$i][$k]);
		if ($this-&gt;s[$k] != 0.0) {
		  if ($A[$k][$k] &lt; 0.0)
			$this-&gt;s[$k] = -$this-&gt;s[$k];
		  for ($i = $k; $i &lt; $this-&gt;m; $i++)
			$A[$i][$k] /= $this-&gt;s[$k];
		  $A[$k][$k] += 1.0;
		}
		$this-&gt;s[$k] = -$this-&gt;s[$k];
	  }		   

	  for ($j = $k + 1; $j &lt; $this-&gt;n; $j++) {
		if (($k &lt; $nct) &amp; ($this-&gt;s[$k] != 0.0)) {
		  // Apply the transformation.
		  $t = 0;
		  for ($i = $k; $i &lt; $this-&gt;m; $i++)
			$t += $A[$i][$k] * $A[$i][$j];
		  $t = -$t / $A[$k][$k];
		  for ($i = $k; $i &lt; $this-&gt;m; $i++)
			$A[$i][$j] += $t * $A[$i][$k];
		  // Place the k-th row of A into e for the
		  // subsequent calculation of the row transformation.
		  $e[$j] = $A[$k][$j];
		}
	  }

	  if ($wantu AND ($k &lt; $nct)) {
		// Place the transformation in U for subsequent back
		// multiplication.
		for ($i = $k; $i &lt; $this-&gt;m; $i++)
		  $this-&gt;U[$i][$k] = $A[$i][$k];
	  }

	  if ($k &lt; $nrt) {
		// Compute the k-th row transformation and place the
		// k-th super-diagonal in e[$k].
		// Compute 2-norm without under/overflow.
		$e[$k] = 0;
		for ($i = $k + 1; $i &lt; $this-&gt;n; $i++)
		  $e[$k] = hypo($e[$k], $e[$i]);
		if ($e[$k] != 0.0) {
		  if ($e[$k+1] &lt; 0.0)
			$e[$k] = -$e[$k];
		  for ($i = $k + 1; $i &lt; $this-&gt;n; $i++)
			$e[$i] /= $e[$k];
		  $e[$k+1] += 1.0;
		}
		$e[$k] = -$e[$k];
		if (($k+1 &lt; $this-&gt;m) AND ($e[$k] != 0.0)) {
		  // Apply the transformation.
		  for ($i = $k+1; $i &lt; $this-&gt;m; $i++)
			$work[$i] = 0.0;
		  for ($j = $k+1; $j &lt; $this-&gt;n; $j++)
			for ($i = $k+1; $i &lt; $this-&gt;m; $i++)
			  $work[$i] += $e[$j] * $A[$i][$j];
		  for ($j = $k + 1; $j &lt; $this-&gt;n; $j++) {
			$t = -$e[$j] / $e[$k+1];
			for ($i = $k + 1; $i &lt; $this-&gt;m; $i++)
			  $A[$i][$j] += $t * $work[$i];
		  }
		}
		if ($wantv) {
		  // Place the transformation in V for subsequent
		  // back multiplication.
		  for ($i = $k + 1; $i &lt; $this-&gt;n; $i++)
			$this-&gt;V[$i][$k] = $e[$i];
		}		
	  }
	} 

	// Set up the final bidiagonal matrix or order p.
	$p = min($this-&gt;n, $this-&gt;m + 1);
	if ($nct &lt; $this-&gt;n)
	  $this-&gt;s[$nct] = $A[$nct][$nct];
	if ($this-&gt;m &lt; $p)
	  $this-&gt;s[$p-1] = 0.0;
	if ($nrt + 1 &lt; $p)
	  $e[$nrt] = $A[$nrt][$p-1];
	$e[$p-1] = 0.0;
	// If required, generate U.
	if ($wantu) {
	  for ($j = $nct; $j &lt; $nu; $j++) {
		for ($i = 0; $i &lt; $this-&gt;m; $i++)
		  $this-&gt;U[$i][$j] = 0.0;
		$this-&gt;U[$j][$j] = 1.0;
	  }
	  for ($k = $nct - 1; $k &gt;= 0; $k--) {
		if ($this-&gt;s[$k] != 0.0) {
		  for ($j = $k + 1; $j &lt; $nu; $j++) {
			$t = 0;
			for ($i = $k; $i &lt; $this-&gt;m; $i++)
			  $t += $this-&gt;U[$i][$k] * $this-&gt;U[$i][$j];
			$t = -$t / $this-&gt;U[$k][$k];
			for ($i = $k; $i &lt; $this-&gt;m; $i++)
			  $this-&gt;U[$i][$j] += $t * $this-&gt;U[$i][$k];
		  }
		  for ($i = $k; $i &lt; $this-&gt;m; $i++ )
			$this-&gt;U[$i][$k] = -$this-&gt;U[$i][$k];
		  $this-&gt;U[$k][$k] = 1.0 + $this-&gt;U[$k][$k];
		  for ($i = 0; $i &lt; $k - 1; $i++)
			 $this-&gt;U[$i][$k] = 0.0;
		 } else {
		   for ($i = 0; $i &lt; $this-&gt;m; $i++)
			 $this-&gt;U[$i][$k] = 0.0;
		   $this-&gt;U[$k][$k] = 1.0;
		 }
	  }
	}

	// If required, generate V.
	if ($wantv) {
	  for ($k = $this-&gt;n - 1; $k &gt;= 0; $k--) {
		if (($k &lt; $nrt) AND ($e[$k] != 0.0)) {
		  for ($j = $k + 1; $j &lt; $nu; $j++) {
			$t = 0;
			for ($i = $k + 1; $i &lt; $this-&gt;n; $i++)
			  $t += $this-&gt;V[$i][$k]* $this-&gt;V[$i][$j];
			$t = -$t / $this-&gt;V[$k+1][$k];
			for ($i = $k + 1; $i &lt; $this-&gt;n; $i++)
			  $this-&gt;V[$i][$j] += $t * $this-&gt;V[$i][$k];
		  }
		}
		for ($i = 0; $i &lt; $this-&gt;n; $i++)
		   $this-&gt;V[$i][$k] = 0.0;
		$this-&gt;V[$k][$k] = 1.0;
	  }
	}

	// Main iteration loop for the singular values.
	$pp   = $p - 1;
	$iter = 0;
	$eps  = pow(2.0, -52.0);
	while ($p &gt; 0) {	  

	  // Here is where a test for too many iterations would go.
	  // This section of the program inspects for negligible
	  // elements in the s and e arrays.  On completion the
	  // variables kase and k are set as follows:
	  // kase = 1  if s(p) and e[k-1] are negligible and k&lt;p
	  // kase = 2  if s(k) is negligible and k&lt;p
	  // kase = 3  if e[k-1] is negligible, k&lt;p, and
	  //		   s(k), ..., s(p) are not negligible (qr step).
	  // kase = 4  if e(p-1) is negligible (convergence).

	  for ($k = $p - 2; $k &gt;= -1; $k--) {
		if ($k == -1)
		  break;
		if (abs($e[$k]) &lt;= $eps * (abs($this-&gt;s[$k]) + abs($this-&gt;s[$k+1]))) {
		  $e[$k] = 0.0;
		  break;
		}
	  }
	  if ($k == $p - 2)
		$kase = 4;
	  else {
		for ($ks = $p - 1; $ks &gt;= $k; $ks--) {
		  if ($ks == $k)
			break;
		  $t = ($ks != $p ? abs($e[$ks]) : 0.) + ($ks != $k + 1 ? abs($e[$ks-1]) : 0.);
		  if (abs($this-&gt;s[$ks]) &lt;= $eps * $t)  {
			$this-&gt;s[$ks] = 0.0;
			break;
		  }
		}
		if ($ks == $k)
		   $kase = 3;
		else if ($ks == $p-1)
		   $kase = 1;
		else {
		   $kase = 2;
		   $k = $ks;
		}
	  }
	  $k++;

	  // Perform the task indicated by kase.
	  switch ($kase) {
		 // Deflate negligible s(p).
		 case 1:
		   $f = $e[$p-2];
		   $e[$p-2] = 0.0;
		   for ($j = $p - 2; $j &gt;= $k; $j--) {
			 $t  = hypo($this-&gt;s[$j],$f);
			 $cs = $this-&gt;s[$j] / $t;
			 $sn = $f / $t;
			 $this-&gt;s[$j] = $t;
			 if ($j != $k) {
			   $f = -$sn * $e[$j-1];
			   $e[$j-1] = $cs * $e[$j-1];
			 }
			 if ($wantv) {
			   for ($i = 0; $i &lt; $this-&gt;n; $i++) {
				 $t = $cs * $this-&gt;V[$i][$j] + $sn * $this-&gt;V[$i][$p-1];
				 $this-&gt;V[$i][$p-1] = -$sn * $this-&gt;V[$i][$j] + $cs * $this-&gt;V[$i][$p-1];
				 $this-&gt;V[$i][$j] = $t;
			   }
			 }
		   }
		   break;
		 // Split at negligible s(k).
		 case 2:
		   $f = $e[$k-1];
		   $e[$k-1] = 0.0;
		   for ($j = $k; $j &lt; $p; $j++) {
			 $t = hypo($this-&gt;s[$j], $f);
			 $cs = $this-&gt;s[$j] / $t;
			 $sn = $f / $t;
			 $this-&gt;s[$j] = $t;
			 $f = -$sn * $e[$j];
			 $e[$j] = $cs * $e[$j];
			 if ($wantu) {
			   for ($i = 0; $i &lt; $this-&gt;m; $i++) {
				 $t = $cs * $this-&gt;U[$i][$j] + $sn * $this-&gt;U[$i][$k-1];
				 $this-&gt;U[$i][$k-1] = -$sn * $this-&gt;U[$i][$j] + $cs * $this-&gt;U[$i][$k-1];
				 $this-&gt;U[$i][$j] = $t;
			   }
			 }
		   }
		   break;		   
		 // Perform one qr step.
		 case 3:				  
		   // Calculate the shift.						  
		   $scale = max(max(max(max(
					abs($this-&gt;s[$p-1]),abs($this-&gt;s[$p-2])),abs($e[$p-2])),
					abs($this-&gt;s[$k])), abs($e[$k]));
		   $sp   = $this-&gt;s[$p-1] / $scale;
		   $spm1 = $this-&gt;s[$p-2] / $scale;
		   $epm1 = $e[$p-2] / $scale;
		   $sk   = $this-&gt;s[$k] / $scale;
		   $ek   = $e[$k] / $scale;
		   $b	= (($spm1 + $sp) * ($spm1 - $sp) + $epm1 * $epm1) / 2.0;
		   $c	= ($sp * $epm1) * ($sp * $epm1);
		   $shift = 0.0;
		   if (($b != 0.0) || ($c != 0.0)) {
			 $shift = sqrt($b * $b + $c);
			 if ($b &lt; 0.0)
			   $shift = -$shift;
			 $shift = $c / ($b + $shift);
		   }
		   $f = ($sk + $sp) * ($sk - $sp) + $shift;
		   $g = $sk * $ek;  
		   // Chase zeros.  
		   for ($j = $k; $j &lt; $p-1; $j++) {
			 $t  = hypo($f,$g);
			 $cs = $f/$t;
			 $sn = $g/$t;
			 if ($j != $k)
			   $e[$j-1] = $t;
			 $f = $cs * $this-&gt;s[$j] + $sn * $e[$j];
			 $e[$j] = $cs * $e[$j] - $sn * $this-&gt;s[$j];
			 $g = $sn * $this-&gt;s[$j+1];
			 $this-&gt;s[$j+1] = $cs * $this-&gt;s[$j+1];
			 if ($wantv) {
			   for ($i = 0; $i &lt; $this-&gt;n; $i++) {
				 $t = $cs * $this-&gt;V[$i][$j] + $sn * $this-&gt;V[$i][$j+1];
				 $this-&gt;V[$i][$j+1] = -$sn * $this-&gt;V[$i][$j] + $cs * $this-&gt;V[$i][$j+1];
				 $this-&gt;V[$i][$j] = $t;
			   }
			 }																	  
			 $t = hypo($f,$g);
			 $cs = $f/$t;
			 $sn = $g/$t;
			 $this-&gt;s[$j] = $t;
			 $f = $cs * $e[$j] + $sn * $this-&gt;s[$j+1];
			 $this-&gt;s[$j+1] = -$sn * $e[$j] + $cs * $this-&gt;s[$j+1];
			 $g = $sn * $e[$j+1];
			 $e[$j+1] = $cs * $e[$j+1];
			 if ($wantu &amp;&amp; ($j &lt; $this-&gt;m - 1)) {
			   for ($i = 0; $i &lt; $this-&gt;m; $i++) {
				 $t = $cs * $this-&gt;U[$i][$j] + $sn * $this-&gt;U[$i][$j+1];
				 $this-&gt;U[$i][$j+1] = -$sn * $this-&gt;U[$i][$j] + $cs * $this-&gt;U[$i][$j+1];
				 $this-&gt;U[$i][$j] = $t;
			   }
			 }				
		   }
		   $e[$p-2] = $f;
		   $iter = $iter + 1;
		   break;
		 // Convergence.
		 case 4:
		   // Make the singular values positive.
		   if ($this-&gt;s[$k] &lt;= 0.0) {
			 $this-&gt;s[$k] = ($this-&gt;s[$k] &lt; 0.0 ? -$this-&gt;s[$k] : 0.0);
			 if ($wantv) {
			   for ($i = 0; $i &lt;= $pp; $i++)
				 $this-&gt;V[$i][$k] = -$this-&gt;V[$i][$k];
			 }
		   }
		   // Order the singular values.  
		   while ($k &lt; $pp) {
			if ($this-&gt;s[$k] &gt;= $this-&gt;s[$k+1])
			  break;
			$t = $this-&gt;s[$k];
			$this-&gt;s[$k] = $this-&gt;s[$k+1];
			$this-&gt;s[$k+1] = $t;
			if ($wantv AND ($k &lt; $this-&gt;n - 1)) {
			  for ($i = 0; $i &lt; $this-&gt;n; $i++) {
				$t = $this-&gt;V[$i][$k+1];
				$this-&gt;V[$i][$k+1] = $this-&gt;V[$i][$k];
				$this-&gt;V[$i][$k] = $t;
			  }
			}
			if ($wantu AND ($k &lt; $this-&gt;m-1)) {
			  for ($i = 0; $i &lt; $this-&gt;m; $i++) {
				$t = $this-&gt;U[$i][$k+1];
				$this-&gt;U[$i][$k+1] = $this-&gt;U[$i][$k];
				$this-&gt;U[$i][$k] = $t;
			  }
			}
			$k++;
		   }
		   $iter = 0;
		   $p--;
		   break;								   
	  } // end switch	  
	} // end while

	/*
	echo "&lt;p&gt;Output A&lt;/p&gt;";   
	$A = new Matrix($A);		
	$A-&gt;toHTML();

	echo "&lt;p&gt;Matrix U&lt;/p&gt;";	
	echo "&lt;pre&gt;";
	print_r($this-&gt;U);		
	echo "&lt;/pre&gt;";

	echo "&lt;p&gt;Matrix V&lt;/p&gt;";	
	echo "&lt;pre&gt;";
	print_r($this-&gt;V);		
	echo "&lt;/pre&gt;";	

	echo "&lt;p&gt;Vector S&lt;/p&gt;";	
	echo "&lt;pre&gt;";
	print_r($this-&gt;s);		
	echo "&lt;/pre&gt;";	
	exit;
	*/

  } // end constructor

  /**
  * Return the left singular vectors
  * @access public
  * @return U
  */
  function getU() {
	return new Matrix($this-&gt;U, $this-&gt;m, min($this-&gt;m + 1, $this-&gt;n));
  }

  /**
  * Return the right singular vectors
  * @access public   
  * @return V
  */
  function getV() {
	return new Matrix($this-&gt;V);
  }

  /**
  * Return the one-dimensional array of singular values
  * @access public   
  * @return diagonal of S.
  */
  function getSingularValues() {
	return $this-&gt;s;
  }

  /**
  * Return the diagonal matrix of singular values
  * @access public   
  * @return S
  */
  function getS() {
	for ($i = 0; $i &lt; $this-&gt;n; $i++) {
	  for ($j = 0; $j &lt; $this-&gt;n; $j++)
		$S[$i][$j] = 0.0;
	  $S[$i][$i] = $this-&gt;s[$i];
	}
	return new Matrix($S);
  }

  /**
  * Two norm
  * @access public   
  * @return max(S)
  */
  function norm2() {
	return $this-&gt;s[0];
  }

  /**
  * Two norm condition number
  * @access public   
  * @return max(S)/min(S)
  */
  function cond() {
	return $this-&gt;s[0] / $this-&gt;s[min($this-&gt;m, $this-&gt;n) - 1];
  }

  /**
  * Effective numerical matrix rank
  * @access public   
  * @return Number of nonnegligible singular values.
  */
  function rank() {
	$eps = pow(2.0, -52.0);
	$tol = max($this-&gt;m, $this-&gt;n) * $this-&gt;s[0] * $eps;
	$r = 0;
	for ($i = 0; $i &lt; count($this-&gt;s); $i++) {
	  if ($this-&gt;s[$i] &gt; $tol)
		$r++;
	}
	return $r;
  }
}
?&gt;

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • There's absolutely nothing in the WINE license preventing this. Regardless if that sentiment is held by the developers of WINE, it likely doesn't concern the people making Proton nor does it prevent them from adding the support.
    • Multiple competing launchers are unironically a gem on PC gaming—I'm not sure why people don't get that yet. Why replicate Apple's horrible control here? Multiple launchers = multiple stores → lower prices for multi-launcher games Every other con seems minute and irrelevant to a vibrant marketplace where you actually save money. The only real complaints I hear are multiple launchers idle as background tasks + people don't like opening multiple apps. For #1, maybe this OS-based launcher should do shutdown idle launchers like GOG. For #2, virtually all launchers let you create shortcuts. Voila, problem solved.
    • Xbox June Update brings unsynced save management, publisher browsing, and more by Pulasthi Ariyasinghe June has been a busy month for Microsoft, bringing major software upgrades across its product stack. It even announced new hardware for its Xbox lineup, finally entering the handheld gaming space. The company's roundup for this month's new features has now been published, and it's touting a great deal of changes. To start off on the PC side, the Xbox app on the platform now has a section to browse by publishers. The company says that this will let players easily discover more games made by their favorite developers and franchises. Copilot for Gaming also landed in beta form recently, letting users ask AI for help when a game gets too difficult. It's only available for iOS and Android for now, with ROG Xbox Ally support coming later this year. Another feature that will hit the Xbox Ally is the new universal launcher feature for the Xbox app on PC. Microsoft just kicked off Xbox Insider testing for this functionality earlier today. Get all the details here. Over on consoles, the ability to hide system apps, pin favorites to the list, and reduce the number of tiles displayed are now available. Game Hubs also arrived as a fresh feature to easily display relevant information when selecting a game to play, offering data on player stats, achievements, friends currently playing, recent captures, available add-ons, events, and more. Double-tapping the play button will quick-launch the game instead. On both Xbox consoles and in the cloud, a new progress bar will now appear when a save has been left behind on a device in an offline state. "A new progress bar, device names, timestamps, and additional details are now displayed when you have previous game saves on another device in an unsynced state," says the company. Microsoft has also added mouse and keyboard controls as well as touch controls for more cloud games this month. These join the fresh additions that have landed on the 'Stream your own game' collection and the Retro Classics app. Check out the full lists on the announcement page here. On top of all this, Microsoft has also announced that Xbox will be at Gamescom this year. While no details have been announced yet, more announcements from Xbox Game Studios may happen at the major gaming event.
  • Recent Achievements

    • Dedicated
      Camlann earned a badge
      Dedicated
    • Week One Done
      fredss earned a badge
      Week One Done
    • Dedicated
      fabioc earned a badge
      Dedicated
    • One Month Later
      GoForma earned a badge
      One Month Later
    • Week One Done
      GoForma earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      649
    2. 2
      Michael Scrip
      225
    3. 3
      ATLien_0
      220
    4. 4
      +FloatingFatMan
      144
    5. 5
      Xenon
      136
  • Tell a friend

    Love Neowin? Tell a friend!