<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>terrorhippiecrew - Weblog</title>
	<atom:link href="http://terrorhippiecrew.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://terrorhippiecrew.net</link>
	<description>IT und alles was mich sonst noch so interessiert</description>
	<lastBuildDate>Mon, 19 Jul 2010 09:37:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>XMLRPC Server und Client</title>
		<link>http://terrorhippiecrew.net/2010/07/xmlrpc-server-und-client/</link>
		<comments>http://terrorhippiecrew.net/2010/07/xmlrpc-server-und-client/#comments</comments>
		<pubDate>Mon, 19 Jul 2010 09:01:14 +0000</pubDate>
		<dc:creator>w13531</dc:creator>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://terrorhippiecrew.net/?p=676</guid>
		<description><![CDATA[Einen kleinen XMLRPC Client und Server. Mit der nächsten Framework Version offiziell verfügbar, inkl der angesprochenen ACL:) Zur Authentifizierung benutze ich den Authorization-Header. Damit können Webservices/APIs mit individuellen Berechtigungen realisiert werden zB. Über eine ACL. Anwendungen lassen sich dadurch auch besser in Backend/Frontend unterteilen und können auch auf externe Resourcen ausgelagert werden oder eingebunden werden(erhöhte [...]]]></description>
			<content:encoded><![CDATA[<p>Einen kleinen XMLRPC Client und Server.<br />
Mit der nächsten Framework Version offiziell verfügbar, inkl der angesprochenen ACL:)<br />
Zur Authentifizierung benutze ich den Authorization-Header. Damit können Webservices/APIs mit individuellen Berechtigungen realisiert werden zB. Über eine ACL. Anwendungen lassen sich dadurch auch besser in Backend/Frontend unterteilen und können auch auf externe Resourcen ausgelagert werden oder eingebunden werden(erhöhte Skalierbarkeit).<br />
Die Objekte die dem Server via setObject() übergeben werden, müssen folgende Konventionen befolgen:<br />
* alle indizierbaren Methoden müssen public sein.<br />
* Methoden müssen folgenden parameter haben: function test($method_name, $params, $user_data) {}<br />
Damit bietet diese Lösung eine Authorisierung und ein einfaches RPC Verfahren an. Das ganze sollte über eine SSL Verbindung laufen, da Passwörter übertragen werden(bzw der HASH). Durch Session-Passwörter könnte auch eine unverschlüsselte Verbindung genutzt werden.<br />
Über diesen kleinen HTACCESS kommt man auch wenn PHP im FastCGI Modus ist an die authorization ran, dabei legt man den Auth-Header auf eine von PHP auslesbare Variable um:</p>
<pre><code>&lt;IfModule mod_rewrite.c&gt;
RewriteEngine On
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
&lt;/IfModule&gt;
</code></pre>
<p>jetzt muss man nur noch im PHP die Variablen auslesen und umschreiben: </p>
<pre><code>//HTTP Auth Credentials
if ((!$_SERVER['PHP_AUTH_USER'] || !$_SERVER['PHP_AUTH_PW'])) {
    list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER["REMOTE_USER"], 6)));
}
</code></pre>
<p>XMLRPC Core Class:</p>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class LIB_Class_XMLRPC {

}
</code></pre>
<p>XMLRPC-Client:</p>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class LIB_Class_XMLRPC_Client extends LIB_Class_XMLRPC {

    private $host       = null;

    private $port       = null;

    private $user       = null;

    private $password   = null;

    private $path       = null;

    private $timeout    = null;

    private $connection = null;

    private $errno      = null;

    private $errstr     = null;

    public function __construct($host = '127.0.0.1', $port = '80', $path = '/', $timeout = '5') {
        $this-&gt;host    = $host;
        $this-&gt;port    = $port;
        $this-&gt;path    = $path;
        $this-&gt;timeout = $timeout;
    } 

    public function connect() {
        if($this-&gt;connection == null) {
            if($this-&gt;port == '443') {
                $this-&gt;connection = fsockopen('ssl://' . $this->host, $this->port, $this->errno, $this->errstr, $this->timeout);
            } else {
                $this-&gt;connection = fsockopen($this->host, $this->port, $this->errno, $this->errstr, $this->timeout);
            }
        }
    }

    public function disconnect() {
        if($this-&gt;connection !== null) {
            fclose($this-&gt;connection);
            $this-&gt;connection = null;
        }
    }

    public function setCredentials($user, $password) {
        $this-&gt;user     = $user;
        $this-&gt;password = $password;
    }

    public function call($request, $params) {
        $this-&gt;connect();

        $xml_req = xmlrpc_encode_request($request, $params);    

        $query   = "POST " . $this->path . " HTTP/1.0\n"
                 . "User-Agent: RIAD-F\n"
                 . "Host: " . $this->host . "\n"
                 . "Content-Type: text/xml\n";

        if(!is_null($this-&gt;user) &#038;&#038; !is_null($this-&gt;password)) {
            $query  .= "Authorization: Basic " . base64_encode($this-&gt;user.":".$this-&gt;password) . "\n";
        }

        $query  .= "Content-Length: " . strlen($xml_req) . "\n\n"
                 . $xml_req . "\n";

        if (!fputs($this-&gt;connection, $query, strlen($query))) {
            return 0;
        }

        $contents = '';

        while (!feof($this-&gt;connection)) {
            $contents .= fgets($this-&gt;connection);
        }

        $xml = substr($contents, strpos($contents, "\r\n\r\n")+4);

        $data = xmlrpc_decode($xml); 

        return $data;
    }   

}
</code></pre>
<p>XMLRPC-Server:</p>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class LIB_Class_XMLRPC_Server extends LIB_Class_XMLRPC {

    private $server = null;

    public function __construct() {}

    public function createServer() {
        if($this-&gt;server === null) {
            $this-&gt;server = xmlrpc_server_create();
        }
    }

    public function destroyServer() {
        if($this-&gt;server !== null) {
            xmlrpc_server_destroy($this->server);
            $this-&gt;server = null;
        }
    }

    public function setObject(&#038;$Object, $ServiceName = null) {
        $this-&gt;createServer();

        if(!is_object($Object)) {
            return false;
        }

        if($ServiceName === null) {
            $ServiceName = get_class($Object);
        }

        $methods = get_class_methods($Object);

        foreach($methods as $value) {
            if(is_callable(array(&#038;$Object, $value))) {
                xmlrpc_server_register_method($this->server, $ServiceName . '.' . $value, array(&#038;$Object, $value));
            }
        }

        return true;
    }

    public function setFunction($FunctionName, $ServiceName = null) {
        $this-&gt;createServer();    

        if(!is_string($FunctionName)) {
            return false;
        } 

        if($ServiceName === null) {
            $ServiceName = 'func';
        }   

        if(is_callable($FunctionName)) {
            xmlrpc_server_register_method($this->server, $ServiceName . '.' . $FunctionName, $FunctionName);
        }
    } 

    public function handle($xmlData, $UserData = null) {
        $this->createServer();

        return xmlrpc_server_call_method($this->server, $xmlData, $UserData);
    }

}
?>
</code></pre>
<p>Der ganze Spass wird zB so genutzt(Server):</p>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class APP_Controller_Index extends FW_Controller {

    public function index_action(array $params = null) {

        //connection to DB
        $db = LIB_Model_PDODB::getInstance(FW_Config::getInstance()->get('DB'));

        //setting up xmlrpc
        $xmlrpc_server = new LIB_Class_XMLRPC_Server();

        //loding working class and hand over db
        $news = LIB_Class_News::getInstance($db);

        //register working class xmlrpc
        $xmlrpc_server->setObject($news, 'news');

        //get request
        $request = file_get_contents('php://input');

        //answer xmlrp calls
        $response = $xmlrpc_server->handle($request);

        //output response
        $this->response->addContent($response);
    }

}
</code></pre>
<p>Client:</p>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class APP_Controller_Index extends FW_Controller {

    public function index_action(array $params = null) {
        $xmlrpc_client = new LIB_Class_XMLRPC_Client('127.0.0.1', '443', '/xmlrpc/');

        $xmlrpc_client->setCredentials('anonymous', 'anonymous');

        $this->response->addContent(print_r($xmlrpc_client->call('news.test', '6'), true));
    }

}
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://terrorhippiecrew.net/2010/07/xmlrpc-server-und-client/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP:XML2ARRAY  ARRAY2XML</title>
		<link>http://terrorhippiecrew.net/2010/06/phpxml2array-array2xml/</link>
		<comments>http://terrorhippiecrew.net/2010/06/phpxml2array-array2xml/#comments</comments>
		<pubDate>Wed, 02 Jun 2010 20:44:08 +0000</pubDate>
		<dc:creator>w13531</dc:creator>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://terrorhippiecrew.net/?p=658</guid>
		<description><![CDATA[Ich habe eine Weile gegooglet und getüftelt bis es ging, jetzt geht es: Ich habe eine kleine Klasse geschrieben(kommt auch im FW zum Einsatz), die mir PHP-Arrays in konformes XML und zurück umwandelt, eigentlich wollte ich ja das schöne WDDX verwenden, aber meine Webhoster mag nicht so wie ich, PHP Serialize kommt nicht in Frage, [...]]]></description>
			<content:encoded><![CDATA[<p>Ich habe eine Weile gegooglet und getüftelt bis es ging, jetzt geht es:<br />
Ich habe eine kleine Klasse geschrieben(kommt auch im FW zum Einsatz), die mir PHP-Arrays in konformes XML und zurück umwandelt, eigentlich wollte ich ja das schöne WDDX verwenden, aber meine Webhoster mag nicht so wie ich, PHP Serialize kommt nicht in Frage, das selbe trifft auf json zu, außerdem will man den spass ja vlt auch irgendwohin mal exportieren und da ist XML schon schöner, irgendwie. Die PEAR Pakete wollte ich für so ein kleinens Problem auch nicht nutzen, ansonsten wäre der PEAR::XML_Serializer eine sehr schöne Sache gewesen.<br />
Sie hat leider ein paar kleine Kinderkrankheiten, z.B. das leere Elemente rausfallen, darum fülle ich leere Elemente mit einem festgelegten Füllzeichen vorher auf um das Problem zu umgehen, ja ich weis das ist doof, ach machts doch selbst besser :D.<br />
Genug gefaselt, hier die Klasse:</p>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class LIB_Model_XMLFile extends FW_Model_File {

    private $file = null;

    public function __construct($file = null) {
        $this-&gt;file = $file;
    }

    /**
    * reads a XML File to an array
    * @param  $file
    * @return array()
    **/
    public function XMLFile2array($file = null) {

        if($file == null) {
            $file = $this-&gt;file;
        }

        if(file_exists($file)) {

            $xml = simplexml_load_file($file);     

            $xml = $this-&gt;xml2array($xml);

            array_walk_recursive($xml, array($this, 'remove_'));

            return $xml;
        }

        return $file;
    }

    private function remove_(&#038;$value, $key) {
        if($value == '_') {
            $value = '';
        }
        $value = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
    }

    /**
    * iterates over an SimpleXML object to convert it into an array
    **/
    private function xml2array($data) {

        if (is_object($data)) {
            $data = get_object_vars($data);
        }

        return (is_array($data)) ? array_map(array($this, 'xml2array'), $data) : $data;
    }

    /**
    * converts a array into an xml file
    **/
    public function array2XMLFile(array $array, $file = null) {

        if($file == null) {
            $file = $this-&gt;file;
        }

        if(file_exists($file)) {

            array_walk_recursive($array, array($this, 'add_'));

            $xml = $this-&gt;array2xml($array, 'page');

            //pretty output
            /*$doc = new DOMDocument('1.0', 'UTF-8');
            $doc-&gt;formatOutput = true;
            $domnode = dom_import_simplexml($xml);
            $domnode = $doc-&gt;importNode($domnode, true);
            $domnode = $doc-&gt;appendChild($domnode);
            return $doc-&gt;saveXML();*/

            return $xml-&gt;asXML($file);
        }

        return $file;

    }

    private function add_(&#038;$value, $key) {
        if($value == '' || empty($value)) {
            $value = '_';
        }
        $value = htmlentities($value, ENT_QUOTES, 'UTF-8');
    }

    /**
    * iterates over an array to convert it into xml
    * @param $data: array
    * @param $rootNodeName
    * @param $xml SimplXMLElement
    * @return $xml SimplXMLElement
    **/
    private function array2xml($data, $rootNodeName = 'data', &#038;$xml = null) {
	   if (is_null($xml)) {
	        $xml = '&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt;
            &lt;!DOCTYPE html_ent [
            &lt;!ENTITY auml "&#228;"&gt;
            &lt;!ENTITY Auml "&#196;"&gt;
            &lt;!ENTITY uuml "&#252;"&gt;
            &lt;!ENTITY Uuml "&#220;"&gt;
            &lt;!ENTITY ouml "&#246;"&gt;
            &lt;!ENTITY Ouml "&#214;"&gt;
            &lt;!ENTITY nbsp "&#160;"&gt;
            &lt;!ENTITY euro "&#8364;"&gt;
            &lt;!ENTITY quot "&#34;"&gt;
            &lt;!ENTITY apos "&#39;"&gt;
            &lt;!ENTITY szlig "&#223;"&gt;
            &lt;!ENTITY amp "&#38;"&gt;
            ]&gt;';
	       $xml = simplexml_load_string($xml . "&lt;$rootNodeName /&gt;");
	   }

       foreach($data as $key =&gt; $value) {
            if(is_numeric($key)) {
                $key = $rootNodeName;
            }
            $key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);

            if(is_array($value)) {
                $node = $this-&gt;isAssoc($value) ? $xml-&gt;addChild($key) : $xml;
                $this-&gt;array2xml($value, $key, $node);
            } else {
                $xml-&gt;addChild($key, $value);
            }
       }
       return $xml;
    }

    private function isAssoc( $array ) {
        return (is_array($array) &#038;&#038; 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
    }

}
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://terrorhippiecrew.net/2010/06/phpxml2array-array2xml/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mein Framework &#8211; Überarbeitet Version 2.00 online</title>
		<link>http://terrorhippiecrew.net/2010/05/mein-framework-uberarbeitet-version-2-00-online/</link>
		<comments>http://terrorhippiecrew.net/2010/05/mein-framework-uberarbeitet-version-2-00-online/#comments</comments>
		<pubDate>Tue, 04 May 2010 22:45:02 +0000</pubDate>
		<dc:creator>w13531</dc:creator>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://terrorhippiecrew.net/?p=646</guid>
		<description><![CDATA[Soo is ja auch schon wieder ein Monate her und viel ist geschehen. Featurelist: Struktur komplett überarbeitet Im &#8216;framework&#8217; Verzeichniss befinden sich nun nurnoch die notwendigsten Komponenten, quasi der Core. Im &#8216;library&#8217; Verzeichniss befinden sich die Facklassen, sowie spezielle Implementierungen der im Framework festgelegten Interfaces alle Verzeichnisse sind in Model/View/Controller Subdirs unterteilt es gibt nun [...]]]></description>
			<content:encoded><![CDATA[<p>Soo is ja auch schon wieder ein Monate her und viel ist geschehen.</p>
<p>Featurelist:</p>
<ul>
<li><strong>Struktur komplett überarbeitet</strong><br />
Im &#8216;framework&#8217; Verzeichniss befinden sich nun nurnoch die notwendigsten Komponenten, quasi der Core.<br />
Im &#8216;library&#8217; Verzeichniss befinden sich die Facklassen, sowie spezielle Implementierungen der im Framework festgelegten Interfaces</li>
<li>alle Verzeichnisse sind in Model/View/Controller Subdirs unterteilt</li>
<li>es gibt nun auch Funktionen die dem View übergeben werden können(sog. View helper), um z.B. Texte zu formatieren usw&#8230;. Achtung: Natürlich kann man im Helper auch Datenbankmanipulation oder anderes durchführen, dies kann zu Inkonsistenz des MVC-Pattern führen und die Komponententrennung zerstören, also mit Bedacht verwenden oder nur dafür wofür Sie gemacht wurden</li>
<li>ein paar kleine Fachkassen sind dazu gekommen(Events, Guestbook, News, Mailer, Validator), weitere Folgen</li>
<li>Datenbank Klassen komplett überarbeitet</li>
<li>ein paar Bugs entfernt(und ein paar hinzugefügt:D)</li>
<li>Autoloader ausgelagert</li>
<li>FW_Workbench überarbeitet</li>
<li>FW_Session überarbeitet</li>
<li>alle Kassen an die neue Struktur angepasst</li>
<li>ACL hinzugefügt</li>
<li>es können jetzt dank autoloader prefixe beliebig viele applications mit unterschiedlichen domains auf dem selben framwork ausgeführt werden</li>
<li>TODO: application modul system</li>
</ul>
<p>Insgesamt wirkt es durch die saubere Trennung wesentlich einfacher in der Handhabung.<br />
Viel Spass damit!</p>
<p><a href="http://terrorhippiecrew.net/2010/02/mein-framework-inhaltsverzeichnis/">zur neuen Version</a></p>
]]></content:encoded>
			<wfw:commentRss>http://terrorhippiecrew.net/2010/05/mein-framework-uberarbeitet-version-2-00-online/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mein Framework &#8211; #13 &#8211; Mailer</title>
		<link>http://terrorhippiecrew.net/2010/04/mein-framework-13-mailer/</link>
		<comments>http://terrorhippiecrew.net/2010/04/mein-framework-13-mailer/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 14:37:43 +0000</pubDate>
		<dc:creator>w13531</dc:creator>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://terrorhippiecrew.net/?p=532</guid>
		<description><![CDATA[&#60; &#8211; Inhaltsverzeichnis FW_Mail: was soll man dazu noch sagen&#8230;. /** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/ class FW_Mail extends FW_Object { private $to = array(); private $from = null; private $subject = null; private $body = null; private $headers = array(); /** * constructor **/ public [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://terrorhippiecrew.net/2010/04/mein-framework-12-filter/">&lt;</a> &#8211; <a href="http://terrorhippiecrew.net/2010/02/mein-framework-inhaltsverzeichnis/">Inhaltsverzeichnis</a><br />
<strong>FW_Mail:</strong> was soll man dazu noch sagen&#8230;.</p>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class FW_Mail extends FW_Object {

    private $to       = array();

    private $from     = null;

    private $subject  = null;

    private $body     = null;

    private $headers  = array();

    /**
    * constructor
    **/
    public function __construct($to, $from, $subject, $body) {
        if(is_array($to)) {
            $this->to   = $to;
        } else {
            $this->to[] = $to;
        }

        $this->from    = $from;
        $this->subject = $subject;
        $this->body    = wordwrap($body, 70);
    }

    /**
    * sends an email with the given data
    **/
    public function send(){
        $this->addHeader('From', $this->from);
        $this->addHeader('Reply-To', $this->from);
        $this->addHeader('Return-Path', $this->from);
        $this->addHeader('X-mailer:', 'RIAD-F Mail System');

        foreach($this->headers as $key => $value) {
            $header .= $key . ': ' . $value . "\n";
        }

        foreach($this->to as $value) {
            if($this->valid_email($value)) {
                mail($value, $this->subject, $this->body, $header);
            }
        }
    }

    /**
    * add custom header
    **/
    public function addHeader($name, $value){
        $this->headers[$name] = $value;
    }

    /**
    * validates email addresses
    * @return bool
    **/
    public function valid_email($email){
        $qtext          = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
  		$dtext 			= '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
  		$atom           = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
                   		  '\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
        $quoted_pair    = '\\x5c[\\x00-\\x7f]';

        $domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
  		$quoted_string  = "\\x22($qtext|$quoted_pair)*\\x22";
  		$domain_ref     = $atom;

        $sub_domain     = "($domain_ref|$domain_literal)";
  		$word           = "($atom|$quoted_string)";

        $domain         = "$sub_domain(\\x2e$sub_domain)*";
  		$local_part     = "$word(\\x2e$word)*";

        $addr_spec      = "$local_part\\x40$domain";

  		return preg_match("!^$addr_spec$!", $email) ? true : false;
	}

}
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://terrorhippiecrew.net/2010/04/mein-framework-13-mailer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mein Framework &#8211; #12 &#8211; Filter</title>
		<link>http://terrorhippiecrew.net/2010/04/mein-framework-12-filter/</link>
		<comments>http://terrorhippiecrew.net/2010/04/mein-framework-12-filter/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 14:33:10 +0000</pubDate>
		<dc:creator>w13531</dc:creator>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://terrorhippiecrew.net/?p=526</guid>
		<description><![CDATA[&#60; &#8211; Inhaltsverzeichnis &#8211; &#62; Das Filter Interface und die Chain-Klasse, wir bedienen uns dabei dem Composite Pattern. Ich stelle hier auch noch 2 Beispiel Filter zur Verfügung(uhhhh, wie großzügig :D) FW_Filter_Interface: /** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/ interface FW_Filter_Interface { public function execute(FW_Http_Request $request, FW_Http_Response [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://terrorhippiecrew.net/2010/04/mein-framework-11-der-front-controller/">&lt;</a> &#8211; <a href="http://terrorhippiecrew.net/2010/02/mein-framework-inhaltsverzeichnis/">Inhaltsverzeichnis</a> &#8211; <a href="http://terrorhippiecrew.net/2010/04/mein-framework-13-mailer/">&gt;</a><br />
Das Filter Interface und die Chain-Klasse, wir bedienen uns dabei dem Composite Pattern. Ich stelle hier auch noch 2 Beispiel Filter zur Verfügung(uhhhh, wie großzügig :D)</p>
<ul>
<li><strong>FW_Filter_Interface:</strong>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
interface FW_Filter_Interface {
    public function execute(FW_Http_Request $request, FW_Http_Response $response);
}
</code></pre>
</li>
<li><strong>FW_Filter_Chain:</strong>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class FW_Filter_Chain extends FW_Object implements FW_Filter_Interface {

    private $filters = array();

    public function addFilter(FW_Filter_Interface $filter) {
        $this->filters[] = $filter;
    }

    public function execute(FW_Http_Request $req, FW_Http_Response $res) {
        foreach($this->filters as $filter) {
            $filter->execute($req, $res);
        }
    }

}
</code></pre>
</li>
<li><strong>FW_GZip_Filter:</strong>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class FW_GZip_Filter implements FW_Filter_Interface {

  public function execute(FW_Http_Request $request, FW_Http_Response $response) {

        if($request->getHeader('accept_encoding') &#038;&#038; strpos($request->getHeader('accept_encoding'), 'gzip') !== false) {

            $txt = $response->getContent();

            if(DEVELOPMENT_ENVIRONMENT == false) {

                $response->addHeader('Content-Encoding', 'gzip');
                $txt = gzencode($txt, 9);

            }

            $response->replaceContent($txt);
        }
  }

}
</code></pre>
</li>
<li><strong>FW_Headers_Filter:</strong>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class FW_Headers_Filter implements FW_Filter_Interface {

  public function execute(FW_Http_Request $request, FW_Http_Response $response) {

        $response->addHeader('X-Powered-By', 'RIAD-F');
        $response->addHeader('Server', 'RIAD-F Application Server');

  }

}
</code></pre>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://terrorhippiecrew.net/2010/04/mein-framework-12-filter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mein  Framework &#8211; #11 &#8211; Der Front Controller</title>
		<link>http://terrorhippiecrew.net/2010/04/mein-framework-11-der-front-controller/</link>
		<comments>http://terrorhippiecrew.net/2010/04/mein-framework-11-der-front-controller/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 14:20:10 +0000</pubDate>
		<dc:creator>w13531</dc:creator>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://terrorhippiecrew.net/?p=512</guid>
		<description><![CDATA[&#60; &#8211; Inhaltsverzeichnis &#8211; &#62; FW_Front_Controller: er liest aus dem Request ab welche Kontroller und Aktionen ausgeführt werden sollen, mit welchen Parametern. Er läd diese und übergibt Ihnen den Request und den Response. Er führt Pre- &#038; Postfilter aus und schickt das Response zum Browser. /** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://terrorhippiecrew.net/2010/04/mein-framework-10-http-request-klasse/">&lt;</a> &#8211; <a href="http://terrorhippiecrew.net/2010/02/mein-framework-inhaltsverzeichnis/">Inhaltsverzeichnis</a> &#8211; <a href="http://terrorhippiecrew.net/2010/04/mein-framework-12-filter/">&gt;</a><br />
<strong>FW_Front_Controller:</strong> er liest aus dem Request ab welche Kontroller und Aktionen ausgeführt werden sollen, mit welchen Parametern. Er läd diese und übergibt Ihnen den Request und den Response. Er führt Pre- &#038; Postfilter aus und schickt das Response zum Browser.</p>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class FW_Front_Controller extends FW_Object {

    private static $instance = null;

    private $preFilters     = null;

    private $postFilters    = null;

    private $controller_path = null;

    /**
    * private clone
    **/
    private function __clone() {}

    /**
    * private constructor
    **/
    private function __construct() {
        $this->preFilters  = FW_Workbench::ClassLoader('FW_Filter_Chain');
        $this->postFilters = FW_Workbench::ClassLoader('FW_Filter_Chain');
    }

    /**
    * singleton
    **/
    public static function getInstance() {

        if(self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
    * set the path to application controllers
    **/
    public function setControllerPath($cntrl_path = null) {
        if($cntrl_path == null) {
            $this->controller_path = DR . 'application' . DS;
        } else {
            $this->controller_path = $cntrl_path;
        }
    }

    /**
    * class loader factory
    **/
    public function ClassLoader($ClassName, $params = null) {

        if(!is_string($ClassName) || !trim($ClassName)) {
            $this->log(date('H:i:s', time()) . "\t" . __CLASS__ . ':' . __FUNCTION__ . '() tried to load illegal class: ' . $ClassName);
            return false;
        }

        $class_path = $this->controller_path . $ClassName . '.class.php';

        if(file_exists($class_path)) {
            require_once($class_path);
        } else {
            $this->log(date('H:i:s', time()) . "\t" . __CLASS__ . ':' . __FUNCTION__ . '() File not found: ' . $class_path);
            return false;
        }

        if(class_exists($ClassName)) {
            try {
                $obj = new $ClassName($params);
            } catch(Exception $e) {
                $this->log(date('H:i:s', time()) . "\t" . __CLASS__ . ':' . __FUNCTION__ . '() could not create class: ' . $e->getMessage());
                return false;
            }
        } else {
            $this->log(date('H:i:s', time()) . "\t" . __CLASS__ . ':' . __FUNCTION__ . '() class not found: ' . $ClassName);
            return false;
        }

        $this->log(date('H:i:s', time()) . "\t" . __CLASS__ . ':' . __FUNCTION__ . '() invoked successfully class: ' . $ClassName);
        return $obj;
    } 

    /**
    * URL Router
    **/
    public function route(FW_HTTP_Request $request, FW_HTTP_Response $response) {

        if($request->issetGet('url') &#038;&#038; $request->getGet('url') != '') {

            $url = explode('/',$request->getGet('url')); 

            if(isset($url[0]) &#038;&#038; $url[0] != '') {
                $module = htmlentities(array_shift($url));
            } else {
                $module = 'index';
            }

            if(isset($url[0]) &#038;&#038; $url[0] != '') {
                $action = htmlentities(array_shift($url));
            } else {
                $action = 'index';
            }

            if(is_array($url)) {
                $params = $url;
            } else {
                $params = null;
            }

        } else {

            $module = 'index';
            $action = 'index';
            $params = null;           

        }

        $request->setControllerName($module);
        $request->setActionName($action);
        $request->setActionParams($params);
    }

    /**
    * add a pre-filter
    **/
    public function addPreFilter(FW_Filter_Interface $filter) {
        $this->preFilters->addFilter($filter);
    }

    /**
    * add a post-filter
    **/
    public function addPostFilter(FW_Filter_Interface $filter) {
        $this->postFilters->addFilter($filter);
    }

    /**
    * runs a user defined controller
    * via URL Request
    * and outputs the Response
    * excecutes PRE and POST filters
    * TODO: implement ACL for fully CMS
    **/
    public function run(FW_Http_Request $request, FW_Http_Response $response) {

        $this->preFilters->execute($request, $response); 

        $module = ucwords($request->getControllerName()) . '_Controller';
        $action = $request->getActionName()     . '_action';
        $params = $request->getActionParams();

        $controller = $this->ClassLoader($module, array($request, $response));

        if($controller &#038;&#038; $controller instanceof FW_Controller) {

           if(is_callable(array($controller, $action))) {

                $controller->$action($params);

           } else if(is_callable(array($controller, 'index_action'))) { //default action instead?

                array_unshift($params, $request->getActionName()); //for consistency
                $request->setActionName('index');                  //for consistency
                $controller->index_action($params);

           } else {

                $response->redirect($request, $response, 'error', 'error_404', $params);
                $this->log(date('H:i:s',time()) . "\t" . __CLASS__ . ':' . __FUNCTION__ . '() tried to excecute invalid Action Method: '. $module . '->' . $action . '()');    

           } 

        } else {
           $this->log(date('H:i:s',time()) . "\t" . __CLASS__ . ':' . __FUNCTION__ . '() tried to excecute invalid Controller: '. $module . '->' . $action . '()');
           $response->redirect($request, $response, 'error', 'error_404', $params);
        }

        $this->postFilters->execute($request, $response);

        $response->send();

    }

}
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://terrorhippiecrew.net/2010/04/mein-framework-11-der-front-controller/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mein Framwork &#8211; #10 &#8211; HTTP Request Klasse</title>
		<link>http://terrorhippiecrew.net/2010/04/mein-framework-10-http-request-klasse/</link>
		<comments>http://terrorhippiecrew.net/2010/04/mein-framework-10-http-request-klasse/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 14:14:07 +0000</pubDate>
		<dc:creator>w13531</dc:creator>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://terrorhippiecrew.net/?p=508</guid>
		<description><![CDATA[&#60; &#8211; Inhaltsverzeichnis &#8211; &#62; Die FW_HTTP_Request Klasse ist ein Singleton, da ja nur ein Request existieren kann. Diese Klasse beinhaltet alle vom Nutzer übergebenen Informationen(header, variablen, dateien, authorisierungen) sowie die MVC Controller/Actions/Params um dem Front Controller die nötigen Infos zu geben. /** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://terrorhippiecrew.net/2010/04/mein-framework-9-http-response-klasse/">&lt;</a> &#8211; <a href="http://terrorhippiecrew.net/2010/02/mein-framework-inhaltsverzeichnis/">Inhaltsverzeichnis</a> &#8211; <a href="http://terrorhippiecrew.net/2010/04/mein-framework-11-der-front-controller/">&gt;</a><br />
Die <strong>FW_HTTP_Request</strong> Klasse ist ein Singleton, da ja nur ein Request existieren kann. Diese Klasse beinhaltet alle vom Nutzer übergebenen Informationen(header, variablen, dateien, authorisierungen) sowie die MVC Controller/Actions/Params um dem Front Controller die nötigen Infos zu geben.</p>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class FW_HTTP_Request extends FW_Object {

    private $post;

    private $get;

    private $cookie;

    private $file;

    private $header;

    private $auth;

    private $server;

    private $MVC_Controller;

    private $MVC_Action;

    private $MVC_Action_Params;

    private static $instance = null;

    /**
    * private clone
    **/
    private function __clone() {}

    /**
    * private constructor
    **/
    private function __construct() {

        $this->post   = &#038;$_POST;
        $this->get    = &#038;$_GET;
        $this->cookie = &#038;$_COOKIE;
        $this->file   = &#038;$_FILES;

        foreach($_SERVER as $key => $value) {
            if(substr($key, 0, 5)== 'HTTP_') {
                $key = strtolower($key);                 //weil es schöner aussieht
                $this->header[substr($key,5)] = $value;  //HTTP_ abschneiden
            } else if($key != 'PHP_AUTH_USER' &#038;&#038; $key != 'PHP_AUTH_PW') {
                $key = strtolower($key);
                $this->server[$key] = $value;
            }
        } 

        if(isset($_SERVER['PHP_AUTH_USER'])) {
            $this->auth['user'] = $_SERVER['PHP_AUTH_USER'];
            $this->auth['pass'] = $_SERVER['PHP_AUTH_PW'];
        } else {
            $this->auth = null;
        }
    }

    /**
    * singleton
    **/
    public static function getInstance() {

        if(self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }   

    /**
    * sets the name of the controller
    **/
    public function setControllerName($name) {
        $this->MVC_Controller = strtolower($name);
    }

    /**
    * gets the name of the controller
    **/
    public function getControllerName() {
        return $this->MVC_Controller;
    }

    /**
    * sets the name of the action method
    **/
    public function setActionName($name) {
        $this->MVC_Action = strtolower($name);
    }

    /**
    * gets the name of the action method
    **/
    public function getActionName() {
        return $this->MVC_Action;
    }

    /**
    * sets the paramteter for the action method
    **/
    public function setActionParams($params) {
        $this->MVC_Action_Params = $params;
    }

    /**
    * gets the parameter for action method
    **/
    public function getActionParams() {
        return $this->MVC_Action_Params;
    }

    /**
    * get authentication data
    **/
    public function getAuthData() {
        return $this->auth;
    }

    /**
    * header information exisits
    **/
    public function issetHeader($key) {
        $key = strtolower($key);
        return (isset($this->header[$key]));
    }

    /**
    * get header informations
    **/
    public function getHeader($key) {
        $key = strtolower($key);
        if($this->issetHeader($key)) {
            return $this->header[$key];
        }
        return null;
    }

    /**
    * server information exisits
    **/
    public function issetServer($key) {
        $key = strtolower($key);
        return (isset($this->server[$key]));
    }

    /**
    * get server informations
    **/
    public function getServer($key) {
        $key = strtolower($key);
        if($this->issetServer($key)) {
            return $this->server[$key];
        }
        return null;
    }

    /**
    * Get var exists
    **/
    public function issetGet($key) {
        return (isset($this->get[$key]));
    }

    /**
    * gets Get data
    **/
    public function getGet($key) {
        if($this->issetGet($key)) {
            return $this->get[$key];
        }
        return null;
    }

    /**
    * post var exists
    **/
    public function issetPost($key) {
        return (isset($this->post[$key]));
    }

    /**
    * gets Post data
    **/
    public function getPost($key) {
        if($this->issetPost($key)) {
            return $this->post[$key];
        }
        return null;
    }

    /**
    * file exists
    **/
    public function issetFile($key) {
        return (isset($this->file[$key]));
    }

    /**
    * gets a file
    **/
    public function getFile($key) {
        if($this->issetFile($key)) {
            return $this->file[$key];
        }
        return null;
    }

    /**
    * cookie exists
    **/
    public function issetCookie($key) {
        return (isset($this->cookie[$key]));
    }

    /**
    * gets cookie data
    **/
    public function getCookie($key) {
        if($this->issetCookie($key)) {
            return $this->cookie[$key];
        }
        return null;
    }

}
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://terrorhippiecrew.net/2010/04/mein-framework-10-http-request-klasse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mein Framwork &#8211; #9 &#8211; HTTP Response Klasse</title>
		<link>http://terrorhippiecrew.net/2010/04/mein-framework-9-http-response-klasse/</link>
		<comments>http://terrorhippiecrew.net/2010/04/mein-framework-9-http-response-klasse/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 14:07:13 +0000</pubDate>
		<dc:creator>w13531</dc:creator>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://terrorhippiecrew.net/?p=502</guid>
		<description><![CDATA[&#60; &#8211; Inhaltsverzeichnis &#8211; &#62; Der FW_HTTP_Response enthält die Antwort(status/headers/content) auf den Request, auch er ist ein Singleton. Er besitzt ausserdem die Fähigkeit auf URLs oder andere Controller zu redirecten. /** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/ class FW_HTTP_Response extends FW_Object { private $headers = array(); private [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://terrorhippiecrew.net/2010/03/mein-framework-8-config-klasse/">&lt;</a> &#8211; <a href="http://terrorhippiecrew.net/2010/02/mein-framework-inhaltsverzeichnis/">Inhaltsverzeichnis</a> &#8211; <a href="http://terrorhippiecrew.net/2010/04/mein-framework-10-http-request-klasse/">&gt;</a><br />
Der <strong>FW_HTTP_Response</strong> enthält die Antwort(status/headers/content) auf den Request, auch er ist ein Singleton. Er besitzt ausserdem die Fähigkeit auf URLs oder andere Controller zu redirecten.</p>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class FW_HTTP_Response extends FW_Object {

    private $headers = array();

    private $content = "";

    private $status  = "200 OK";

    private static $instance = null;

    /**
    * private clone
    **/
    private function __clone() {}

    /**
    * private constructor
    **/
    private function __construct() {}

    /**
    * singleton
    **/
    public static function getInstance() {

        if(self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    } 

    /**
    * adds custom headers
    **/
    public function addHeader($name, $content) {
        $this->headers[$name] = $content;
    }

    /**
    * sets the header status
    **/
    public function setStatus($status) {
        $this->status = $status;
    }

    /**
    * appends a line of content
    **/
    public function addContent($content) {
        $this->content .= $content;
    }

    /**
    * return content
    **/
    public function getContent() {
        return $this->content;
    }  

    /**
    * replace content
    **/
    public function replaceContent($newContent) {
        $this->content = $newContent;
    }

    /**
    * sends the content to the browser
    **/
    public function send() {

        header("HTTP/1.0 ".$this->status);

        if(!empty($this->headers)) {
            foreach($this->headers as $name => $content) {
                header($name.": ".$content);
            }
        }

        echo $this->content;

        //resetten
        $this->content = "";
        $this->headers = null;
    }

    /**
    * redirect a URL
    **/
    public function redirectURL($url, $immediately = false) {
        $this->addHeader("Location", $url);
        if($immediately === true) {
            $this->send();
            exit();
        }
    }

    /**
    * redirects to a controller/action pair
    **/
    public function redirect(FW_HTTP_Request $request,FW_HTTP_Response $response, $controller, $action, array $params = null) {

        $request->setControllerName($controller);
        $request->setActionName($action);
        $request->setActionParams($params);

        FW_Front_Controller::getInstance()->run($request, $response);
    }

    /**
    * sets a cookie
    **/
    public function setCookie($name, $value = null, $expire = null, $path = "/") {
        $expire = (int)($expire === null) ? time()+3600 : $expire;
        setcookie($name, $value, $expire, $path);
    }

    /**
    * deletes a cookie
    **/
    public function deleteCookie($name) {
        $this->setCookie($name, null, (time()-(86400*365*10)));
    }

}
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://terrorhippiecrew.net/2010/04/mein-framework-9-http-response-klasse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spass mit MySQL</title>
		<link>http://terrorhippiecrew.net/2010/03/spass-mit-mysql/</link>
		<comments>http://terrorhippiecrew.net/2010/03/spass-mit-mysql/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 15:19:18 +0000</pubDate>
		<dc:creator>w13531</dc:creator>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://terrorhippiecrew.net/?p=475</guid>
		<description><![CDATA[Hier ein paar Queries die ich ganz nett finde: E-Mail adresse in DB beim auslesen zum Link machen: $sql = "SELECT INSERT(INSERT(mail, CHAR_LENGTH(mail) + 1, 0, '\"&#62;E-Mail&#60;/a&#62;'), 1, 0, '&#60;a href=\"mailto:') as 'E-Mail' WHERE ....;";]]></description>
			<content:encoded><![CDATA[<p>Hier ein paar Queries die ich ganz nett finde:</p>
<p>E-Mail adresse in DB beim auslesen zum Link machen:<br />
<code>$sql = "SELECT INSERT(INSERT(mail, CHAR_LENGTH(mail) + 1, 0, '\"&gt;E-Mail&lt;/a&gt;'), 1, 0, '&lt;a href=\"mailto:') as 'E-Mail' WHERE ....;";</code></p>
]]></content:encoded>
			<wfw:commentRss>http://terrorhippiecrew.net/2010/03/spass-mit-mysql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mein Framework &#8211; #7 &#8211; Session Management</title>
		<link>http://terrorhippiecrew.net/2010/03/mein-framework-7-session-management/</link>
		<comments>http://terrorhippiecrew.net/2010/03/mein-framework-7-session-management/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 09:40:18 +0000</pubDate>
		<dc:creator>w13531</dc:creator>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://terrorhippiecrew.net/?p=449</guid>
		<description><![CDATA[&#60; &#8211; Inhaltsverzeichnis &#8211; &#62; FW_Session: diese Klasse bietet Session-Verwaltungsfunktionen an, das ganze Funktioniert natürlich nur dann, wenn man auch nur brav die hier Verwendeten methoden benutzt und nicht direkt mit der Session arbeitet. /** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/ class FW_Session extends FW_Object { private [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://terrorhippiecrew.net/2010/02/mein-framework-6-die-controller/">&lt;</a> &#8211; <a href="http://terrorhippiecrew.net/2010/02/mein-framework-inhaltsverzeichnis/">Inhaltsverzeichnis</a> &#8211; <a href="http://terrorhippiecrew.net/2010/03/mein-framework-8-config-klasse/">&gt;</a><br />
<strong>FW_Session:</strong> diese Klasse bietet Session-Verwaltungsfunktionen an, das ganze Funktioniert natürlich nur dann, wenn man auch nur brav die hier Verwendeten methoden benutzt und nicht direkt mit der Session arbeitet.</p>
<pre><code>/** (c) 2010 Arne "w13531" Wenzel [ mailto: w13531 (at) terrorhippiecrew (dot) net ] **/
class FW_Session extends FW_Object {

    private static $instance = null;

    private $_sess_db = null;

    /**
    * private clone
    **/
    private function __clone() {}

    /**
    * private constructor
    **/
    private function __construct() {}    

    /**
    * singleton
    **/
    public static function getInstance() {

        if (self::$instance === null) {
            self::$instance = new self;
        }

        return self::$instance;
    } 

    /**
    * set a custom session save handler
    **/
    public static function setSaveHandler($open = null, $close = null, $read = null, $write = null, $destroy = null, $gc = null) {

        if($open!=null &#038;&#038; $close!=null &#038;&#038; $read!=null &#038;&#038; $write!=null &#038;&#038; $destroy!=null &#038;&#038; $gc!=null) {

            return session_set_save_handler($open, $close, $read, $write, $destroy, $gc);

        } else {

            return session_set_save_handler(array(self,'openHandler'), array(self,'closeHandler'), array(self,'readHandler'), array(self,'writeHandler'), array(self,'destroyHandler'), array(self,'gcHandler'));

        }
    }

    /**
    * TODO: custom session save handler to open a session
    **/
    public static function openHandler() {
        if (self::$_sess_db = mysql_connect('localhost',
                                            'root',
                                            '')) {
            return mysql_select_db('my_application', self::$_sess_db);
        }
        return false;
    }

    /**
    * TODO: custom session save handler to close a session
    **/
    public static function closeHandler() {
        return mysql_close(self::$_sess_db);
    }

    /**
    * TODO: custom session save handler to read a session
    **/
    public static function readHandler($id) {
        $id = mysql_real_escape_string($id);
        $sql = sprintf("SELECT `session_data` FROM `sessions` " .
                       "WHERE `session` = '%s'", $id);
        if ($result = mysql_query($sql, self::$_sess_db)) {
            if (mysql_num_rows($result)) {
                $record = mysql_fetch_assoc($result);
                return $record['session_data'];
            }
        }
        return '';
    }

    /**
    * TODO: custom session save handler to write a session
    **/
    public static function writeHandler($id, $data) {
        $sql = sprintf("REPLACE INTO `sessions` VALUES('%s', '%s', '%s')",
                       mysql_real_escape_string($id),
                       mysql_real_escape_string(time()),
                       mysql_real_escape_string($data)
                       );
        return mysql_query($sql, self::$_sess_db);
    }

    /**
    * TODO: custom session save handler to destroy a session
    **/
    public static function destroyHandler($id) {
        $sql = sprintf("DELETE FROM `sessions` WHERE `session` = '%s'", $id);
        return mysql_query($sql, self::$_sess_db);
    }

    /**
    * TODO: custom session save handler to garbage collect a session
    **/
    public static function gcHandler($max) {
        $sql = sprintf("DELETE FROM `sessions` WHERE `session_expires` < '%s'",
                       mysql_real_escape_string(time() - $max));
        return mysql_query($sql, self::$_sess_db);
    }

    /** TODO:
    CREATE TABLE IF NOT EXISTS `sessions` (
    `session` varchar(255) character set utf8 collate utf8_bin NOT NULL,
    `session_expires` int(10) unsigned NOT NULL default '0',
    `session_data` text collate utf8_unicode_ci,
    PRIMARY KEY  (`session`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    **/

    /**
    * writes the session down when obj is destroyed
    **/
    public function __destruct() {
          session_write_close();
    }

    /**
    * gets a var
    **/
    public function __get($var) {

        if(isset($_SESSION[$var])) {
            return $_SESSION[$var];
        } else {
            return null;
        }

    }

    /**
    * sets a var
    **/
    public function __set($var, $val) {
          return ($_SESSION[$var] = $val);
    }

    /**
    * unsets a var
    **/
    public function __unset($var) {
          if(isset($_SESSION[$var])) {
                unset($_SESSION[$var]);
          }
    }

    /**
    * destroys a session
    **/
    public function destroy() {

        $_SESSION = array();

        if (isset($_COOKIE[session_name()])) {
	 		setcookie(session_name(), '', time()-42000, '/');
        }

        session_destroy();

    }

    /**
    * returns session id
    **/
    public function getID() {
        return session_id();
    }

    /**
    * set session id
    **/
    public function setID($id) {
        return session_id($id);
    }

    /**
    * sets the session save path
    **/
    public function setSessionSavePath($path) {
        session_save_path($path);
    } 

    /**
    * gets the session save path
    **/
    public function getSessionSavePath() {
        return session_save_path();
    } 

    /**
    * starts a session
    **/
    public function start() {
        session_start();
    }

    /**
    * encodes a session
    **/
    public function encode() {
        return session_encode();
    }

    /**
    * decodes a session
    **/
    public function decode() {
        return session_decode();
    }

    /**
    * gets the cookie parameters
    **/
    public function getCookieParams() {
        return session_get_cookie_params();
    }

    /**
    * sets cookie parameters
    **/
    public function setCookieParams($lifetime, $path=null, $domain=null,$secure=false, $httponly) {
        session_set_cookie_params($lifetime, $path, $secure , $httponly = false);
    }

    /**
    * regenerates the session
    **/
    public function regenerateID($old = false) {
        session_regenerate_id($old);
    }

    /**
    * sets the session name
    **/
    public function setName($name) {
        session_name($name);
    }

    /**
    * gets the session name
    **/
    public function getName() {
        return session_name();
    }

}
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://terrorhippiecrew.net/2010/03/mein-framework-7-session-management/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
