<?
/* ####################################################################################### DEBUG ######################################################################################################################################################################################################################################################################################## */

    
error_reporting(E_ERROR);
 
//print_r($_POST); phpinfo(); die(); //print_r(debug_backtrace());
    
session_start();
    if ( isset(
$_SESSION["auth"]) || isset($_SERVER["HTTPS"]) ) define('CMS_URL',CMS_URL_SSL); else define('CMS_URL',CMS_URL_PLAIN);

/* ################################################################################### UGLY DEFINES ######################################################################################################################################################################################################################################################################################## */
/* -( ---------------------------------------------- )- */                                            
define 'CMS_VERSION',        '1.0.0-b6042' );
/* -(  - mCMS COR3 - t3h m157y CMS in 303 lines    - )- */ if ( isset($_SERVER['QUERY_STRING']) ) { define 'CMS_REQUEST',     urldecode(str_replace('?'.$_SERVER['QUERY_STRING'],'',$_SERVER['REQUEST_URI'])));
/* -( ---------------------------------------------- )- */                                   } else { define 'CMS_REQUEST',     urldecode($_SERVER['REQUEST_URI']) ); };
/* -( - (c)2006-2007 Sebastian Glaser              - )- */                                             define 'CMS_TEMP',         CMS_ROOT.'.cache/');
/* -( - (c)2006-2007 Konrad Meyendrisch            - )- */                                            define 'CMS_INCL',         CMS_ROOT.'.modules/');
/* -( ---------------------------------------------- )- */                                             define 'CMS_LOCAL',          realpath(CMS_ROOT.dirname(CMS_REQUEST)).'/' );
/* -( ---------------------------------------------- )- */                                             define 'CMS_LOCAL_REL',      dirname(CMS_REQUEST).'/' );
/* -( - Creative Commons [[BY NC ND]]              - )- */                                            define 'CMS_LOCAL_URL',    str_replace(CMS_URL.'/',CMS_URL,str_replace(CMS_URL.'/',CMS_URL,CMS_URL.str_replace("//","/",dirname(CMS_REQUEST)."/"))) );
/* -( ---------------------------------------------- )- */                                             define 'CMS_LOCAL_INC',   realpath(CMS_ROOT.dirname(CMS_REQUEST).'/.modules/') );
/* -( -                                            - )- */                                             define 'CMS_FILE',         realpath(CMS_ROOT.CMS_REQUEST) );
/* -( - a holistic, extensible diectory viewer in  - )- */                                             define 'CMS_FILE_URL',     CMS_URL.CMS_REQUEST );
/* -( - php, strangely always around 303 lines (1) - )- */                                             $MACRO['name'] =             CMS_NAME;
/* -( -                                            - )- */                                             $MACRO['endsieg_date'] =     date('H:i D, y-m-d \W\e\e\k: W',time());
/* -( -                                            - )- */                                             $MACRO['title'] =             'mCMS';
/* -( -                                            - )- */                                             $MACRO['root_url'] =        CMS_URL;
/* -( -                                            - )- */                                             $MACRO['file_url'] =        CMS_URL;
/* -( -                                            - )- */                                             $MACRO['cms_local_url'] =        CMS_URL;
/* -( -                                            - )- */                                             $MACRO['cms_head'] =        '';
/* -( -                                            - )- */                                             $MACRO['language'] =        CMS_LANGUAGE;
/* -( -                                            - )- */                                             define('MOD_XHTML_TEMPLATE','.template');
/* -( -                                            - )- */                                             $GLOBALS['ALIAS']['[[BR]]']        = '[[xhtml|br]]';
/* -( -                                            - )- */                                             $GLOBALS['ALIAS']['[[EXTERN|']    = '[[xhtml|extern|';
/* -( -                                            - )- */                                             $GLOBALS['ALIAS']['[[LINK|']    = '[[xhtml|extern|title:';
/* -( -                                            - )- */                                             $GLOBALS['ALIAS']['[[IMG|']        = '[[xhtml|image|src:';
/* -( ---------------------------------------------- )- */                                             $_SERVER['QUERY_STRING'] = urldecode($_SERVER['QUERY_STRING']);
/* ###################################################################################### INIT mCMS ######################################################################################################################################################################################################################################################################################## */
    
$instances = array();
    
$modules = array();
    
$virtual = array();
    
$mCMS_int = array();
    
$mCMS_list = array();

    
mCMS_init(array('insert'));
    echo 
mCMS_handle_request();
    exit(
0);
/* ############################################################################################ LIB ######################################################################################################################################################################################################################################################################################## */
                                
