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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.7 - (show annotations)
Wed Jun 25 23:41:14 2003 UTC (21 years, 2 months ago) by joko
Branch: MAIN
Changes since 1.6: +10 -4 lines
now using "global $Dumper_mode"

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

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