/[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.6 - (show annotations)
Wed Apr 16 16:24:23 2003 UTC (21 years, 4 months ago) by joko
Branch: MAIN
Changes since 1.5: +12 -1 lines
+ odd and even from php.net

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

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