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

Contents of /nfo/php/libs/org.netfrag.glib/php_extensions.php

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.8 - (show annotations)
Sat Apr 5 19:54:29 2003 UTC (21 years, 3 months ago) by joko
Branch: MAIN
CVS Tags: HEAD
Changes since 1.7: +6 -1 lines
FILE REMOVED
moved to utils/

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 if (!@include_once($filename)) {
309 $msg = "php::loadModule error: Could not load module '$namespacedClassname', file '$filename' does not exist.";
310 user_error($msg);
311 php::append_log($msg, PEAR_LOG_ERR);
312 //trigger_error($msg);
313 //print "msg: $msg<br/>";
314 return;
315 }
316 //restore_error_handler();
317
318 //exit;
319
320 return 1;
321 }
322 }
323
324
325 function &mkComponent() {
326
327 // argument handling - perl style
328 $arg_list = &func_get_args();
329
330 // trace
331 //print "php::mkInstance: " . Dumper($arg_list);
332 //exit;
333
334 // patch arglist if all arguments are passed in as a single array
335 if (sizeof($arg_list) == 1 && is_array($arg_list[0])) {
336 $arg_list = &$arg_list[0];
337 }
338
339 //print "arg_list: $arg_list<br/>";
340 $namespacedClassname = array_shift($arg_list);
341
342 // debug
343 if (DEBUG_PHP_EXTENSIONS == 1) {
344 print "php::mkComponent: $namespacedClassname<br/>";
345 }
346 if (LOG_PHP_EXTENSIONS == 1) {
347 php::append_log( "php::mkComponent( $namespacedClassname )" );
348 }
349
350 $classname = $namespacedClassname;
351 $filename = $namespacedClassname;
352 $load_module_options = null;
353
354 if (strstr($namespacedClassname, '_')) {
355 //print "mkObject: unallowed character in namespaced classname: '_' ($namespacedClassname)<br/>";
356 //return;
357 }
358
359 if (strstr($namespacedClassname, '.')) {
360 //print "mkObject: unallowed character in namespaced classname: '_' ($namespacedClassname)<br/>";
361 //return;
362 $parts = split('\.', $namespacedClassname);
363 $filename = $parts[0];
364 $extension = $parts[sizeof($parts) - 1];
365 $load_module_options = array( extension => $extension );
366 }
367
368
369 // trace
370 //print "mkObject: $classname<br/>";
371 //print "file: $filename<br/>";
372
373 // build native class name from namespaced one
374 $classname = str_replace('::', '_', $classname);
375 $classname = str_replace('/', '_', $classname);
376
377 // load class-file
378 if (!class_exists($classname)) {
379 php::loadModule($filename, $load_module_options);
380 }
381
382 // instantiate object
383 $attributes = $arg_list;
384 // V0:
385 //$obj = new $classname($attributes);
386 // V1:
387 //$obj = new DesignPattern_Bridge($classname, $attributes);
388 // V2:
389 $obj = php::mkInstance($classname, $attributes);
390
391 // constructor autocall - if possible
392 // FIXME: take care for side-effects!!!
393 /*
394 if (method_exists($obj, 'constructor')) {
395 $obj->constructor();
396 }
397 */
398
399 // return instance
400 return $obj;
401
402 }
403
404 // from: http://www.php.net/manual/en/function.method-exists.php
405 function class_has_method($className, $methodName) {
406 $bool_exists = (in_array(strtolower($methodName), get_class_methods($className)));
407 return $bool_exists;
408 }
409
410 // down: array( item ) => item
411 function &array_shrink(&$array) {
412 // shrink array to single item? yes!
413 if (is_array($array) && !php::is_hash($array) && (sizeof($array) == 1)) { $array = $array[0]; }
414 return $array;
415 }
416
417 function append_log($message, $level = PEAR_LOG_DEBUG) {
418 static $Class_Logger_loaded;
419 static $Class_Logger_instance;
420 if (!$Class_Logger_loaded) {
421 $Class_Logger_loaded++;
422 //print "LOAD<br/>";
423 php::loadModule('Class::Logger');
424 }
425 if (class_exists('Class_Logger')) {
426 //$Class_Logger_instance = new Class_Logger();
427 $Class_Logger_instance = php::mkComponent('Class::Logger');
428 //print "YAI<br/>";
429 //Class_Logger::log($message);
430 $Class_Logger_instance->log($message, $level);
431 } else {
432 // FIXME! pre-logger log-messages (two or three):
433 // [PEAR_LOG_DEBUG] php::loadModule( Class::Logger )
434 // [PEAR_LOG_DEBUG] php::loadModule( DesignPattern::AbstractClass )
435 //print "[$level] $message" . "<br/>";
436 }
437 }
438
439 function &mkInstance($classname, $attributes = array()) {
440
441 $oo = is_object($this);
442
443 // autocall constructor?
444 if ($oo) {
445 //print Dumper($this);
446 //exit;
447 //print "this: $this<br/>";
448 //print "parent: $parent<br/>";
449 // V1:
450 //parent::constructor();
451 // V2:
452 //call_user_func('parent::constructor');
453 // V3:
454 //call_user_func(array($this, 'constructor'));
455 if (method_exists($this, 'constructor')) {
456 //print "YAI<br/>";
457 //call_user_func(array($this, 'constructor'));
458 }
459 }
460
461 if ($oo) {
462 //$this->log( get_class($this) . "->mkInstance( classname $classname )" );
463 //Class_Logger::log( get_class($this) . "->mkInstance( classname $classname )" );
464 } else {
465 //php::append_log( "php::mkInstance( classname $classname )" );
466 }
467
468 if (isset($attributes)) {
469 //print Dumper($attributes);
470
471 /*
472 // pass single argument 1:1
473 if (count($attributes) == 1) {
474 $attributes_merged = $attributes[0];
475
476
477
478 // pass hash 1:1
479 } elseif (is_hash($attributes)) {
480 $attributes_merged = $attributes;
481
482 } else {
483 $attributes_merged = $attributes;
484 }
485 */
486
487 $args_pass = array();
488 for ($i=0; $i<=count($attributes); $i++) {
489 array_push($args_pass, '&$attributes[' . $i . ']');
490 }
491
492 $arg_string = join(', ', $args_pass);
493
494 /*
495 // merge entries of numerical indexed arrays together into one hash
496 } else {
497 $attributes_merged = array();
498 foreach ($attributes as $entry) {
499 $attributes_merged = array_merge($attributes_merged, $entry);
500 }
501 }
502 */
503
504 if (!class_exists($classname)) {
505 user_error("Class '$classname' doesn't exist.");
506 return;
507 }
508
509 //print Dumper($attributes_merged);
510 //print Dumper($attributes);
511 //$instance = new $classname($attributes_merged);
512 //$instance = new $classname($attributes[0]);
513 $evalstr = 'return new $classname(' . $arg_string . ');';
514
515 //print "eval: $evalstr<br/>";
516
517 $instance = eval($evalstr);
518 //print $evalstr . "<br/>";
519 } else {
520 $instance = new $classname;
521 }
522 //$this->log("ok");
523 return $instance;
524 }
525
526 // up: string -> array
527 function array_cast_safe(&$array_or_not) {
528 if (!is_array($array_or_not)) {
529 $array_or_not = array($array_or_not);
530 //print Dumper($array_or_not);
531 //exit;
532 }
533 }
534
535 // To return all ancestors class of an object
536 // from: http://www.php.net/manual/en/function.get-parent-class.php
537 function get_ancestors_class($classname) {
538 $father = get_parent_class($classname);
539 if ($father != "") {
540 $ancestors = php::get_ancestors_class($father);
541 $ancestors[] = $father;
542 }
543 return $ancestors;
544 }
545
546 // ------ override/expand php's 'include_path' setting ------
547 function add_libpath($paths) {
548
549 if (!is_array($paths)) {
550 $paths = array($paths);
551 }
552 array_push($paths, ini_get("include_path"));
553
554 // determine OS
555 $os = 'linux';
556 if (stristr($_SERVER["SERVER_SOFTWARE"], 'win32')) {
557 $os = 'windows';
558 }
559
560 $path_delimiter = ':';
561 // change path-delimiter for win32
562 if ($os == 'windows') { $path_delimiter = ';'; }
563 // build new 'include_path'-string
564 $path_new = join($path_delimiter, $paths);
565 ini_set("include_path", $path_new);
566 }
567
568 // from: http://www.php.net/manual/en/function.is-subclass-of.php
569 function is_subclass($child, $parent) {
570 if (is_string($child)) {
571 do {
572 $child = get_parent_class($child);
573 if (!$child) return false;
574 //} while ($child == $parent);
575 } while ($child != $parent);
576 return true;
577 } else {
578 return is_subclass_of($child, $parent);
579 }
580 }
581
582
583 function maintenance($type = 'system', $options = array()) {
584
585 switch ($type) {
586
587 case 'system':
588 print "<br/><br/>";
589 print "<p align=\"center\">We have taken down our systems for maintenance purposes. <br/>Please apologize the downtime.</p>";
590 print "<p align=\"center\">Wir f&uuml;hren gerade Wartungsarbeiten an unseren Systemen durch. <br/>Bitte entschuldigen Sie die Unterbrechung des Betriebs.</p>";
591
592 print "<br/><br/>";
593 print "<p align=\"center\"><a href=\"mailto:info@top-scores.net\">Top-Scores Ltd.</a></p>";
594 $do_exit = 1;
595 break;
596
597 case 'database':
598 print "
599 Database error, we are already notified of this failure and working to resolve it.<br/>
600 We apologize for the inconvenience, please come back later.<br/>
601 <br/>
602 Es ist ein Datenbankfehler aufgetreten. Wir haben bereits Kenntnis von diesem Fehler, an der Lösung des Problems wird gearbeitet.<br/>
603 Bitte versuchen Sie es später nocheinmal.<br/>
604 ";
605 $do_exit = 1;
606 break;
607
608 case 'rpc':
609
610 // V0
611 //return;
612
613 // V2
614 // FIXME: implement some more behaviour here!
615 // via constants?
616 // e.g.:
617 if (!constants::get('APP_MODE_DEBUG_LIGHT')) { return; }
618
619 // V1
620 print "<font color=\"red\"><b>FIXME! - in 'php::maintenance(rpc)'</b></font><br/>";
621 print "RPC Problems!<br/>";
622 print "Status:<br/>";
623 print Dumper($options[status]);
624 break;
625
626 }
627
628 if ($options[no_exit]) { $do_exit = 0; }
629 if ($do_exit) {
630 exit;
631 }
632
633 }
634
635
636 }
637
638
639 ?>

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