/[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.3 - (hide annotations)
Tue Apr 8 22:35:16 2003 UTC (21 years, 4 months ago) by joko
Branch: MAIN
Changes since 1.2: +8 -1 lines
+ 'function yesno' from utils/links.php

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

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