/[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.5 - (hide annotations)
Fri Apr 11 01:31:50 2003 UTC (21 years, 3 months ago) by joko
Branch: MAIN
Changes since 1.4: +11 -1 lines
+ function log (from flib-shortcuts)

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

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