function optimism() { return true; }                                // pretty important! reflects the optimistic attitude of ths CMS.            
                                
function pessimism() { return !optimism(); }                        // optimistic definition of the negative, there is still optimism in pessimism!
                                
function mood() { return optimism() or pessimism(); }
/* PHP_BACKWARD_COMPAT<5.1 */    # function array_diff_key() { $args = func_get_args(); return array_flip(call_user_func_array('array_diff',array_map('array_flip',$args))); }
                                
function mCMS_get_file($filename$incpath false$resource_context null,$offset=NULL,$length=NULL) {
                                    if (
false === $fh fopen($filename'rb')) {
                                        
user_error('mCMS_get_file() failed to open stream: No such file or directory'E_USER_WARNING);
                                        return 
false; }
                                    
clearstatcache();
                                    if (
$fsize = @filesize($filename)) {
                                        if (
$length != NULL) if ( $length $fsize $fsize $length;
                                        if (
$offset != NULL) if ( $offset $fsize fread($fh,$offset);
                                        
$data fread($fh$fsize); }
                                    else {    
$data '';
                                        while (!
feof($fh)) {
                                        
$data .= fread($fh8192); } }
                                    
fclose($fh);
                                    return 
$data;}
/* PHP_LACK */                    function mCMS_htmlnumericentities($str) { return preg_replace('/[^!-%\x27-;=?-~ ]/e''"&#".ord("$0").chr(59)'$str); } function numericentitieshtml($str){ return utf8_encode(preg_replace('/&#(\d+);/e''chr(str_replace(";","",str_replace("&#","","$0")))'$str)); }
                                function 
mCMS_getsuffix($name) { $file_array=split("\.",$name); $suffix=$file_array[count($file_array)-1]; if(strlen($suffix)>0){ return $suffix; } else { return pessimism(); } }
                                function 
mCMS_globr ($sDir$sPattern$nFlags NULL$depth 5$x 0) { $sDir realpath($sDir); $sDir escapeshellcmd($sDir); $aFiles glob($sDir.'/'.$sPattern,$nFlags); if ($x $depth) foreach (glob("$sDir/*"GLOB_ONLYDIR) as $sSubDir) { $aSubFiles mCMS_globr($sSubDir$sPattern$nFlags$depth$x++); $aFiles array_merge($aFiles$aSubFiles); } return $aFiles; }
/* PHP_WORKAROUND */            function mCMS_basename($f) {
                                        return 
array_pop(split('/',$f));
                                    }
    
/* ################################################################################ mCMS Functional ######################################################################################################################################################################################################################################################################################## */
function mCMS_init ($virt=array()) {
    global 
$instances$modules$virtual$mCMS_int$mCMS_list;    
    foreach ( 
$virt as $v ) {$virtual[$v] = true$modules[$v] = 'virtual';} // Load virtual modules
    
$GLOBALS['mCMS_html_encode'] = array_diff_key(get_html_translation_table(HTML_ENTITIES),get_html_translation_table(HTML_SPECIALCHARS));
    
$fl = array();                                                                            // Load basic DATABASE
    
$fl array_merge($fl,glob(CMS_ROOT.'.mCMS.db/*.integer'));
    
$fl array_merge($fl,glob(CMS_ROOT.'.mCMS.db/*.list'));
    
$fl array_merge($fl,glob(CMS_LOCAL.'.mCMS.db/*.integer'));
    
$fl array_merge($fl,glob(CMS_LOCAL.'.mCMS.db/*.list'));
    
$fl array_unique($fl);
    foreach ( 
$fl as $f ) {
        if (
preg_match('/\.integer/',$f)) {
            
$t str_replace('.integer','',basename($f));
            
$mCMS_int[$t] = file_get_contents($f);}
        elseif (
preg_match('/\.list/',$f)) {
            
$t str_replace('.list','',basename($f));
            
$mCMS_list[$t] = split("\n",file_get_contents($f)); } }
    
$tmp mCMS_globr(CMS_INCL,"mod_*.php",NULL,1);                                            // Generate an index of available modules
    
if (CMS_LOCAL != CMS_ROOT$tmp array_merge($tmp,mCMS_globr(CMS_INCL,"mod_*.php",NULL,1));
    foreach (
$tmp as $k => $v) { //echo("<p/>$k $v ".basename($v)).' '.str_replace(".php","",str_replace("mod_","",basename($v)));
    
$modules[str_replace(".php","",str_replace("mod_","",basename($v)))]['path'] = $v; } }

function 
mCMS_handle_request () {                                                                    // SERVES ANY FILE EXISTING NOT OVERLOADED BY A MODULE -> TRIES TO LOAD MOD ERROR -> (THEN RESORTS TO DIRECTORY BROWSWER WITH 404 -OR- DIES WITH MINIMAL 404 PAGE)
    
global $instances$modules$virtual;
    
$suffix mCMS_getsuffix(CMS_REQUEST); $stdin NULL;        //die($suffix);                                        
    
if ( !isset($modules[$suffix]) ) {
            die(  
"mCMS::-(COULD NOT SERVE)-($suffix)-"  );
            }                        
    elseif( isset(
$modules[$suffix]) ) {                                                //die('wrm'.$suffix);// The famous CHAIN OF COMMAND(s) rolled up from left to right
            
$stack split('\.',mCMS_basename(CMS_REQUEST)); $prefix=NULL
            if ( 
count($stack) > ) {
                if ( isset(
$stack[0]) ) {
                    if ( 
$stack[0] != '' ) { $index $stack[0]; if ( !mCMS_trymod($index) ) array_shift($stack); }
                    if ( 
count($stack) > ) die("lol, attack");
                    if ( 
$stack[0] == '' ) die("access denied");
                    
$files array_merge(glob(CMS_LOCAL.$index.'*.*'),glob(CMS_LOCAL.'archive/'.$index.'*.*')); $previous $index;    
                    foreach ( 
$stack as $command ) {                                                 // echo("<p />CHAIN_OF_COMMAND: $command, -($previous)-");
                        
if ( mCMS_trymod($command) ) { $stdin $GLOBALS[$command]->actions($suffix,$files,$stdin,$index,$previous); }
                        else { 
user_error("CHAIN_OF_COMMAND: $command failed, -($previous)-"E_USER_WARNING); }
                        
$previous=$command; }
                    return 
$stdin; } }
            else { die(
'mCMS::-(THE CHAIN OF COMMAND FAILED)-(makes no sense)-'); } }
    elseif ( 
mCMS_reqmod('xhtml') && file_exists(CMS_LOCAL.'index.xhtml') )    {    return $GLOBALS['xhtml']->actions(CMS_LOCAL.'index.xhtml'); }
    elseif ( 
mCMS_reqmod('xhtml') && file_exists(CMS_ROOT.'index.xhtml') )    {    return $GLOBALS['xhtml']->actions(CMS_ROOT.'index.xhtml'); }
    elseif ( 
mCMS_trymod('error') ) { }
    else {                                                                                             die(
'<html><head><title>mCMS - 404 - '.CMS_REQUEST.'</title></head><body><h1>mCMS -(ERROR: 404)-</h1><hr>An error occured processing your request <b>-('.CMS_REQUEST.')-</b><br>This might be due to the fact that the file does NOT exist, or mCMS could not answer your request - possibly a missing module.<hr></body></html>'); } }

function 
mCMS_integer_set ($name,$value,$path=NULL) {
    if ( 
$path NULL $path CMS_LOCAL.'.mCMS.db/'.$name.'.integer';
    if ( 
file_exists($path) ) { $h fopen($path,'w'); } else { $h fopen(CMS_ROOT.'.mCMS.db/'.$name.'.integer','w'); }
    
fwrite($h,$value);
    
fclose($h); }

function 
mCMS_list_set($name,$value=NULL,$path=NULL) { global $mCMS_list;
    if ( !
is_dir(CMS_LOCAL.'.mCMS.db') ) if (!mkdir(CMS_LOCAL.'.mCMS.db')) return '-(mCMS_core: Could not create local database dir)-';
    if ( !
file_exists(CMS_LOCAL.'.mCMS.db/'.$name.'.list') && !is_file(CMS_LOCAL.'.mCMS.db/'.$name.'.list') ) if (!touch(CMS_LOCAL.'.mCMS.db/'.$name.'.list')) return '-(mCMS_core: Could not create local database dir)-';
    if ( 
$path == NULL $path CMS_LOCAL.'.mCMS.db/'.$name.'.list';
    if ( 
$value == NULL$value $mCMS_list[$name];                                                //echo ( "<p>list_set( $name , $value =NULL, $path =NULL)" );
    
if ( file_exists($path) ) { $h fopen($path,'w'); } else { $h fopen($path,'w'); }
    
fwrite($h,implode("\n",$value));
    
fclose($h); }

function 
mCMS_trymod $m $init true $mode NULL ) {                                            // echo("<p /> mCMS_reqmod -($m)- -($mode)-");
    
global $instances$modules$virtual;
    
$m strtolower($m);
    if ( isset(
$virtual[$m]) ) {
        if (
$init && !isset($GLOBALS[$m]) ) $GLOBALS[$m] = new $m($mode);
        return 
optimism(); }
    elseif ( isset(
$modules[$m]) ) {
        include_once(
$modules[$m]['path']);
        if (
$init && !isset($GLOBALS[$m]) ) $GLOBALS[$m] = new $m($mode);
        return 
optimism(); }
    else { return 
pessimism(); } }

function 
mCMS_reqmod $m $init true $mode NULL ) {                                        // FIXME: throw error
    
if ( mCMS_trymod($m,$init,$mode) ) { return optimism(); }
    else {    die(
"REQUIRED MODULE ($m) NOT FOUND!"); } }

function 
mCMS_parse ($t,$postcache=false) {
    if ( isset(
$GLOBALS['ALIAS']) ) foreach ( $GLOBALS['ALIAS'] as $s => $r) { $t str_replace($s,$r,$t); }
    if ( 
$postcache ) {
        
$t preg_replace_callback("/{{(.*[^}])}}/",'mCMS_parse_macro',$t);    
        return 
$t; }
    else {
        
$t preg_replace_callback("/\[\[([\s\S]*?[^\]])]\]/",'mCMS_parse_macro',$t);    
        return 
$t; } }

function 
mCMS_parse_macro($match) {
    global 
$instances$modules$virtual;
    
$orig array_shift($match);
    
$comm array_shift($match);                                                                // echo("<p />-($comm)- is... ");
    
$index array_shift(split('\.',mCMS_basename(CMS_REQUEST)));
    
$files array_merge(glob(CMS_LOCAL.$index.'*.*'),glob(CMS_LOCAL.'archive/'.$index.'*.*'));
    if ( isset(
$GLOBALS['MACRO'][strtolower($comm)]) ) {                                        // echo("<p />a macro -($comm)-");
        
return $GLOBALS['MACRO'][strtolower($comm)]; }
    if ( 
mCMS_trymod($comm) ) {                                                    // echo("<p />a module -($comm)-");
        
return $GLOBALS[strtolower($comm)]->actions(); }
    
$args split('\|',$comm);
    if (
is_array($args)) {
            
$comm array_shift($args);
            
$mode array_shift($args); }
    elseif (isset(
$args)) {
        
$mode $args; }
    if ( isset(
$modules[strtolower($comm)]) ) {                                            // echo("a complex module call, ".realpath(CMS_ROOT.$mode).' '); 
        
if ( isset($mode) ) if ( is_dir(CMS_ROOT.$mode) ) {                                        // echo("a global instance of a module -($mode)-");
            
if ( !isset($instances[strtolower($comm)][$mode]) ) {                                    // echo("<p /> - needs to be instantiated -($comm, $mode)-");
                
mCMS_reqmod($comm,false);
                
$instances[strtolower($comm)][$mode] = new $comm($mode);
                return 
$instances[strtolower($comm)][$mode]->actions($mode,$args,NULL,$index,$files); }
            else {                                                                                 
// echo("already instantiated -($comm, $mode)-");
                
return $instances[strtolower($comm)][$mode]->actions($mode,$args,NULL,$index,$files); } }
        elseif (isset(
$virtual[$comm])) {                                        // echo("a virtual module -($comm, $mode)-");
            
return $GLOBALS[strtolower($comm)]->actions($mode,$args,NULL,$index); }
        else {                                                                                    
// echo("a static module -($comm, $mode)-");
            
if ( mCMS_reqmod($comm,true,$mode) ) return $GLOBALS[strtolower($comm)]->actions($mode,$args,NULL,$index,$files); } }
    return 
$orig; }

class 
insert {    
    function 
actions ($context,$files,$stdin=NULL,$index=NULL,$previous=NULL) {
        
$file CMS_LOCAL.$context;
        if (
file_exists($file)) {
            
$name str_replace('.xhtml','',mCMS_basename($context));
            return 
$GLOBALS['xhtml']->section($name,mCMS_parse(file_get_contents($context)),false,'h1',$file);
        } elseif (
file_exists(CMS_ROOT.$context)) {
            
$name str_replace('.xhtml','',mCMS_basename($context));
            return 
$GLOBALS['xhtml']->section($name,mCMS_parse(file_get_contents($context)),false,'h1',CMS_ROOT.$context);
        }
}}
?>
1