/[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.2 - (show annotations)
Sun Apr 6 01:37:31 2003 UTC (21 years, 4 months ago) by jonen
Branch: MAIN
Changes since 1.1: +23 -2 lines
+ added functions to generate and handle unique ID's

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

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