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