| [ Index ] |
|
Code source de PRADO 3.0.6 |
1 <?php 2 /** 3 * PradoBase class file. 4 * 5 * This is the file that establishes the PRADO component model 6 * and error handling mechanism. 7 * 8 * @author Qiang Xue <qiang.xue@gmail.com> 9 * @link http://www.pradosoft.com/ 10 * @copyright Copyright © 2005 PradoSoft 11 * @license http://www.pradosoft.com/license/ 12 * @version $Id: PradoBase.php 1481 2006-10-29 12:29:16Z xue $ 13 * @package System 14 */ 15 16 /** 17 * Defines the PRADO framework installation path. 18 */ 19 if(!defined('PRADO_DIR')) 20 define('PRADO_DIR',dirname(__FILE__)); 21 22 /** 23 * Includes the classes essential for PradoBase class 24 */ 25 require_once (PRADO_DIR.'/TComponent.php'); 26 require_once (PRADO_DIR.'/Exceptions/TException.php'); 27 require_once (PRADO_DIR.'/Util/TLogger.php'); 28 29 /** 30 * PradoBase class. 31 * 32 * PradoBase implements a few fundamental static methods. 33 * 34 * To use the static methods, Use Prado as the class name rather than PradoBase. 35 * PradoBase is meant to serve as the base class of Prado. The latter might be 36 * rewritten for customization. 37 * 38 * @author Qiang Xue <qiang.xue@gmail.com> 39 * @version $Id: PradoBase.php 1481 2006-10-29 12:29:16Z xue $ 40 * @package System 41 * @since 3.0 42 */ 43 class PradoBase 44 { 45 /** 46 * File extension for Prado class files. 47 */ 48 const CLASS_FILE_EXT='.php'; 49 /** 50 * @var array list of path aliases 51 */ 52 private static $_aliases=array('System'=>PRADO_DIR); 53 /** 54 * @var array list of namespaces currently in use 55 */ 56 private static $_usings=array(); 57 /** 58 * @var TApplication the application instance 59 */ 60 private static $_application=null; 61 /** 62 * @var TLogger logger instance 63 */ 64 private static $_logger=null; 65 66 /** 67 * @return string the version of Prado framework 68 */ 69 public static function getVersion() 70 { 71 return '3.0.6'; 72 } 73 74 /** 75 * Initializes error handlers. 76 * This method set error and exception handlers to be functions 77 * defined in this class. 78 */ 79 public static function initErrorHandlers() 80 { 81 /** 82 * Sets error handler to be Prado::phpErrorHandler 83 */ 84 set_error_handler(array('PradoBase','phpErrorHandler'),error_reporting()); 85 /** 86 * Sets exception handler to be Prado::exceptionHandler 87 */ 88 set_exception_handler(array('PradoBase','exceptionHandler')); 89 } 90 91 /** 92 * Class autoload loader. 93 * This method is provided to be invoked within an __autoload() magic method. 94 * @param string class name 95 */ 96 public static function autoload($className) 97 { 98 include_once($className.self::CLASS_FILE_EXT); 99 if(!class_exists($className,false) && !interface_exists($className,false)) 100 self::fatalError("Class file for '$className' cannot be found."); 101 } 102 103 /** 104 * @return string a string that can be displayed on your Web page showing powered-by-PRADO information 105 */ 106 public static function poweredByPrado() 107 { 108 return '<a title="Powered by PRADO" href="http://www.pradosoft.com/"><img src="http://www.pradosoft.com/images/powered.gif" style="border-width:0px;" alt="Powered by PRADO" /></a>'; 109 } 110 111 /** 112 * PHP error handler. 113 * This method should be registered as PHP error handler using 114 * {@link set_error_handler}. The method throws an exception that 115 * contains the error information. 116 * @param integer the level of the error raised 117 * @param string the error message 118 * @param string the filename that the error was raised in 119 * @param integer the line number the error was raised at 120 */ 121 public static function phpErrorHandler($errno,$errstr,$errfile,$errline) 122 { 123 if(error_reporting()!=0) 124 throw new TPhpErrorException($errno,$errstr,$errfile,$errline); 125 } 126 127 /** 128 * Default exception handler. 129 * This method should be registered as default exception handler using 130 * {@link set_exception_handler}. The method tries to use the errorhandler 131 * module of the Prado application to handle the exception. 132 * If the application or the module does not exist, it simply echoes the 133 * exception. 134 * @param Exception exception that is not caught 135 */ 136 public static function exceptionHandler($exception) 137 { 138 if(self::$_application!==null && ($errorHandler=self::$_application->getErrorHandler())!==null) 139 { 140 $errorHandler->handleError(null,$exception); 141 } 142 else 143 { 144 echo $exception; 145 } 146 exit(1); 147 } 148 149 /** 150 * Stores the application instance in the class static member. 151 * This method helps implement a singleton pattern for TApplication. 152 * Repeated invocation of this method or the application constructor 153 * will cause the throw of an exception. 154 * This method should only be used by framework developers. 155 * @param TApplication the application instance 156 * @throws TInvalidOperationException if this method is invoked twice or more. 157 */ 158 public static function setApplication($application) 159 { 160 if(self::$_application!==null) 161 throw new TInvalidOperationException('prado_application_singleton_required'); 162 self::$_application=$application; 163 } 164 165 /** 166 * @return TApplication the application singleton, null if the singleton has not be created yet. 167 */ 168 public static function getApplication() 169 { 170 return self::$_application; 171 } 172 173 /** 174 * @return string the path of the framework 175 */ 176 public static function getFrameworkPath() 177 { 178 return PRADO_DIR; 179 } 180 181 /** 182 * Serializes a data. 183 * The original PHP serialize function has a bug that may not serialize 184 * properly an object. 185 * @param mixed data to be serialized 186 * @return string the serialized data 187 */ 188 public static function serialize($data) 189 { 190 $arr[0]=$data; 191 return serialize($arr); 192 } 193 194 /** 195 * Unserializes a data. 196 * The original PHP unserialize function has a bug that may not unserialize 197 * properly an object. 198 * @param string data to be unserialized 199 * @return mixed unserialized data, null if unserialize failed 200 */ 201 public static function unserialize($str) 202 { 203 $arr=unserialize($str); 204 return isset($arr[0])?$arr[0]:null; 205 } 206 207 /** 208 * Creates a component with the specified type. 209 * A component type can be either the component class name 210 * or a namespace referring to the path of the component class file. 211 * For example, 'TButton', 'System.Web.UI.WebControls.TButton' are both 212 * valid component type. 213 * This method can also pass parameters to component constructors. 214 * All paramters passed to this method except the first one (the component type) 215 * will be supplied as component constructor paramters. 216 * @param string component type 217 * @return TComponent component instance of the specified type 218 * @throws TInvalidDataValueException if the component type is unknown 219 */ 220 public static function createComponent($type) 221 { 222 self::using($type); 223 if(($pos=strrpos($type,'.'))!==false) 224 $type=substr($type,$pos+1); 225 if(($n=func_num_args())>1) 226 { 227 $args=func_get_args(); 228 $s='$args[1]'; 229 for($i=2;$i<$n;++$i) 230 $s.=",\$args[$i]"; 231 eval("\$component=new $type($s);"); 232 return $component; 233 } 234 else 235 return new $type; 236 } 237 238 /** 239 * Uses a namespace. 240 * A namespace ending with an asterisk '*' refers to a directory, otherwise it represents a PHP file. 241 * If the namespace corresponds to a directory, the directory will be appended 242 * to the include path. If the namespace corresponds to a file, it will be included (include_once). 243 * @param string namespace to be used 244 * @throws TInvalidDataValueException if the namespace is invalid 245 */ 246 public static function using($namespace) 247 { 248 if(isset(self::$_usings[$namespace]) || class_exists($namespace,false)) 249 return; 250 if(($pos=strrpos($namespace,'.'))===false) // a class name 251 { 252 try 253 { 254 include_once($namespace.self::CLASS_FILE_EXT); 255 } 256 catch(Exception $e) 257 { 258 if(!class_exists($namespace,false)) 259 throw new TInvalidOperationException('prado_component_unknown',$namespace); 260 else 261 throw $e; 262 } 263 } 264 else if(($path=self::getPathOfNamespace($namespace,self::CLASS_FILE_EXT))!==null) 265 { 266 $className=substr($namespace,$pos+1); 267 if($className==='*') // a directory 268 { 269 if(is_dir($path)) 270 { 271 self::$_usings[$namespace]=$path; 272 set_include_path(get_include_path().PATH_SEPARATOR.$path); 273 } 274 else 275 throw new TInvalidDataValueException('prado_using_invalid',$namespace); 276 } 277 else // a file 278 { 279 if(is_file($path)) 280 { 281 self::$_usings[$namespace]=$path; 282 if(!class_exists($className,false)) 283 { 284 try 285 { 286 include_once($path); 287 } 288 catch(Exception $e) 289 { 290 if(!class_exists($className,false)) 291 throw new TInvalidOperationException('prado_component_unknown',$className); 292 else 293 throw $e; 294 } 295 } 296 } 297 else 298 throw new TInvalidDataValueException('prado_using_invalid',$namespace); 299 } 300 } 301 else 302 throw new TInvalidDataValueException('prado_using_invalid',$namespace); 303 } 304 305 /** 306 * Translates a namespace into a file path. 307 * The first segment of the namespace is considered as a path alias 308 * which is replaced with the actual path. The rest segments are 309 * subdirectory names appended to the aliased path. 310 * If the namespace ends with an asterisk '*', it represents a directory; 311 * Otherwise it represents a file whose extension name is specified by the second parameter (defaults to empty). 312 * Note, this method does not ensure the existence of the resulting file path. 313 * @param string namespace 314 * @param string extension to be appended if the namespace refers to a file 315 * @return string file path corresponding to the namespace, null if namespace is invalid 316 */ 317 public static function getPathOfNamespace($namespace,$ext='') 318 { 319 if(isset(self::$_usings[$namespace])) 320 return self::$_usings[$namespace]; 321 else if(isset(self::$_aliases[$namespace])) 322 return self::$_aliases[$namespace]; 323 else 324 { 325 $segs=explode('.',$namespace); 326 $alias=array_shift($segs); 327 if(($file=array_pop($segs))!==null && ($root=self::getPathOfAlias($alias))!==null) 328 return rtrim($root.'/'.implode('/',$segs),'/').(($file==='*')?'':'/'.$file.$ext); 329 else 330 return null; 331 } 332 } 333 334 /** 335 * @param string alias to the path 336 * @return string the path corresponding to the alias, null if alias not defined. 337 */ 338 public static function getPathOfAlias($alias) 339 { 340 return isset(self::$_aliases[$alias])?self::$_aliases[$alias]:null; 341 } 342 343 protected static function getPathAliases() 344 { 345 return self::$_aliases; 346 } 347 348 /** 349 * @param string alias to the path 350 * @param string the path corresponding to the alias 351 * @throws TInvalidOperationException if the alias is already defined 352 * @throws TInvalidDataValueException if the path is not a valid file path 353 */ 354 public static function setPathOfAlias($alias,$path) 355 { 356 if(isset(self::$_aliases[$alias])) 357 throw new TInvalidOperationException('prado_alias_redefined',$alias); 358 else if(($rp=realpath($path))!==false && is_dir($rp)) 359 { 360 if(strpos($alias,'.')===false) 361 self::$_aliases[$alias]=$rp; 362 else 363 throw new TInvalidDataValueException('prado_aliasname_invalid',$alias); 364 } 365 else 366 throw new TInvalidDataValueException('prado_alias_invalid',$alias,$path); 367 } 368 369 /** 370 * Fatal error handler. 371 * This method displays an error message together with the current call stack. 372 * The application will exit after calling this method. 373 * @param string error message 374 */ 375 public static function fatalError($msg) 376 { 377 echo '<h1>Fatal Error</h1>'; 378 echo '<p>'.$msg.'</p>'; 379 if(!function_exists('debug_backtrace')) 380 return; 381 echo '<h2>Debug Backtrace</h2>'; 382 echo '<pre>'; 383 $index=-1; 384 foreach(debug_backtrace() as $t) 385 { 386 $index++; 387 if($index==0) // hide the backtrace of this function 388 continue; 389 echo '#'.$index.' '; 390 if(isset($t['file'])) 391 echo basename($t['file']) . ':' . $t['line']; 392 else 393 echo '<PHP inner-code>'; 394 echo ' -- '; 395 if(isset($t['class'])) 396 echo $t['class'] . $t['type']; 397 echo $t['function'] . '('; 398 if(isset($t['args']) && sizeof($t['args']) > 0) 399 { 400 $count=0; 401 foreach($t['args'] as $item) 402 { 403 if(is_string($item)) 404 { 405 $str=htmlentities(str_replace("\r\n", "", $item), ENT_QUOTES); 406 if (strlen($item) > 70) 407 echo "'". substr($str, 0, 70) . "...'"; 408 else 409 echo "'" . $str . "'"; 410 } 411 else if (is_int($item) || is_float($item)) 412 echo $item; 413 else if (is_object($item)) 414 echo get_class($item); 415 else if (is_array($item)) 416 echo 'array(' . count($item) . ')'; 417 else if (is_bool($item)) 418 echo $item ? 'true' : 'false'; 419 else if (is_null($item)) 420 echo 'NULL'; 421 else if (is_resource($item)) 422 echo get_resource_type($item); 423 $count++; 424 if (count($t['args']) > $count) 425 echo ', '; 426 } 427 } 428 echo ")\n"; 429 } 430 echo '</pre>'; 431 exit(1); 432 } 433 434 /** 435 * Returns a list of user preferred languages. 436 * The languages are returned as an array. Each array element 437 * represents a single language preference. The languages are ordered 438 * according to user preferences. The first language is the most preferred. 439 * @return array list of user preferred languages. 440 */ 441 public static function getUserLanguages() 442 { 443 static $languages=null; 444 if($languages===null) 445 { 446 if(!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) 447 $languages[0]='en'; 448 else 449 { 450 $languages=array(); 451 foreach(explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']) as $language) 452 { 453 $array=split(';q=',trim($language)); 454 $languages[trim($array[0])]=isset($array[1])?(float)$array[1]:1.0; 455 } 456 arsort($languages); 457 $languages=array_keys($languages); 458 if(empty($languages)) 459 $languages[0]='en'; 460 } 461 } 462 return $languages; 463 } 464 465 /** 466 * Returns the most preferred language by the client user. 467 * @return string the most preferred language by the client user, defaults to English. 468 */ 469 public static function getPreferredLanguage() 470 { 471 static $language=null; 472 if($language===null) 473 { 474 $langs=Prado::getUserLanguages(); 475 $lang=explode('-',$langs[0]); 476 if(empty($lang[0]) || !ctype_alpha($lang[0])) 477 $language='en'; 478 else 479 $language=$lang[0]; 480 } 481 return $language; 482 } 483 484 /** 485 * Writes a log message. 486 * This method wraps {@link log()} by checking the application mode. 487 * When the application is in Debug mode, debug backtrace information is appended 488 * to the message and the message is logged at DEBUG level. 489 * When the application is in Performance mode, this method does nothing. 490 * Otherwise, the message is logged at INFO level. 491 * @param string message to be logged 492 * @param string category of the message 493 * @see log, getLogger 494 */ 495 public static function trace($msg,$category='Uncategorized') 496 { 497 if(self::$_application && self::$_application->getMode()===TApplicationMode::Performance) 498 return; 499 if(!self::$_application || self::$_application->getMode()===TApplicationMode::Debug) 500 { 501 $trace=debug_backtrace(); 502 if(isset($trace[0]['file']) && isset($trace[0]['line'])) 503 $msg.=" (line {$trace[0]['line']}, {$trace[0]['file']})"; 504 $level=TLogger::DEBUG; 505 } 506 else 507 $level=TLogger::INFO; 508 self::log($msg,$level,$category); 509 } 510 511 /** 512 * Logs a message. 513 * Messages logged by this method may be retrieved via {@link TLogger::getLogs} 514 * and may be recorded in different media, such as file, email, database, using 515 * {@link TLogRouter}. 516 * @param string message to be logged 517 * @param integer level of the message. Valid values include 518 * TLogger::DEBUG, TLogger::INFO, TLogger::NOTICE, TLogger::WARNING, 519 * TLogger::ERROR, TLogger::ALERT, TLogger::FATAL. 520 * @param string category of the message 521 */ 522 public static function log($msg,$level=TLogger::INFO,$category='Uncategorized') 523 { 524 if(self::$_logger===null) 525 self::$_logger=new TLogger; 526 self::$_logger->log($msg,$level,$category); 527 } 528 529 /** 530 * @return TLogger message logger 531 */ 532 public static function getLogger() 533 { 534 if(self::$_logger===null) 535 self::$_logger=new TLogger; 536 return self::$_logger; 537 } 538 539 /** 540 * Converts a variable into a string representation. 541 * This method achieves the similar functionality as var_dump and print_r 542 * but is more robust when handling complex objects such as PRADO controls. 543 * @param mixed variable to be dumped 544 * @param integer maximum depth that the dumper should go into the variable. Defaults to 10. 545 * @param boolean whether to syntax highlight the output. Defaults to false. 546 * @return string the string representation of the variable 547 */ 548 public static function varDump($var,$depth=10,$highlight=false) 549 { 550 Prado::using('System.Util.TVarDumper'); 551 return TVarDumper::dump($var,$depth,$highlight); 552 } 553 554 /** 555 * Localize a text to the locale/culture specified in the globalization handler. 556 * @param string text to be localized. 557 * @param array a set of parameters to substitute. 558 * @param string a different catalogue to find the localize text. 559 * @param string the input AND output charset. 560 * @return string localized text. 561 * @see TTranslate::formatter() 562 * @see TTranslate::init() 563 */ 564 public static function localize($text, $parameters=array(), $catalogue=null, $charset=null) 565 { 566 Prado::using('System.I18N.Translation'); 567 $app = Prado::getApplication()->getGlobalization(false); 568 569 $params = array(); 570 foreach($parameters as $key => $value) 571 $params['{'.$key.'}'] = $value; 572 573 //no translation handler provided 574 if($app===null || ($config = $app->getTranslationConfiguration())===null) 575 return strtr($text, $params); 576 577 Translation::init(); 578 579 if(empty($catalogue) && isset($config['catalogue'])) 580 $catalogue = $config['catalogue']; 581 582 //globalization charset 583 $appCharset = $app===null ? '' : $app->getCharset(); 584 585 //default charset 586 $defaultCharset = ($app===null) ? 'UTF-8' : $app->getDefaultCharset(); 587 588 //fall back 589 if(empty($charset)) $charset = $appCharset; 590 if(empty($charset)) $charset = $defaultCharset; 591 592 return Translation::formatter()->format($text,$params,$catalogue,$charset); 593 } 594 } 595 596 /** 597 * TReflectionClass class. 598 * This class was originally written to cope with the incompatibility between different PHP versions. 599 * It is equivalent to ReflectionClass for PHP version >= 5.1.0 600 * @author Qiang Xue <qiang.xue@gmail.com> 601 * @version $Id: PradoBase.php 1481 2006-10-29 12:29:16Z xue $ 602 * @package System 603 * @since 3.0 604 */ 605 class TReflectionClass extends ReflectionClass 606 { 607 } 608 609 ?>
titre
Description
Corps
titre
Description
Corps
titre
Description
Corps
titre
Corps
| Généré le : Sun Feb 25 21:07:04 2007 | par Balluche grâce à PHPXref 0.7 |