HTML/FlexyFramework.php
[pear] / HTML / FlexyFramework.php
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4: */
3 // +----------------------------------------------------------------------+
4 // | PHP Version 4                                                        |
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1997-2002 The PHP Group                                |
7 // +----------------------------------------------------------------------+
8 // | This source file is subject to version 2.02 of the PHP license,      |
9 // | that is bundled with this package in the file LICENSE, and is        |
10 // | available at through the world-wide-web at                           |
11 // | http://www.php.net/license/2_02.txt.                                 |
12 // | If you did not receive a copy of the PHP license and are unable to   |
13 // | obtain it through the world-wide-web, please send a note to          |
14 // | license@php.net so we can mail you a copy immediately.               |
15 // +----------------------------------------------------------------------+
16 // | Authors:  Alan Knowles <alan@akbkhome.com>                           |
17 // +----------------------------------------------------------------------+
18 //
19 // $Id: FlexyFramework.php,v 1.8 2003/02/22 01:52:50 alan Exp $
20 //
21 //  Description
22 //  A Page (URL) to Object Mapper
23 //  Cleaned up version.. - for use on new projects -- not BC!! beware!!!
24
25
26 //-----------------------------------------------------------
27 // Debian APACHE - some idiot disabled AcceptPathInfo - it needs adding back.
28 //-----------------------------------------------------------
29
30  
31  
32 // Initialize Static Options
33 require_once 'PEAR.php';
34 require_once 'HTML/FlexyFramework/Page.php';  
35 require_once 'HTML/FlexyFramework/Error.php';
36 // better done here..
37 require_once 'DB/DataObject.php';
38
39 // To be removed ?? or made optional or something..
40  
41
42 // remove E_ANAL  
43  
44 error_reporting(E_ALL & ~E_STRICT );
45 //ini_set('display_errors','off');
46 //ini_set('log_errors','off');
47
48 //PEAR::setErrorHandling(PEAR_ERROR_TRIGGER, E_USER_ERROR);
49
50
51
52
53 /**
54 * The URL to Object Mapper
55 *
56 * Usage:
57 * Create a index.php and add these lines.
58 *  
59 * ini_set("include_path", "/path/to/application"); 
60 * require_once 'HTML/FlexyFramework.php';
61 * HTML_FlexyFramework::factory(array("dir"=>"/where/my/config/dir/is");
62 *
63 *
64 * the path could include pear's path, if you dont install all the pear 
65 * packages into the development directory.
66 *
67 * It attempts to load a the config file from the includepath, 
68 * looks for ConfigData/default.ini
69 * or ConfigData/{hostname}.ini
70 * if your file is called staging.php rather than index.php 
71 * it will try staging.ini
72 *
73 */
74  
75 class HTML_FlexyFramework {
76     
77     /**
78      * Confirgurable items..
79      * If we set them to 'true', they must be set, otherwise they are optional.
80      */
81     var $project; // base class name
82     var $database; // set to true even if nodatabase=true
83     
84     // optional
85     var $debug = false;
86     var $enable = false; // modules
87     var $disable = false; // modules or permissions
88     var $appName = false;
89     var $appNameShort = false; // appname (which has templates)
90     var $version = false; // give it a version name. (appended to compile dir)
91     var $nodatabase = false; // set to true to block db config and testing.
92     var $fatalAction = false; // page to redirct to on failure. (eg. databse down etc.)
93     var $charset = false; // default UTF8
94     var $dataObjectsCache = true;  // use dataobjects ini cache.. - let's try this as the default behaviour...
95     var $dataObjectsCacheExpires = 72000; // 20 hours..
96     var $languages = false; // language settings -- see _handlelanguage
97     var $projectExtends = false; // if this is an array, it's a fallback of 'Projects' that can be called
98     
99
100     
101     // derived.
102     var $cli = false; // from cli 
103     var $run = false; // from cli
104     var $enableArray = false; // from enable.
105     var $classPrefix = false; // from prject.
106     var $baseDir = false ; // (directory+project)
107     var $rootDir = false ; // (directory that index.php is in!)
108     
109     var $baseURL = false;
110     var $rootURL = false ; // basename($baseURL)
111     
112     var $page = false; // active page..
113     var $timer = false; // the debug timer
114     var $calls = false; // the number of calls made to run!
115     var $start = false; // the start tiem.
116     
117     var $baseRequest = '';
118     var $ext; // the striped extention.
119     
120     var $dataObjectsOriginalIni = ''; // 1 houre..
121     
122     // used to be $_GLOBALS[__CLASS__]
123     
124     static $singleton; 
125     
126     
127     /**
128      * 
129      * Constructor - with assoc. array of props as option
130      * called by index.php usually, and runs the app code,
131      *
132      * uses 'universal construcor' format, so the argument relates directly to properties of this object.
133      * 
134      */
135     
136     
137     function __construct($config)
138     {
139         if (isset(self::$singleton)) {
140             trigger_error("FlexyFramework Construct called twice!", E_ERROR);
141         }
142         
143         self::$singleton = $this;
144         
145         $this->calls = 0;
146
147         $m = explode(' ',microtime());
148         $this->start = $m[0] + $m[1];
149         
150         $config = $this->loadModuleConfig($config);
151         
152         foreach($config as $k=>$v) {
153             $this->$k = $v;
154         }
155         $this->_parseConfig();
156         
157         // echo '<PRE>'; print_r($this);exit;
158         if ($this->cli) {
159             $args = $_SERVER['argv'];
160             array_shift($args );
161             array_shift($args );
162             $this->_run($this->run,false,$args);
163             return;
164         }
165     
166         // handle apache mod_rewrite..
167         // it looks like this might not work anymore..
168         
169         /*
170          *
171 <IfModule mod_rewrite.c>
172 RewriteEngine On
173 RewriteBase /
174 RewriteRule ^/web.hpasite/index\.local.php$ - [L]
175 RewriteCond %{REQUEST_FILENAME} !-f
176 RewriteCond %{REQUEST_FILENAME} !-d
177 RewriteRule ^(.+)$ /web.hpasite/index.local.php [L,NC,E=URL:$1]
178 </IfModule>
179 */ 
180         
181         if (!empty($_SERVER['REDIRECT_STATUS'])  && !empty($_SERVER['REDIRECT_URL'])) {
182           // phpinfo();exit;
183             $sn = $_SERVER['SCRIPT_NAME'];
184             $sublen = strlen(substr($sn , 0,  strlen($sn) - strlen(basename($sn)) -1));
185             //var_dump(array($sn,$subdir,basename($sn)));exit;
186           
187             //var_dump($_SERVER['SCRIPT_NAME'] . substr($_SERVER['REDIRECT_URL'],$sublen));
188             $this->_run($_SERVER['SCRIPT_NAME'] .  substr($_SERVER['REDIRECT_URL'], $sublen),false);
189             return ;
190         }
191         // eg... /web.hpasite/index.local.php/Projects
192          $this->_run($_SERVER['REQUEST_URI'],false);
193             
194         
195     }
196     /**
197      * This is the standard way to get information about the application settings.
198      * $ff = HTML_FlexyFramework::get();
199      * if ($ff->SomeVar[...])....
200      *
201      */
202     static function get()
203     {
204         return self::$singleton;
205     }
206     /*
207      * looks for files in the path and load up the default values for config?
208      */
209     function loadModuleConfig($cfg)
210     {
211         if (empty($cfg['enable'])) {
212             return $cfg;
213         }
214         $proj = $cfg['project'];
215         $rootDir = realpath(dirname($_SERVER["SCRIPT_FILENAME"]));
216
217         foreach(explode(',',$cfg['enable']) as $m) {
218             $cls = $proj.'_'. $m . '_Config';
219
220             if (!file_exists($rootDir . '/'.str_replace('_','/', $cls). '.php')) {
221                 continue;
222             }
223             require_once str_replace('_','/', $cls). '.php';
224             $c = new $cls();
225             if (method_exists($c,'init')) {
226                 $cfg = $c->init($this,$cfg);
227             }
228         }
229         return $cfg;
230     }
231     
232   
233     /**
234      * parse the configuration set by the constructor.
235      * 
236      *
237      */
238   
239     function _parseConfig()
240     {
241         
242         // make sure required values are set.. (anything that is not defaulted to false..)
243         foreach(get_class_vars(__CLASS__) as $k =>$v) {
244             if ($v === false && !isset($this->$k)) {
245                 die("$k is not set");
246             }
247         }
248         
249         
250         // enable modules.
251         if (!empty($this->enable)) {
252             $this->enableArray = explode(',', $this->enable);
253             
254             if (!in_array('Core',$this->enableArray ) &&
255                 !in_array('Core', explode(',', $this->disable ? $this->disable : '')))
256             {
257                 $this->enable = 'Core,'. $this->enable ;
258                 $this->enableArray = explode(',', $this->enable);
259             }
260         }
261         // are we running cli?
262         $this->cli = php_sapi_name() == 'cli'; 
263         
264         // will these work ok with cli?
265         $bits = explode(basename($_SERVER["SCRIPT_FILENAME"]), $_SERVER["SCRIPT_NAME"]);
266         if (!$this->cli) {
267             $bits[0] = str_replace('%2F','/',urlencode($bits[0]));
268             $this->baseURL = $bits[0] . basename($_SERVER["SCRIPT_FILENAME"]);
269             // however this is not correct if we are using rewrite..
270             if (!empty($_SERVER['REDIRECT_STATUS'])  && !empty($_SERVER['REDIRECT_URL'])) {
271                 $this->baseURL = substr($bits[0],0,-1); // without the trailing '/' ??
272                 $this->rootURL = $bits[0] == '/' ? '' : $bits[0];
273                 //$this->baseURL = $this->baseURL == '' ? '/' : $this->baseURL;
274                 
275             }
276             //phpinfo();exit;
277             // is this bit used??
278             //if (empty($_SERVER['SCRIPT_NAME'])) {
279                 
280             //    $this->baseURL = ''; // ??? this is if we replace top level...
281             //}
282         }
283         // if cli - you have to have set baseURL...
284         
285         
286         $this->rootDir = realpath(dirname($_SERVER["SCRIPT_FILENAME"]));
287         $this->baseDir = $this->rootDir .'/'. $this->project;
288         if (empty($this->rootURL)) {
289             $this->rootURL = dirname($this->baseURL); 
290             $this->rootURL = ($this->rootURL == '/') ? '' : $this->rootURL;
291         }
292          
293       
294         //var_dump($this->baseURL);
295         
296         if (!isset($this->database) && isset($this->DB_DataObject['database'])) {
297             $this->database = $this->DB_DataObject['database'];
298         }
299         
300          $this->classPrefix   = str_replace('/', '_', $this->project) . '_';
301         
302         // list the available options..
303         if ($this->cli && empty($_SERVER['argv'][1])) {
304             require_once 'HTML/FlexyFramework/Cli.php';
305             $fcli = new HTML_FlexyFramework_Cli($this);
306             $fcli->cliHelp();
307             exit;
308         }
309         
310         
311         // see if it's a framework assignment.
312         $ishelp = false;
313         if ($this->cli) {
314             require_once 'HTML/FlexyFramework/Cli.php';
315             $fcli = new HTML_FlexyFramework_Cli($this);
316             $res = $fcli->parseDefaultOpts();
317             if ($res === true) {
318                 $ishelp = true;
319             } 
320              
321         }
322         
323         
324         $this->run = $this->cli ? $_SERVER['argv'][1] : false;
325      
326         
327         $this->_parseConfigDataObjects();
328         if ($this->dataObjectsCache && !$this->nodatabase) {
329             $this->_configDataObjectsCache();
330         }
331         
332         $this->_parseConfigTemplate();
333         $this->_parseConfigMail();
334  
335         //echo '<PRE>';print_r($this);exit;
336         
337         $this->_exposeToPear();
338                 
339
340         $this->_validateEnv();
341         
342         if ($ishelp) {
343             return;
344         }
345
346         $this->_validateDatabase();
347  
348         $this->_validateTemplate();
349         
350     }
351     /**
352      *
353      *
354      *'languages' => array(
355             'param' => '_lang',
356             'avail' => array('en','zh_HK', 'zh_CN'),
357             'default' => 'en',
358             'cookie' => 'TalentPricing_lang',
359             'localemap' => array(
360                 'en' => 'en_US.utf8',
361                 'zh_HK' => 'zh_TW.utf8',
362                 'zh_CN' => 'zh_CN.utf8',
363             )
364         ),
365     */
366     
367     function _handleLanguages($request)
368     {
369         if (
370             empty($this->languages) ||
371             (
372                     !isset($this->languages['cookie']) && !isset($this->languages['default'])
373             )
374         ) {
375             return;
376         }
377         
378         $cfg = $this->languages;
379         
380         $default = $cfg['default'];
381         
382         if(!empty($_SERVER["HTTP_ACCEPT_LANGUAGE"])){
383             
384             $brower_langs = explode(",", $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
385             
386             foreach ($brower_langs as $bl) {
387                 $l = preg_replace('/;(.*)/', '', $bl);
388                 
389                 $l = str_replace('-', '_', $l);
390                 
391                 if(!in_array($l, $cfg['avail'])){
392                     continue;
393                 }
394                 
395                 $default = $l;
396                 break;
397             }
398         }
399            
400         $lang = isset($_COOKIE[$cfg['cookie']]) ?  $_COOKIE[$cfg['cookie']] : $default;
401
402         // handle languages in request..
403         $bits = explode('/', $request);
404         $redirect_to = false;
405         if (count($bits) && in_array($bits[0],$this->languages)) {
406             // redirect..
407             $lang = array_shift($bits);
408             
409             $redirect_to = implode('/', $request);
410             
411         }
412         
413         
414         
415         
416         
417         
418         if (isset($_REQUEST[$cfg['param']])) {
419             $lang = $_REQUEST[$cfg['param']];
420         }
421     
422         if (!in_array($lang, $cfg['avail'])) {
423             $lang = $cfg['default'];
424         }
425         if (isset($cfg['localemap'][$lang])) {
426             setlocale(LC_ALL, $cfg['localemap'][$lang]);
427         }
428         setcookie($cfg['cookie'], $lang, 0, '/');
429         
430         $this->locale = $lang;
431         
432         if (!empty($this->HTML_Template_Flexy)) {
433             $this->HTML_Template_Flexy['locale'] = $lang;   //set a language for template engine
434         }
435         if ($redirect_to !== false) {
436             header('Location: ' . $this->rootURL . '/'.$redirect_to );
437             exit;
438          
439         }
440     }
441     
442     function parseDefaultLanguage($http_accept, $deflang = "en") 
443     {
444         if(isset($http_accept) && strlen($http_accept) > 1)  {
445            # Split possible languages into array
446            $x = explode(",",$http_accept);
447            
448            foreach ($x as $val) {
449               #check for q-value and create associative array. No q-value means 1 by rule
450               if(preg_match("/(.*);q=([0-1]{0,1}.\d{0,4})/i",$val,$matches))
451                  $lang[$matches[1]] = (float)$matches[2];
452               else
453                  $lang[$val] = 1.0;
454            }
455            
456            #return default language (highest q-value)
457            $qval = 0.0;
458            foreach ($lang as $key => $value) {
459               if ($value > $qval) {
460                  $qval = (float)$value;
461                  $deflang = $key;
462               }
463            }
464         }
465         return strtolower($deflang);
466      }
467     
468     /**
469      * overlay array properties..
470      */
471     
472     function applyIf($prop, $ar) {
473         if (!isset($this->$prop)) {
474             $this->$prop = $ar;
475             return;
476         }
477         // add only things that where not set!!!.
478         $this->$prop = array_merge($ar,$this->$prop);
479         
480         return;
481         //foreach($ar as $k=>$v) {
482         //    if (!isset($this->$prop->$k)) {
483          //       $this->$prop->$k = $v;
484           //  }
485        // }
486     }
487     
488     /**
489      * DataObject cache 
490      * - if turned on (dataObjectsCache = true) then 
491      *  a) ini file points to a parsed version of the structure.
492      *  b) links.ini is a merged version of the configured link files.
493      * 
494      * This only will force a generation if no file exists at all.. - after that it has to be called manually 
495      * from the core page.. - which uses the Expires time to determine if regeneration is needed..
496      * 
497      * 
498      */
499     
500     function _configDataObjectsCache()
501     {
502         // cli works under different users... it may cause problems..
503         $this->debug(__METHOD__);
504         if (function_exists('posix_getpwuid')) {
505             $uinfo = posix_getpwuid( posix_getuid () ); 
506             $user = $uinfo['name'];
507         } else {
508             $user = getenv('USERNAME'); // windows.
509         }
510         
511         
512
513         $iniCache = ini_get('session.save_path') .'/' . 
514                'dbcfg-' . $user . '/'. str_replace('/', '_', $this->project) ;
515         
516         
517         if ($this->appNameShort) {
518             $iniCache .= '_' . $this->appNameShort;
519         }
520         if ($this->version) {
521             $iniCache .= '.' . $this->version;
522         }
523         if ($this->database === false) {
524             return;
525         }
526         
527         $dburl = parse_url($this->database);
528         if (!empty($dburl['path'])) {
529             $iniCache .= '-'.ltrim($dburl['path'],'/');
530         }
531         
532         $iniCache .= '.ini';
533         $this->debug(__METHOD__ . " : ini cache : $iniCache");
534         
535         $dburl = parse_url($this->database);
536         $dbini = 'ini_'. basename($dburl['path']);
537         $this->debug(__METHOD__ . " : ini file : $dbini");
538         //override ini setting... - store original..
539         if (isset($this->DB_DataObject[$dbini])) {
540             $this->dataObjectsOriginalIni = $this->DB_DataObject[$dbini];
541             ///print_r($this->DB_DataObject);exit;
542         }
543         // 
544         
545         
546         
547         $this->DB_DataObject[$dbini] =   $iniCache;
548         // we now have the configuration file name..
549         
550         
551         if (!file_exists($iniCache) || empty( $this->dataObjectsCacheExpires)) {
552             $this->generateDataobjectsCache(true);
553             return;
554         }
555      
556         
557         
558     }
559     /**
560      *  _generateDataobjectsCache:
561      * 
562      * create xxx.ini and xxx.links.ini 
563      * 
564      * @arg force (boolean) force generation - default false;
565      * 
566      */
567      
568     function generateDataobjectsCache($force = false)
569     {
570         //$this->debug('generateDataobjectsCache: force=' . ($force ? 'yes' : 'no'));
571         if (!$this->dataObjectsCache) { // does not use dataObjects Caching..
572             $this->debug('generateDataobjectsCache', 'dataObjectsCache - empty');
573             return;
574         }
575         
576         $dburl = parse_url($this->database);
577         $dbini = 'ini_'. basename($dburl['path']);
578         
579         
580         $iniCache = $this->DB_DataObject[$dbini];
581         if ($force && file_exists($iniCache)) {
582             unlink($iniCache);
583             clearstatcache();
584         }
585         
586         $iniCacheTmp = $iniCache . '.tmp' .md5(rand());  // random to stop two processes using the same file.
587         // has it expired..
588         $force = ($force ? $force : !file_exists($iniCache)) || !$this->dataObjectsCacheExpires;
589         // $this->debug('generateDataobjectsCache: after check : force=' . ($force ? 'yes' : 'no'));
590          // not force or not expired, do not bother..
591         if (!$force) {
592             if ((filemtime($iniCache) + $this->dataObjectsCacheExpires) >time()) {
593                 return;
594             }
595         }
596         
597         
598         
599          //echo "GENERATE?";
600         
601         // force quoting of column names..
602         // unless it forced off..
603         if (!isset($this->DB_DataObject['quote_identifiers_tableinfo'] )) { 
604             $this->DB_DataObject['quote_identifiers_tableinfo'] = true;
605         }
606         if (!file_exists(dirname($iniCache))) {
607             if (!mkdir(dirname($iniCache),0700, true)) {
608                 die("Failed to make cache directory : $iniCache\n");
609             }
610         }
611         
612         $this->DB_DataObject[$dbini] = $iniCacheTmp;
613         $this->_exposeToPear();
614         
615         
616         // DB_DataObject::debugLevel(1);      
617         require_once 'HTML/FlexyFramework/Generator.php';
618         $generator = new HTML_FlexyFramework_Generator();
619         $generator->start();
620         
621         HTML_FlexyFramework_Generator::writeCache($iniCacheTmp, $iniCache); 
622         // reset the cache to the correct lcoation.
623         $this->DB_DataObject[$dbini] = $iniCache;
624         $this->_exposeToPear();
625         
626         //$GLOBALS['_DB_DATAOBJECT']['INI'][$this->database] =   parse_ini_file($iniCache, true);
627         //$GLOBALS['_DB_DATAOBJECT']['SEQUENCE']
628         // clear any dataobject cache..
629          
630         
631         //die("done");
632         
633     }
634     /**
635      * DataObject Configuration:
636      * Always in Project/DataObjects
637      * unless enableArray is available...
638      * 
639      * 
640      * 
641      */
642     function _parseConfigDataObjects()
643     {
644         if ($this->nodatabase && !$this->database) {
645             return;
646         }
647         $dburl = parse_url($this->database);
648         $dbini = 'ini_'. basename($dburl['path']);
649                 
650         $dbinis =  array(); //array(dirname(__FILE__) . '/Pman/DataObjects/pman.ini');
651         $dbreq =  array(); //array( dirname(__FILE__) . '/Pman/DataObjects/');
652         $dbcls =  array(); //array('Pman_DataObjects_');
653
654         $project = explode('/',$this->project)[0]; 
655         
656         if (!empty($this->enableArray)) {
657                 
658             $tops = array_merge( array($project), empty($this->projectExtends) ? array() : $this->projectExtends);
659             
660             foreach($tops as $td) {
661                     
662                 $bd = $this->rootDir .'/'.$td;
663                 foreach($this->enableArray as $m) {
664                     // look in Pman/MODULE/DataObjects/*
665                      if (file_exists($bd.'/'.$m.'/DataObjects')) {
666                         $dbinis[] = $bd.'/'.$m.'/DataObjects/'. strtolower($project).'.ini';
667                         $dbcls[] = $td.'_'. $m . '_DataObjects_';
668                         $dbreq[] = $bd.'/'.$m.'/DataObjects';
669                         continue;
670                     }
671                     // look in MODULE/DataObjects ?? DO WE SUPPORT THIS ANYMORE???
672                     if (file_exists($bd.'/../'.$m.'/DataObjects')) {
673                         $dbinis[] = $bd.'/../'.$m.'/DataObjects/'. strtolower($project).'.ini';
674                         $dbcls[] = $td. '_DataObjects_';
675                         $dbreq[] = $bd.'/../'.$m.'/DataObjects';
676                     }
677                         
678                         
679                       
680                 }
681             }     
682         } else {
683             
684             if (isset($this->DB_DataObject['schema_location'])) {
685                 $dbinis[] = $this->DB_DataObject['schema_location'] .'/'.basename($dburl['path']).'.ini';
686             } else {
687                 $dbinis[] = $this->baseDir.'/DataObjects/'.basename($dburl['path']).'.ini';
688             }
689             // non modular.
690             
691             $dbcls[] = $project .'_DataObjects_';
692             $dbreq[] = $this->baseDir.'/DataObjects';
693         }
694             
695         
696         $this->applyIf('DB_DataObject', array(   
697         
698             'class_location' =>  implode(PATH_SEPARATOR,$dbreq),
699             'class_prefix' =>  implode(PATH_SEPARATOR,$dbcls),
700             'database'        => $this->database,    
701             ///'require_prefix' => 
702          //   'schema_location' => dirname(__FILE__) . '/Pman/DataObjects/',
703              $dbini=> implode(PATH_SEPARATOR,$dbinis),
704          
705            //   'debug' => 5,
706         ));
707       //  print_r($this->DB_DataObject);exit;
708     }
709     /**
710      Set up thetemplate
711      * 
712      */
713     function _parseConfigTemplate()
714     {
715         
716         // compile.
717         if (function_exists('posix_getpwuid')) {
718             $uinfo = posix_getpwuid( posix_getuid () ); 
719          
720             $user = $uinfo['name'];
721         } else {
722             $user = getenv('USERNAME'); // windows.
723         }
724         
725         $compileDir = ini_get('session.save_path') .'/' . 
726             $user . '_compiled_templates_' . $this->project;
727         
728         if ($this->appNameShort) {
729             $compileDir .= '_' . $this->appNameShort;
730         }
731         if ($this->version) {
732             $compileDir .= '.' . $this->version;
733         }
734         
735         // templates. -- all this should be cached!!!
736         $src = array();
737          
738         
739         if ($this->appNameShort && !in_array('Core', explode(',', $this->disable ? $this->disable : ''))) {
740             // in app based version, template directory is in Core
741             
742             $src = array(  
743                 $this->baseDir . '/Core/templates'
744             );
745         }
746         
747         if(!empty($this->projectExtends)){
748             foreach ($this->projectExtends as $e){
749                 $add = $this->rootDir . '/' . $e .'/templates';
750                 if (!in_array($add,$src) && file_exists($add)) {
751                     $src[] = $add;
752                 }
753             }
754         }
755         
756         $src[] = $this->baseDir . '/templates';
757         
758         
759         
760         if (!empty($this->enableArray)) {
761              
762             
763             foreach($this->enableArray as $m) {
764                 $add = $this->baseDir . '/' . $m .'/templates';
765                 if (!in_array($add,$src) && file_exists($add) && $this->appNameShort != $m) {
766                     $src[] = $add;
767                 }
768                 
769             }
770             if (!empty($this->projectExtends)  )  {
771                 foreach ($this->projectExtends as $extend){
772                     foreach($this->enableArray as $m) {
773                         $add = $this->rootDir . '/' . $extend . '/' . $m .'/templates';
774                         if (!in_array($add,$src) && file_exists($add) && $this->appNameShort != $m) {
775                             $src[] = $add;
776                         }
777                     }
778                 }
779     
780             }
781         }
782          
783         
784         if ($this->appNameShort) {
785             $src[] =  $this->baseDir . '/'. $this->appNameShort. '/templates';
786         }
787         
788         // images may come from multiple places: - if we have multiple template directories.?
789         // how do we deal with this..?
790         // images/ << should always be mapped to master!
791         // for overridden appdir ones we will have to se rootURL etc.
792         
793         $url_rewrite = 'images/:'. $this->rootURL . '/'. $this->project. '/templates/images/';
794         
795         $this->applyIf('HTML_Template_Flexy', array(
796             'templateDir' => implode(PATH_SEPARATOR, $src),
797             'compileDir' => $compileDir,
798             'multiSource' => true,
799             'forceCompile' => 0,
800             'url_rewrite' => $url_rewrite,
801             'filters' => 'Php,SimpleTags', /// for non-tokenizer version?
802             'debug' => $this->debug ? 1 : 0,
803             'useTokenizer' => 1,
804              
805             
806         
807         
808         ));
809     } 
810     
811     function _parseConfigMail()
812     {
813         $this->applyIf('HTML_Template_Flexy', array(
814            'debug' => 0,
815            'driver' => 'smtp',
816            'host' => 'localhost',
817            'port' => 25,
818         ));
819     }
820     function _exposeToPear()
821     {
822         $cls = array_keys(get_class_vars(__CLASS__));
823         $base = array();
824         
825         // anything that get's set, that's not in our default properties
826         // is assumed to be an option set .
827         foreach(get_object_vars($this) as $k=>$v) {
828             if (in_array($k,$cls)) {
829                 $base[$k] = $v;
830                 continue;
831             }
832             $options = &PEAR::getStaticProperty($k,'options');
833             $options = $v;
834         }
835         $options = &PEAR::getStaticProperty('HTML_FlexyFramework','options');
836         $options = $base;
837          //   apply them..
838     }
839     
840     
841     function _validateEnv() 
842     {
843         /* have I been initialized */
844         
845         
846         if (get_magic_quotes_gpc() && !$this->cli) {
847             $this->fatalError(
848                 "magic quotes is enabled add the line<BR>
849                    php_value magic_quotes_gpc 0<BR>
850                    to your .htaccess file <BR>
851                    (Apache has to be configured to &quot;AllowOverride Options AuthConfig&quot; for the directory)
852                    ");
853                 
854         }
855         // set up error handling - 
856         $this->error = new HTML_FlexyFramework_Error();
857         
858         /// fudge work around bugs in PEAR::setErrorHandling(,)
859         $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
860         $GLOBALS['_PEAR_default_error_options'] = array($this->error,'raiseError');
861         
862         
863         
864         if ($this->debug) {
865             require_once 'Benchmark/Timer.php'; 
866             $this->timer = new BenchMark_Timer(true);
867             register_shutdown_function(function() { echo $this->timer->getOutput(); });
868         }
869
870     }
871     
872     function _validateDatabase()
873     {
874         //echo "<PRE>"; print_r($this);
875
876         if ($this->nodatabase) {
877             return;
878         }
879         $options = &PEAR::getStaticProperty('DB_DataObject','options');
880         $dd = empty($options['dont_die']) ? false : true;
881         $options['dont_die'] = true;
882         
883         // database is the only setting - we dont support mult databses?
884           
885             
886         $x = new DB_Dataobject;
887         $x->_database = $this->database;
888         if (PEAR::isError($err = $x->getDatabaseConnection())) {
889                                 
890
891                 $this->fatalError("Configuration or Database Error: could not connect to Database, <BR>
892                     Please check the value given to HTML_FlexyFramework, or run with debug on!<BR>
893                      <BR> ".$err->toString());
894         }
895         // reset dont die!
896         $options['dont_die'] = $dd ;
897         
898         
899     }
900     function _validateTemplate()
901     {
902         // check that we have a writeable directory for flexy's compiled templates.
903         
904         if (empty($this->HTML_Template_Flexy['compileDir'])) {
905             return;
906         }
907         
908         if ( !file_exists($this->HTML_Template_Flexy['compileDir']))  {
909             mkdir($this->HTML_Template_Flexy['compileDir'], 0700);
910             @mkdir($this->HTML_Template_Flexy['compileDir'], 0700, true);
911             clearstatcache();
912              
913             if ( !file_exists($this->HTML_Template_Flexy['compileDir']))  {
914             
915                 $this->fatalError("Configuration Error: you specified a directory that does not exist for<BR>
916                     HTML_Template_Flexy => compileDir  {$this->HTML_Template_Flexy['compileDir']}<BR>\n"
917                 );
918             }
919         }
920         
921         if (!is_writeable($this->HTML_Template_Flexy['compileDir'])) {
922             $this->fatalError("Configuration Error: Please make sure the template cache directory is writeable<BR>
923                     eg. <BR>
924                     chmod 700 {$this->HTML_Template_Flexy['compileDir']}<BR>
925                     chgrp apache_user  {$this->HTML_Template_Flexy['compileDir']}<BR>\n"
926             );
927         }
928         //echo "<PRE>";print_R($config);
929         
930         
931          
932           
933         
934         
935     }
936   
937   
938    
939         
940     
941     
942     /**
943     * Quality Redirector
944     *
945     * Usage in a page.:
946     * HTML_FlexyFramework::run('someurl/someother',array('somearg'=>'xxx'));
947     * ...do clean up...
948     * exit; <- dont cary on!!!!
949     *
950     * You should really
951     * 
952     * @param   string           redirect to url 
953     * @param   array Args Optional      any data you want to send to the next page..
954     * 
955     *
956     * @return   false
957     * @access   public
958     * @static
959     */
960   
961     
962     static function run($request,$args=array()) 
963     {
964         self::$singleton->_run($request,true,$args);
965         return false;
966     }
967     
968     
969     /**
970     * The main execution loop
971     *
972     * recursivly self called if redirects (eg. return values from page start methods)
973     * 
974     * @param   string from $_REQUEST or redirect from it'self.
975     * @param   boolean isRedirect  = is the request a redirect 
976     *
977     *
978     * @return   false || other    false indicates no page was served!
979     * @access   public|private
980     * @see      see also methods.....
981     */
982   
983     function _run($request,$isRedirect = false,$args = array()) 
984     {
985         
986         // clean the request up.
987         $this->calls++;
988         
989         if ($this->calls > 5) {
990             // to many redirections...
991             trigger_error("FlexyFramework:: too many redirects - backtrace me!",E_USER_ERROR);
992             exit;
993         }
994         
995         $newRequest = $this->_getRequest($request,$isRedirect);
996         
997          
998         // find the class/file to load
999         list($classname,$subRequest) = $this->requestToClassName($newRequest,FALSE);
1000         
1001         
1002         $this->debug("requestToClassName return = CLASSNAME: $classname SUB REQUEST: $subRequest");
1003         
1004         // assume that this was handled by getclassname ?????
1005         if (!$classname) {
1006             return false;
1007         }
1008         
1009         // make page data/object accessable at anypoint in time using  this
1010         // not sure if this is used anymore - or even works..?
1011         $classobj = &PEAR::getStaticProperty('HTML_FlexyFramework', 'page');
1012         
1013         $classobj =  new  $classname();  // normally do not have constructors.
1014         
1015         
1016         $classobj->baseURL = $this->baseURL;
1017         $classobj->rootURL = $this->rootURL;
1018         $classobj->rootDir = $this->rootDir;
1019         $classobj->bootLoader  = $this;
1020         $classobj->request = $newRequest;
1021         $classobj->timer = &$this->timer;
1022         
1023         $this->page = $classobj;
1024         if ($this->cli && !$isRedirect ) { // redirect always just takes redirect args..
1025             require_once 'HTML/FlexyFramework/Cli.php';
1026             $fcli = new HTML_FlexyFramework_Cli($this);
1027             $nargs = $fcli->cliParse($classname);
1028             $args = $nargs === false ? $args : $nargs; /// replace if found.
1029             $classobj->cli_args = $nargs;
1030         }
1031         
1032         // echo '<PRE>'; print_r($this);exit;
1033         // echo "CHECK GET AUTH?";
1034         if (!method_exists($classobj, 'getAuth')) {
1035         //    echo "NO GET AUTH?";
1036             $this->fatalError("class $classname does not have a getAuth Method");
1037             return false;
1038         }
1039         
1040         /* check auth on the page */
1041         if (is_string($redirect = $classobj->getAuth())) {
1042             $this->debug("GOT AUTH REDIRECT".$redirect);
1043             return $this->_run($redirect,TRUE);
1044         }
1045         // used HTML_FlexyFramework::run();
1046                  
1047
1048         if ($redirect === false) {
1049             $this->debug("GOT AUTH FALSE");    
1050             return false; /// Access deined!!! - 
1051         }
1052      
1053         // allow the page to implement caching (for the full page..)
1054         // although normally it should implement caching on the outputBody() method.
1055         
1056         if (method_exists($classobj,"getCache")) {
1057             if ($result = $classobj->getCache()) {
1058                 return $result;
1059             }
1060         }
1061         /* allow redirect from start */
1062         if (method_exists($classobj,"start")) {
1063             if (is_string($redirect = $classobj->start($subRequest,$isRedirect,$args)))  {
1064                 $this->debug("REDIRECT $redirect <BR>");
1065                 return $this->_run($redirect,TRUE);
1066             }
1067             if ($redirect === false) {
1068                 return false;
1069             }
1070         }
1071                 
1072
1073          // used HTML_FlexyFramework::run();
1074         
1075         /* load the modules 
1076          * Modules are common page components like navigation headers etc.
1077          * that can have dynamic code.
1078          * Code has been removed now..
1079          */
1080         
1081         
1082         if ($this->timer) {
1083             $this->timer->setMarker("After $request loadModules Modules"); 
1084         }
1085         
1086         /* output it  - (our base page does not implement output for cli. */
1087         
1088         if ( method_exists($classobj,'output')) {
1089             $classobj->output(); 
1090         }
1091         
1092         
1093         if ($this->timer) {
1094             $this->timer->setMarker("After $request output"); 
1095             $this->timer->stop(); //?? really - yes...
1096            
1097             
1098         }
1099         
1100         if ($this->cli) {
1101             return true;
1102         }
1103         
1104         
1105         exit; /// die here...
1106         
1107     }
1108     
1109     /**
1110     * map the request into an object and run the page.
1111     *
1112     * The core of the work is done here.
1113     * 
1114     * 
1115     * @param   request  the request string
1116     * @param   boolean isRedirect - indicates that it should not attempt to strip the .../index.php from the request.
1117     * 
1118     * @access  private
1119     */
1120   
1121     function _getRequest($request, $isRedirect) 
1122     {
1123         
1124          
1125         if ($this->cli) {
1126             return $request;
1127         }
1128         
1129         $startRequest = $request;
1130         $request =@ array_shift(explode('?', $request));
1131         $this->debug("INPUT REQUEST $request<BR>");
1132         if (!$isRedirect) {
1133             // check that request forms contains baseurl????
1134             if (!empty($_SERVER['REDIRECT_STATUS'])  && !empty($_SERVER['REDIRECT_URL'])) {
1135                // phpinfo();exit;
1136                 $sn = $_SERVER['SCRIPT_NAME'];
1137                 $sublen = strlen(substr($sn , 0,  strlen($sn) - strlen(basename($sn)) -1 ));
1138                  //var_dump(array($sn,$subdir,basename($sn)));exit;
1139                 $subreq =  $_SERVER['SCRIPT_NAME'];
1140                 $request = substr($_SERVER['REDIRECT_URL'],$sublen);
1141                 
1142                  
1143             } else {
1144                   
1145              
1146                 $subreq = substr($request,0, strlen($this->baseURL));
1147                 if ($subreq != substr($this->baseURL,0,strlen($subreq))) {
1148                     $this->fatalError(
1149                         "Configuration error: Got base of $subreq which does not 
1150                             match configuration of: $this->baseURL} ");
1151                 }
1152                 $request = substr($request,strlen($this->baseURL));
1153                 
1154             }
1155             
1156              
1157         }
1158        // var_Dump(array('req'=>$request,'subreq'=>$subreq));
1159         
1160         // strip front
1161         // echo "REQUEST WAS: $request<BR>";
1162         // $request = preg_replace('/^'.preg_quote($base_url,'/').'/','',trim($request));
1163         // echo "IS NOW: $request<BR>";
1164         // strip end
1165         // strip valid html stuff
1166         //$request = preg_replace('/\/[.]+/','',$request);
1167         
1168
1169         $request = preg_replace('/^[\/]*/','',$request);
1170         $request = preg_replace('/\?.*$/','',$request);
1171         $request = preg_replace('/[\/]*$/','',$request);
1172         $this->baseRequest = $request;
1173         $request = str_replace('&','',$request); // any other invalid characters???
1174         $request = preg_replace('/\.([a-z]+)$/','',$request);
1175         $this->ext = substr($this->baseRequest , strlen($request));
1176         
1177         // REDIRECT ROO to index.php! for example..
1178         
1179         if (!$request && !$isRedirect) {
1180             if ($this->baseURL && (strlen($startRequest) < strlen($this->baseURL))) {
1181                 // needs to handle https + port
1182                 $http = ((!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"]  == 'on')) ? 'https' : 'http';
1183                 $sp = '';
1184                 if (!empty($_SERVER['SERVER_PORT'])) {
1185                     if ((($http == 'http') && ($_SERVER['SERVER_PORT'] == 80)) || (($http == 'https') && ($_SERVER['SERVER_PORT'] == 443))) {
1186                         // standard ports..
1187                     } else {
1188                         $sp .= ':'.((int) $_SERVER['SERVER_PORT']);
1189                     }
1190                 }
1191                 $host = !empty($_SERVER["HTTP_X_FORWARDED_HOST"]) ? $_SERVER["HTTP_X_FORWARDED_HOST"] : $_SERVER["HTTP_HOST"];
1192                 header('Location: '.$http.'://'.$host .$sp . $this->baseURL);
1193  
1194                 exit;
1195             }
1196             $request = "";
1197         }
1198        // var_dump(array($startRequest,$request, $this->baseRequest));
1199         
1200         $this->debug("OUTPUT REQUEST $request<BR>");
1201         
1202         $this->_handleLanguages($request);
1203
1204         
1205         return $request;
1206     }
1207     
1208    
1209     
1210     
1211     /**
1212     * get the Class name and filename to load
1213     *
1214     * Parses the request and converts that into a File + Classname
1215     * if the class doesnt exist it will attempt to find a file below it, and
1216     * call that one with the data.
1217     * Used by the module loader to determine the location of the modules
1218     *   
1219     * @param   request  the request string
1220     * @param   boolean showError - if false, allows you to continue if the class doesnt exist.
1221     * 
1222     *
1223     * @return   array classname, filepath
1224     * @access   private
1225     * @static
1226     */
1227   
1228     function requestToClassName($request,$showError=TRUE) 
1229     {
1230        // if ($request == "error") {
1231        //     return array("HTML_FlexyFramework_Error","");
1232        // }
1233         
1234         // special classes ::
1235         if ($this->cli && in_array($request, array('DataObjects'))) {
1236             require_once 'HTML/FlexyFramework/'. $request . '.php';
1237             return array('HTML_FlexyFramework_'. $request,'');
1238         }
1239         
1240         
1241         $request_array=explode("/",$request);
1242         $original_request_array = $request_array;
1243         $sub_request_array = array();
1244         $l = count($request_array)-1;
1245         if ($l > 10) { // ?? configurable?
1246             //PEAR::raiseError("Request To Long");
1247             $this->fatalError("Request To Long - " . $request);
1248         }
1249
1250         
1251         $classname='';
1252         // tidy up request array
1253         
1254         if ($request_array) {
1255             foreach(array_keys($request_array) as $i) {
1256                 $request_array[$i] = preg_replace('/[^a-z0-9]/i','_',urldecode($request_array[$i]));
1257             }
1258         }
1259         //echo "<PRE>"; print_r($request_array);
1260         // technically each module should do a check here... similar to this..
1261         
1262         
1263         for ($i=$l;$i >-1;$i--) {
1264             $location = implode('/',$request_array) . ".php";
1265             if ($location == '.php') {
1266                 $this->debug("SKIP first path check, as request str is empty");
1267                 break;
1268             }
1269             
1270             $this->debug("baseDIR = {$this->baseDir}");
1271             
1272             $floc = "{$this->baseDir}/$location";
1273             $this->debug("CHECK LOCATION = $location");
1274             
1275             
1276             
1277             if (!empty($location) && $location != '.php' && @file_exists($floc )) {             // hide? error???
1278                 require_once $floc ;
1279                 $classname = $this->classPrefix . implode('_',$request_array);
1280                 $this->debug("FOUND FILE - SET CLASS = $classname <BR>");
1281                 break;
1282             } 
1283             
1284             // in here check the 'projectExtends' versions..?
1285             
1286             if(!empty($this->projectExtends)){
1287                 $this->debug("Trying project Extends<BR>");
1288                 $has_extend_class = false;
1289                 
1290                 foreach ($this->projectExtends as $e){
1291                     $floc = "{$this->rootDir}/{$e}/$location";
1292                     $this->debug("Trying file: $floc");
1293                     if (!empty($location) && @file_exists($floc)) {             // hide? error???
1294                         require_once $floc ;
1295                         $classname = $e . '_' . implode('_',$request_array);
1296                         $has_extend_class = true;
1297                         $this->debug("FOUND FILE - SET CLASS = $classname <BR>");
1298                         break;
1299                     } 
1300                 }
1301                 
1302                 if(!empty($has_extend_class)){
1303                     break;
1304                 }
1305                 
1306             }
1307             
1308             
1309             $this->debug("$floc  - !!FOUND NOT FILE!!");
1310             
1311             $sub_request_array[] = $original_request_array[$i];
1312             unset($request_array[$i]);
1313             unset($original_request_array[$i]);
1314         }
1315          
1316         // is this really needed here!
1317         
1318         $classname = preg_replace('/[^a-z0-9]/i','_',$classname);
1319         $this->debug("CLASSNAME is '$classname'");
1320         // got it ok.
1321         if ($classname && class_exists($classname)) {
1322             $this->debug("using $classname");
1323             //print_r($sub_request_array);
1324             return array($classname,implode('/',array_reverse($sub_request_array)));
1325         }
1326         // stop looping..
1327         if ($showError) {
1328             $this->fatalError("INVALID REQUEST: \n $request FILE:".$this->baseDir. "/{$location}  CLASS:{$classname}");
1329             
1330         } 
1331         
1332         
1333         $this->debug("Try base {$this->baseDir}.php");   
1334         // try {project name}.php
1335         // this used to be silenced @ - if this fails we are usually pretty fried..
1336         
1337         if (file_exists($this->baseDir.'.php')) {
1338             
1339             
1340             $classname = str_replace('/', '_', $this->project); //   basename($this->baseDir);
1341             
1342             $this->debug("FOUND {$this->baseDir} requring and checking class $classname");   
1343             require_once $this->baseDir.'.php';
1344             $this->debug("require success");
1345             
1346             if (!class_exists($classname)) {
1347                 $this->fatalError( "{$this->baseDir}.php did not contain class $classname");
1348             }
1349         }
1350         // got projectname.php
1351         if ($classname && class_exists($classname)) {
1352             $this->debug("using $classname");
1353             //print_r($sub_request_array);
1354              
1355             return array($classname,implode('/',array_reverse($sub_request_array)));
1356         }    
1357             
1358         
1359         $this->fatalError( "can not find {$this->baseDir}.php"); // dies..
1360               
1361      
1362     }
1363     
1364     /**
1365     * ensure Single CLi process 
1366     * usage:
1367     * HTML_FlexyFramework::ensureSingle(__FILE__, $this);
1368     * @param string filename of running class
1369     * @param object class
1370     */
1371       
1372     static function ensureSingle($sig, $class) 
1373     {
1374         //echo "check single: $sig / ". get_class($class) ."\n";
1375         $ff = HTML_FlexyFramework::get();
1376         if (function_exists('posix_getpwuid')) {
1377             $uinfo = posix_getpwuid( posix_getuid () ); 
1378             $user = $uinfo['name'];
1379         } else {
1380             $user = getenv('USERNAME'); // windows.
1381         }
1382         $fdir = ini_get('session.save_path') .'/' . 
1383                 $user . '_cli_' . $ff->project ;
1384      
1385         
1386         if (!file_exists($fdir)) {
1387             mkdir($fdir, 0777);
1388         }
1389         
1390         $lock = $fdir.'/'. md5($sig) . '.' . get_class($class);
1391         //echo "check single: lock : $lock\n";
1392         if (!file_exists($lock)) {
1393             file_put_contents($lock, getmypid());
1394             //echo "check single: lock : DOES NOT EXIST\n";
1395             return true;
1396         }
1397         $oldpid = file_get_contents($lock);
1398         if (!file_exists('/proc/' . $oldpid)) {
1399             
1400             file_put_contents($lock, getmypid());
1401           //  echo "check single: lock : PROC NOT EXIST\n";
1402             return true;
1403         }
1404         // file exists, but process might not be the same..
1405         $name = array_pop(explode('_', get_class($class)));
1406         $cmd = file_get_contents('/proc/' . $oldpid.'/cmdline');
1407         if (!preg_match('/php/i',$cmd) || !preg_match('/'.$name.'/i',$cmd)) {
1408             file_put_contents($lock, getmypid());
1409             //echo "check single: lock : CMDLINE !have PHP \n";
1410             return true;
1411         }
1412         die("process " . $sig . " already running\n");
1413         
1414     }
1415     /**
1416      * removes the lock for the applicaiton - use with care...
1417      *
1418      *
1419      */
1420     static function ensureSingleClear($sig, $class)
1421     {
1422         $ff = HTML_FlexyFramework::get();
1423         if (function_exists('posix_getpwuid')) {
1424             $uinfo = posix_getpwuid( posix_getuid () ); 
1425             $user = $uinfo['name'];
1426         } else {
1427             $user = getenv('USERNAME'); // windows.
1428         }
1429         $fdir = ini_get('session.save_path') .'/' . 
1430                 $user . '_cli_' . $ff->project ;
1431      
1432         
1433         if (!file_exists($fdir)) {
1434             mkdir($fdir, 0777);
1435         }
1436         $lock = $fdir.'/'. md5($sig);
1437         if (!file_exists($lock)) {
1438             
1439             return true;
1440         }
1441         unlink($lock);;
1442     }
1443     
1444     
1445     /**
1446     * Debugging 
1447     * 
1448     * @param   string  text to output.
1449     * @access   public
1450     */
1451   
1452     function debug($output) {
1453        
1454         if (empty($this->debug)) {  
1455             return;
1456         }
1457         echo $this->cli ? 
1458               "HTML_FlexyFramework::debug  - ".$output."\n" 
1459             : "<B>HTML_FlexyFramework::debug</B> - ".$output."<BR>\n";
1460     
1461     }
1462     /**
1463     * Raises a fatal error. - normally only used when setting up to help get the config right.
1464     * 
1465     * can redirect to fatal Action page.. - hoepfully not issued before basic vars are set up..
1466     * 
1467     * @param   string  text to output.
1468     * @access   public
1469     */
1470     
1471     function fatalError($msg,$showConfig = 0) 
1472     {
1473         
1474         
1475          if ($this->fatalAction) {
1476             HTML_FlexyFramework::run($this->fatalAction,$msg);
1477             exit;
1478         }
1479         
1480         echo $this->cli ? $msg ."\n" : "<H1>$msg</H1>configuration information<PRE>";
1481         if ($showConfig) {
1482             
1483             print_r($this);
1484         }
1485         $ff = HTML_FlexyFramework::get();
1486         $ff->debug($msg);
1487         exit;
1488     }    
1489 }
1490
1491