/[cvs]/nfo/php/libs/org.netfrag.glib/utils/extensions.php
ViewVC logotype

Annotation of /nfo/php/libs/org.netfrag.glib/utils/extensions.php

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.1 - (hide annotations)
Sat Apr 5 19:53:45 2003 UTC (21 years, 3 months ago) by joko
Branch: MAIN
moved here from ../

1 joko 1.1 <?php
2    
3     /**
4     * This file contains some core functions extending php.
5     *
6     * @author Andreas Motl <andreas.motl@ilo.de>
7     * @package org.netfrag.glib
8     * @name php
9     *
10     */
11    
12     /**
13     * $Id: php_extensions.php,v 1.7 2003/04/04 17:35:40 joko Exp $
14     *
15     * $Log: php_extensions.php,v $
16     * Revision 1.7 2003/04/04 17:35:40 joko
17     * fixed php croaking
18     * moved error handling function to 'php_errors.php'
19     * + function php::maintenance
20     *
21     * Revision 1.6 2003/03/11 02:14:18 joko
22     * + fixed metadata for phpDocumentor
23     *
24     * Revision 1.5 2003/03/10 22:58:46 joko
25     * + fixed metadata for phpDocumentor
26     *
27     * Revision 1.4 2003/03/05 23:16:46 joko
28     * updated docu - phpDocumentor is very strict about its 'blocks'...
29     *
30     * Revision 1.3 2003/03/05 18:54:41 joko
31     * updated docu - phpDocumentor is very strict about its 'blocks'...
32     *
33     * Revision 1.2 2003/03/05 11:58:49 joko
34     * modified is_hash, mkInstance and others
35     *
36     * Revision 1.1 2003/03/03 21:08:21 joko
37     * refactored from flib/utils
38     *
39     *
40     */
41    
42    
43     /**
44     * --- shortcut functions
45     * Is there a mechanism in php to 'export' these methods
46     * to the global symbol table automagically?
47     * We wouldn't require declaring these shortcuts below and
48     * could also do some nice stuff at runtime.
49     * (maybe resembling CPAN's Exporter)
50     *
51     * Okay, 'eval' and 'create_function' are alternatives, but i'm
52     * still looking for something that would let us manipulate the
53     * symbol table.... (would also be a nice-to-have feature for
54     * mungling "other" symbol table entries, like variables
55     * and/or object references etc.)
56     *
57     * TODO: $php::EXPORT_OK = array('Dumper', 'session_register_safe', 'mkObject', 'is_hash', 'merge_to');
58     *
59     */
60     // this is (and will probably always be) required by the "Exporter"
61     function &Dumper() {
62     $args = func_get_args();
63     // shrink array to single item?
64     //if (sizeof($args) == 1) { $args = $args[0]; }
65     php::array_shrink($args);
66     return php::Dumper($args);
67     }
68    
69     // these could be refactore using Exporter proposal below,
70     // which just does this code at runtime via eval
71     //function &session_register_safe() { return php::session_register_safe(func_get_args()); }
72     //function &is_hash() { return php::is_hash(func_get_args()); }
73     //function &loadModule() { return php::loadModule(func_get_args()); }
74     //function &mkObject() { return php::mkInstance(func_get_args()); }
75    
76    
77     //exit;
78    
79     // yes!
80     php::export_symbols();
81    
82    
83    
84     /**
85     * --- php extension functions living in the php:: namespace
86     *
87     * <pre>
88     * x php::Dumper
89     * x php::session_register_safe
90     * x php::array_init
91     * x php::is_hash
92     * x php::array_join_merge
93     * o php::merge
94     * o php::merge_to
95     * x php::loadModule
96     * x php::mkInstance
97     * </pre>
98     *
99     * @author Andreas Motl <andreas.motl@ilo.de>
100     * @copyright (c) 2003 - All Rights reserved.
101     * @license GNU LGPL (GNU Lesser General Public License)
102     *
103     * @link http://www.netfrag.org/~joko/
104     * @link http://www.gnu.org/licenses/lgpl.txt
105     *
106     * @package org.netfrag.glib
107     * @name php
108     *
109     * <pre>
110     * Todo:
111     * @todo (o) establish mkInstance here (move from DesignPattern::Object::mkObject)
112     * @todo (o) establish loadModule here (move from DesignPattern::Object::loadModule)
113     *
114     * Ideas:
115     * @todo (o) php::create_redirector_function('func', array( type => 'lamba|function|method', name => 'Abc::do_xyz') )
116     * @todo (o) php::create_redirector_method('class|obj_ref', 'method', $target)
117     * @todo (o) php::export_symbol(from, to) (maybe solves above two)
118     * </pre>
119     *
120     */
121     class php {
122    
123    
124     // Exporter proposal
125    
126     // does (e.g.) Exporter::export_symbol('php', 'loadModule', array( php_function => 'loadModule' ));
127     // (or) Exporter::export_symbol('php', 'mkInstance', array( php_function => 'mkObject' ));
128     // -> just all from EXPORT_OK
129    
130     function export_symbols() {
131    
132     $symbols = func_get_args();
133     php::array_shrink($symbols);
134    
135     global $PHP_EXTENSIONS_EXPORT;
136     //print Dumper($PHP_EXTENSIONS_EXPORT);
137     //exit;
138    
139     if (is_array($PHP_EXTENSIONS_EXPORT)) {
140     //if (defined('EXPORT_OK')) {
141     //print EXPORT_OK . "<br/>";
142     //$symbols = split(' ', EXPORT_OK);
143     //foreach ($php->EXPORT_OK as $symbol) {
144     /*
145     foreach (EXPORT_OK as $symbol) {
146     print "exporting: $symbol<br/>";
147     Exporter::export_symbol('php', $symbol, array( php_function => $symbol ));
148     }
149     */
150    
151     $symbols = php::array_join_merge($PHP_EXTENSIONS_EXPORT, $symbols);
152    
153     php::loadModule('Exporter');
154     if (class_exists('Exporter')) {
155     Exporter::export_symbols('php', $symbols);
156     }
157    
158     }
159    
160     }
161    
162     function Dumper() {
163     $arg_list = func_get_args();
164     $count = 1;
165    
166     // build dump by catching output of php's 'print_r'
167     // using php's output buffering functions
168     ob_start();
169     foreach ($arg_list as $arg) {
170     print_r($arg);
171     if (is_string($arg)) {
172     print "\n";
173     }
174     $count++;
175     }
176     $var_dump = ob_get_contents();
177     ob_end_clean();
178    
179     //print "mode: " . $this->Dumper_mode . "<br/>";
180     //if ($this->Dumper_mode == HTML) {
181     $var_dump = str_replace("\n", '<br/>', $var_dump);
182     $var_dump = str_replace(" ", '&nbsp;', $var_dump);
183     //}
184    
185     //if (sizeof($args) == 1) { $var_dump .= '<br/>'; }
186    
187     return $var_dump;
188     }
189    
190     function session_register_safe($varname) {
191     if (!session_is_registered($varname)) {
192     session_register($varname);
193     return 1;
194     }
195     }
196    
197     // -------------------------------------------------
198     // array initializer
199     // initializes passed variable (taken by reference) with an empty array
200     // does this only if it doesn't exist yet or initialization is explicitely requested ($clear = 1)
201     function array_init(&$var, $clear = 0) {
202     if (!is_array($var) || $clear) { $var = array(); }
203     }
204    
205     // from: php.net - http://www.php.net/manual/en/function.array-merge-recursive.php
206     function is_hash( $var = null ) {
207     if( is_array( $var ) ) {
208     $keys = array_keys( $var );
209     $all_num = true;
210     for( $i=0; $i<count($keys); $i++ )
211     if( is_string($keys[$i] ) ) return true;
212     }
213     return false;
214     }
215    
216     // from: php.net - http://www.php.net/manual/en/function.array-merge-recursive.php
217     function array_join_merge( $arr1, $arr2 ) {
218     if( is_array( $arr1 ) and is_array( $arr2 ) ) {
219     // the same -> merge
220     $new_array = array();
221    
222     if( php::is_hash( $arr1 ) and php::is_hash( $arr2 ) ) {
223     // hashes -> merge based on keys
224     $keys = array_merge( array_keys( $arr1 ), array_keys( $arr2 ) );
225     foreach( $keys as $key ) {
226     $new_array[$key] = php::array_join_merge( $arr1[$key], $arr2[$key] );
227     }
228     } else {
229     // two real arrays -> merge
230     $new_array =
231     array_reverse(array_unique(array_reverse(array_merge($arr1,$arr2))));
232     }
233    
234     return $new_array;
235     } else {
236     // not the same ... take new one if defined, else the old one stays
237     return $arr2 ? $arr2 : $arr1;
238     }
239     }
240    
241    
242     // TODO:
243     // o refactor to the php:: namespace?
244     // o PEAR::???
245     // x rename mkObject to mkInstance
246     // x rename loadModule? let it like is.... (suggestions? loadPackage?)
247     // o enhance loadModule: make it possible to load packages from anywhere?! #?)&%$
248    
249     function namespace2filename($nsName) {
250     if ($filename = str_replace('::', '/', $nsName)) {
251     return $filename;
252     }
253     }
254    
255     function loadModule($namespacedClassname, $options = null) {
256    
257     if (DEBUG_PHP_EXTENSIONS == 1) {
258     print "php::loadModule: " . Dumper($namespacedClassname);
259     }
260     if (LOG_PHP_EXTENSIONS == 1) {
261     php::append_log( "php::loadModule( $namespacedClassname )" );
262     }
263    
264     if ($filename = php::namespace2filename($namespacedClassname)) {
265    
266     if (is_array($options)) {
267     $extension = $options[extension];
268     } elseif ($options) {
269     $extension = $options;
270     } else {
271     $extension = 'php';
272     }
273    
274     $filename .= ".$extension";
275    
276     // V1: just require
277     //require_once($filename);
278    
279     // V2: check file for existance (didn't work!!! problem with path-style conversion regarding platform running on?)
280     /*
281     if (file_exists($filename)) {
282     require_once($filename);
283     } else {
284     //user_error("Could not load module '$namespacedClassname', file '$filename' does not exist.");
285     }
286     */
287    
288     // V3: wrapped through eval (weird)
289     /*
290     $evalstring = "return include_once('$filename');";
291     $result = eval($evalstring);
292     if (!$result) {
293     user_error("DesignPattern::Object: Could not load module '$namespacedClassname', file '$filename' does not exist.");
294     return;
295     }
296     */
297    
298     // V4: just include
299     //define ("WARNING", E_USER_NOTICE);
300     //error_reporting(E_USER_WARNING);
301     //error_reporting(E_ALL);
302     //error_reporting(E_CORE_ERROR);
303     //set_error_handler(array('php::error_handler_2'));
304    
305     //set_error_handler('php_error_handler');
306     // TODO: do stack-backtracing here to determine function called two or three levels before!!!
307     //print "file: $filename<br/>";
308    
309     if (!include_once($filename)) {
310     //if (!@include_once($filename)) {
311     $msg = "php::loadModule error: Could not load module '$namespacedClassname', file '$filename' does not exist.";
312     user_error($msg);
313     php::append_log($msg, PEAR_LOG_ERR);
314     //trigger_error($msg);
315     //print "msg: $msg<br/>";
316     return;
317     }
318     //restore_error_handler();
319    
320     //exit;
321    
322     return 1;
323     }
324     }
325    
326    
327     function &mkComponent() {
328    
329     // argument handling - perl style
330     $arg_list = &func_get_args();
331    
332     // trace
333     //print "php::mkInstance: " . Dumper($arg_list);
334     //exit;
335    
336     // patch arglist if all arguments are passed in as a single array
337     if (sizeof($arg_list) == 1 && is_array($arg_list[0])) {
338     $arg_list = &$arg_list[0];
339     }
340    
341     //print "arg_list: $arg_list<br/>";
342     $namespacedClassname = array_shift($arg_list);
343    
344     // debug
345     if (DEBUG_PHP_EXTENSIONS == 1) {
346     print "php::mkComponent: $namespacedClassname<br/>";
347     }
348     if (LOG_PHP_EXTENSIONS == 1) {
349     php::append_log( "php::mkComponent( $namespacedClassname )" );
350     }
351    
352     $classname = $namespacedClassname;
353     $filename = $namespacedClassname;
354     $load_module_options = null;
355    
356     if (strstr($namespacedClassname, '_')) {
357     //print "mkObject: unallowed character in namespaced classname: '_' ($namespacedClassname)<br/>";
358     //return;
359     }
360    
361     if (strstr($namespacedClassname, '.')) {
362     //print "mkObject: unallowed character in namespaced classname: '_' ($namespacedClassname)<br/>";
363     //return;
364     $parts = split('\.', $namespacedClassname);
365     $filename = $parts[0];
366     $extension = $parts[sizeof($parts) - 1];
367     $load_module_options = array( extension => $extension );
368     }
369    
370    
371     // trace
372     //print "mkObject: $classname<br/>";
373     //print "file: $filename<br/>";
374    
375     // build native class name from namespaced one
376     $classname = str_replace('::', '_', $classname);
377     $classname = str_replace('/', '_', $classname);
378    
379     // load class-file
380     if (!class_exists($classname)) {
381     php::loadModule($filename, $load_module_options);
382     }
383    
384     // instantiate object
385     $attributes = $arg_list;
386     // V0:
387     //$obj = new $classname($attributes);
388     // V1:
389     //$obj = new DesignPattern_Bridge($classname, $attributes);
390     // V2:
391     $obj = php::mkInstance($classname, $attributes);
392    
393     // constructor autocall - if possible
394     // FIXME: take care for side-effects!!!
395     /*
396     if (method_exists($obj, 'constructor')) {
397     $obj->constructor();
398     }
399     */
400    
401     // return instance
402     return $obj;
403    
404     }
405    
406     // from: http://www.php.net/manual/en/function.method-exists.php
407     function class_has_method($className, $methodName) {
408     $bool_exists = (in_array(strtolower($methodName), get_class_methods($className)));
409     return $bool_exists;
410     }
411    
412     // down: array( item ) => item
413     function &array_shrink(&$array) {
414     // shrink array to single item? yes!
415     if (is_array($array) && !php::is_hash($array) && (sizeof($array) == 1)) { $array = $array[0]; }
416     return $array;
417     }
418    
419     function append_log($message, $level = PEAR_LOG_DEBUG) {
420     static $Class_Logger_loaded;
421     static $Class_Logger_instance;
422     if (!$Class_Logger_loaded) {
423     $Class_Logger_loaded++;
424     //print "LOAD<br/>";
425     php::loadModule('Class::Logger');
426     }
427     if (class_exists('Class_Logger')) {
428     //$Class_Logger_instance = new Class_Logger();
429     $Class_Logger_instance = php::mkComponent('Class::Logger');
430     //print "YAI<br/>";
431     //Class_Logger::log($message);
432     $Class_Logger_instance->log($message, $level);
433     } else {
434     // FIXME! pre-logger log-messages (two or three):
435     // [PEAR_LOG_DEBUG] php::loadModule( Class::Logger )
436     // [PEAR_LOG_DEBUG] php::loadModule( DesignPattern::AbstractClass )
437     //print "[$level] $message" . "<br/>";
438     }
439     }
440    
441     function &mkInstance($classname, $attributes = array()) {
442    
443     $oo = is_object($this);
444    
445     // autocall constructor?
446     if ($oo) {
447     //print Dumper($this);
448     //exit;
449     //print "this: $this<br/>";
450     //print "parent: $parent<br/>";
451     // V1:
452     //parent::constructor();
453     // V2:
454     //call_user_func('parent::constructor');
455     // V3:
456     //call_user_func(array($this, 'constructor'));
457     if (method_exists($this, 'constructor')) {
458     //print "YAI<br/>";
459     //call_user_func(array($this, 'constructor'));
460     }
461     }
462    
463     if ($oo) {
464     //$this->log( get_class($this) . "->mkInstance( classname $classname )" );
465     //Class_Logger::log( get_class($this) . "->mkInstance( classname $classname )" );
466     } else {
467     //php::append_log( "php::mkInstance( classname $classname )" );
468     }
469    
470     if (isset($attributes)) {
471     //print Dumper($attributes);
472    
473     /*
474     // pass single argument 1:1
475     if (count($attributes) == 1) {
476     $attributes_merged = $attributes[0];
477    
478    
479    
480     // pass hash 1:1
481     } elseif (is_hash($attributes)) {
482     $attributes_merged = $attributes;
483    
484     } else {
485     $attributes_merged = $attributes;
486     }
487     */
488    
489     $args_pass = array();
490     for ($i=0; $i<=count($attributes); $i++) {
491     array_push($args_pass, '&$attributes[' . $i . ']');
492     }
493    
494     $arg_string = join(', ', $args_pass);
495    
496     /*
497     // merge entries of numerical indexed arrays together into one hash
498     } else {
499     $attributes_merged = array();
500     foreach ($attributes as $entry) {
501     $attributes_merged = array_merge($attributes_merged, $entry);
502     }
503     }
504     */
505    
506     if (!class_exists($classname)) {
507     user_error("Class '$classname' doesn't exist.");
508     return;
509     }
510    
511     //print Dumper($attributes_merged);
512     //print Dumper($attributes);
513     //$instance = new $classname($attributes_merged);
514     //$instance = new $classname($attributes[0]);
515     $evalstr = 'return new $classname(' . $arg_string . ');';
516    
517     //print "eval: $evalstr<br/>";
518    
519     $instance = eval($evalstr);
520     //print $evalstr . "<br/>";
521     } else {
522     $instance = new $classname;
523     }
524     //$this->log("ok");
525     return $instance;
526     }
527    
528     // up: string -> array
529     function array_cast_safe(&$array_or_not) {
530     if (!is_array($array_or_not)) {
531     $array_or_not = array($array_or_not);
532     //print Dumper($array_or_not);
533     //exit;
534     }
535     }
536    
537     // To return all ancestors class of an object
538     // from: http://www.php.net/manual/en/function.get-parent-class.php
539     function get_ancestors_class($classname) {
540     $father = get_parent_class($classname);
541     if ($father != "") {
542     $ancestors = php::get_ancestors_class($father);
543     $ancestors[] = $father;
544     }
545     return $ancestors;
546     }
547    
548     // ------ override/expand php's 'include_path' setting ------
549     function add_libpath($paths) {
550    
551     if (!is_array($paths)) {
552     $paths = array($paths);
553     }
554     array_push($paths, ini_get("include_path"));
555    
556     // determine OS
557     $os = 'linux';
558     if (stristr($_SERVER["SERVER_SOFTWARE"], 'win32')) {
559     $os = 'windows';
560     }
561    
562     $path_delimiter = ':';
563     // change path-delimiter for win32
564     if ($os == 'windows') { $path_delimiter = ';'; }
565     // build new 'include_path'-string
566     $path_new = join($path_delimiter, $paths);
567     ini_set("include_path", $path_new);
568     }
569    
570     // from: http://www.php.net/manual/en/function.is-subclass-of.php
571     function is_subclass($child, $parent) {
572     if (is_string($child)) {
573     do {
574     $child = get_parent_class($child);
575     if (!$child) return false;
576     //} while ($child == $parent);
577     } while ($child != $parent);
578     return true;
579     } else {
580     return is_subclass_of($child, $parent);
581     }
582     }
583    
584    
585     function maintenance($type = 'system', $options = array()) {
586    
587     switch ($type) {
588    
589     case 'system':
590     print "<br/><br/>";
591     print "<p align=\"center\">We have taken down our systems for maintenance purposes. <br/>Please apologize the downtime.</p>";
592     print "<p align=\"center\">Wir f&uuml;hren gerade Wartungsarbeiten an unseren Systemen durch. <br/>Bitte entschuldigen Sie die Unterbrechung des Betriebs.</p>";
593    
594     print "<br/><br/>";
595     print "<p align=\"center\"><a href=\"mailto:info@top-scores.net\">Top-Scores Ltd.</a></p>";
596     $do_exit = 1;
597     break;
598    
599     case 'database':
600     print "
601     Database error, we are already notified of this failure and working to resolve it.<br/>
602     We apologize for the inconvenience, please come back later.<br/>
603     <br/>
604     Es ist ein Datenbankfehler aufgetreten. Wir haben bereits Kenntnis von diesem Fehler, an der Lösung des Problems wird gearbeitet.<br/>
605     Bitte versuchen Sie es später nocheinmal.<br/>
606     ";
607     $do_exit = 1;
608     break;
609    
610     case 'rpc':
611    
612     // V0
613     //return;
614    
615     // V2
616     // FIXME: implement some more behaviour here!
617     // via constants?
618     // e.g.:
619     if (!constants::get('APP_MODE_DEBUG_LIGHT')) { return; }
620    
621     // V1
622     print "<font color=\"red\"><b>FIXME! - in 'php::maintenance(rpc)'</b></font><br/>";
623     print "RPC Problems!<br/>";
624     print "Status:<br/>";
625     print Dumper($options[status]);
626     break;
627    
628     }
629    
630     if ($options[no_exit]) { $do_exit = 0; }
631     if ($do_exit) {
632     exit;
633     }
634    
635     }
636    
637    
638     }
639    
640    
641     ?>

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed