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

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