/[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.4 - (show annotations)
Wed Apr 9 07:55:47 2003 UTC (21 years, 4 months ago) by joko
Branch: MAIN
Changes since 1.3: +20 -1 lines
+ function untwingle_reference

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

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