/[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.9 - (show annotations)
Thu Aug 11 14:06:26 2005 UTC (18 years, 11 months ago) by jonen
Branch: MAIN
CVS Tags: HEAD
Changes since 1.8: +12 -1 lines
+ added generic array-key sorting function

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

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