Exemplo n.º 1
1
 public static function exceptionHandle(Exception $exception)
 {
     if (DEBUG_MODE) {
         //直接输出调试信息
         echo nl2br($exception->__toString());
         echo '<hr /><p>Router:</p><pre>';
         print_r(Singleton::getInstance('Router'));
         echo '</pre>';
     } else {
         $code = $exception->getCode();
         $message = nl2br($exception->getMessage());
         /*
                     如果错误码"可能为"合法的http状态码则尝试设置,
                     setStatus()方法会忽略非法的http状态码. */
         if ($code >= 400 && $code <= 505 && !headers_sent()) {
             ResponseModule::setStatus($code);
         }
         $var_list = array('message' => $message, 'code' => $code, 'file' => $exception->getFile(), 'url' => Singleton::getInstance('Router')->getUrl());
         if ($error_file = self::_getErrorFilePath($code)) {
             Lugit::$view = new View($var_list);
             Lugit::$view->render($error_file);
         } else {
             echo 'No error page is found.<pre>';
             print_r($var_list);
             echo '</pre>';
         }
     }
     exit;
 }
Exemplo n.º 2
0
 public function __construct()
 {
     session_start();
     $this->view = new View(Singleton::getInstance()->r->getController());
     $menu = array();
     if ($this->sesionIniciada()) {
         $this->view->setMsgBienvenida($this->getSesionVar("ROL") . " : " . $this->getSesionVar("NOMBRE") . " " . $this->getSesionVar("APELLIDO"));
         switch ($this->getRol()) {
             case ROL_ADMINISTRADOR:
                 $this->crearMenu($menu, "usuario/consultarUsuarios", 'Usuarios');
                 $this->crearMenu($menu, "preguntas/crearPreguntas", 'Preguntas');
                 $this->crearMenu($menu, "tipoMedicamento/consultarTipoMedicamentos", 'Tipos de Medicamentos');
                 $this->crearMenu($menu, "bodega/consultarBodegas", 'Bodega');
                 $this->crearMenu($menu, "medicamento/consultarMedicamentos", 'Medicamentos');
                 $this->crearMenu($menu, "empresa/consultarEmpresas", 'Empresas');
                 $this->crearMenu($menu, "pedido/consultarPedidos", 'PEDIDOS');
                 break;
             case ROL_REPARTIDOR:
                 $this->crearMenu($menu, "repartidor/consultarPedidosAsignados", 'Pedidos asignados');
                 break;
             case ROL_CLIENTE:
                 $this->crearMenu($menu, "cliente/consultarPedidos", 'PEDIDOS');
                 break;
             default:
                 break;
         }
         $this->crearMenu($menu, "usuario/consultar", 'Consulta de datos');
         $this->crearMenu($menu, "usuario/modificar", 'Modificar datos');
         $this->crearMenu($menu, "usuario/eliminar", 'Eliminar cuenta');
         $this->crearMenu($menu, "usuario/cerrarSesion", 'Cerrar sesión ');
         $this->view->setMenu($menu);
     }
 }
Exemplo n.º 3
0
 /**
  * 获得控件值.
  * 
  * @access private
  * @param mixed $name
  * @return void
  */
 private function _getValue($name, $defaultValue)
 {
     if (!($value = Singleton::getInstance('ResponseModule')->request->filter('htmlspecialchars')->{$name})) {
         $value = $defaultValue;
     }
     $value = $value ? " value=\"{$value}\"" : '';
 }
Exemplo n.º 4
0
 public function bRegisterUser($reg_email, $reg_fname, $reg_aname)
 {
     # get the connection
     $mysqli = Parent::connect();
     # get password generator
     $oPassword = Singleton::getInstance('Password');
     # get a random password
     $random_password = $oPassword->encryptPassword();
     # check if succeed otherwise try again
     if (!$random_password) {
         $random_password = $oPassword->randomPassword();
     }
     #lowercase email
     $slEmail = strtolower($reg_email);
     if ($sStmt = $mysqli->prepare("INSERT INTO `users`(`username`, `password`, `voornaam`, `achternaam`, `email`) VALUES (?,?,?,?,?)")) {
         # bind
         $sStmt->bind_param('sssss', $reg_fname, $random_password, $reg_fname, $reg_aname, $reg_email);
         # execute
         if ($sStmt->execute()) {
             User::sendRegistrationMail($reg_email, $random_password);
         } else {
             echo "een paar fouten";
         }
     }
 }
 /**
  * @throws WrongArgumentException
  * @return PrimitiveForm
  * 
  * @deprecated You should use ofProto() instead
  **/
 public function of($className)
 {
     Assert::classExists($className);
     $protoClass = EntityProto::PROTO_CLASS_PREFIX . $className;
     Assert::classExists($protoClass);
     return $this->ofProto(Singleton::getInstance($protoClass));
 }
 public function testStaticMethodCalling()
 {
     $this->assertEquals(ClassUtils::callStaticMethod('Singleton::getInstance', 'UrlEncodeFilter'), Singleton::getInstance('UrlEncodeFilter'));
     $this->assertEquals(ClassUtils::callStaticMethod('ImaginaryDialect::me'), ImaginaryDialect::me());
     try {
         ClassUtils::callStaticMethod('InexistantClass::InSaNeMeThOd');
         $this->fail();
     } catch (ClassNotFoundException $e) {
         /* first pass */
     } catch (WrongArgumentException $e) {
         /* and all others */
     }
     try {
         ClassUtils::callStaticMethod('complete nonsense');
         $this->fail();
     } catch (WrongArgumentException $e) {
         /* pass */
     }
     try {
         ClassUtils::callStaticMethod('Identifier::comp::lete::non::sense');
         $this->fail();
     } catch (WrongArgumentException $e) {
         /* pass */
     }
 }
Exemplo n.º 7
0
 public function transform()
 {
     // get transformed document
     $doc = $this->__Document->transform();
     // set content of body
     $this->__Layout->__Body()->write($doc);
     // Verbrauchter PHP Speicher (RAM)
     $memory = fbytes(memory_get_usage());
     // Skriptlaufzeit
     $runtime = round(microtime(true) - RUNTIME, 5);
     $req = Singleton::getInstance('HTTP_Request');
     if (substr_count($req->getRequestUri(), 'ajax.') > 0) {
         return $this->__Layout->getAJAX();
     }
     $this->__Layout->__Body()->write('<!-- runtime: ' . $runtime . ' // memory usage: ' . $memory . ' -->');
     // check logfiles
     $sys_logs = scandir(LOG_PATH);
     if (count($sys_logs) > 2) {
         jgrowl(count($sys_logs) - 2 . ' Log(s) verfügbar', 'Systemfehler', 'warning');
     }
     $app_logs = scandir(RESOURCE_PATH . '/logs');
     if (count($app_logs) > 2) {
         jgrowl(count($app_logs) - 2 . ' Log(s) verfügbar', 'Anwendungsfehler', 'warning');
     }
     $notes = Singleton::getInstance('Watchdog')->getNotifications();
     $this->__Layout->__Body()->write($notes);
     return $this->__Layout->getLayout();
     // end function
 }
Exemplo n.º 8
0
 private function setupDataBaseConnection()
 {
     $this->db = Singleton::getInstance(DataBase::class);
     if (!$this->db->isConnected()) {
         $this->db->setType(DataBaseConfig::TYPE);
         $this->db->connect(DataBaseConfig::HOST, DataBaseConfig::USER, DataBaseConfig::PWD, DataBaseConfig::DB);
     }
 }
Exemplo n.º 9
0
 public static function run()
 {
     self::initConst();
     date_default_timezone_set('Etc/GMT-8');
     error_reporting(DEBUG_MODE ? E_ALL : E_ALL ^ E_NOTICE ^ E_WARNING);
     set_exception_handler(array('Basic', 'exceptionHandle'));
     Singleton::getInstance('Router')->dispatch();
 }
Exemplo n.º 10
0
 public function __construct()
 {
     # set table name
     parent::__construct('users');
     # get the database and mysqli instance since this is the model
     $oDatabase = Singleton::getInstance('Database');
     $this->mysqli = $oDatabase->connect();
 }
Exemplo n.º 11
0
 public function testSingleton()
 {
     $obj = Singleton::getInstance();
     try {
         $demo = clone $obj;
     } catch (\Exception $e) {
         $this->assertEquals('f**k you', $e->getMessage());
     }
 }
Exemplo n.º 12
0
 public static function getKmz()
 {
     $sql = "SELECT * FROM species_tree_nominal where class='Aves'";
     $_SQL = Singleton::getInstance(SQL_DRIVER);
     $res = $_SQL->sql_query($sql);
     while ($ob = $_SQL->sql_fetch_object($res)) {
         shell_exec("cd /home/www/species/tmp/kmz/; wget http://www.xeno-canto.org/ranges/" . str_replace(" ", "_", $ob->nominal) . ".kmz");
     }
 }
Exemplo n.º 13
0
 public function __get($key)
 {
     $key = ucfirst(strtolower($key));
     if (class_exists($key . 'Module')) {
         return Singleton::getInstance($key . 'Module');
     } else {
         return null;
     }
 }
Exemplo n.º 14
0
 public function __construct()
 {
     # set table name
     parent::__construct('files');
     # get the database and mysqli instance since this is the model
     $oDatabase = Singleton::getInstance('Database');
     $this->mysqli = $oDatabase->connect();
     $oUser = Singleton::getInstance('User');
     $iUserid = $oUser->getUserId();
     $this->userid = $iUserid;
 }
Exemplo n.º 15
0
 /**
  * 应用验证器并返回过滤后的结果.
  * 用法:
  * Singleton->getInstance('ValidatorModule')->applyValidator('not_empty', '');
  * //返回false
  *
  * Singleton->getInstance('ValidatorModule')->applyValidator('not_empty', array('', 'abc'));
  * //返回false
  *
  * 支持静态方法
  * Singleton->getInstance('ValidatorModule')->applyValidator('YourClass::yourMethod', 'abc');
  *
  * @access public
  * @param string $validator 验证器名称
  * @param mixed $data 要处理的数据
  * @return bool 验证结果
  */
 public function applyValidator($validator, $data)
 {
     $result = Singleton::getInstance('FilterModule')->applyFilter($validator, $data);
     if (is_array($result)) {
         foreach ($result as $v) {
             if (!$v) {
                 return false;
             }
         }
         return true;
     }
     return (bool) $result;
 }
Exemplo n.º 16
0
/**
 * @throws \Exception                       - if no parameter are given
 * @throws UnexpectedParameterTypeException - if first parameter is not a string
 *
 * @returns (mixed) - the result of the query-definition execution
 *
 * expect a list of parameter with at least one value. the
 * list is handled over to the queue, which will executed
 * with them
 *
 * in the end a result of the execution of the query-definition
 * through the stored handler is returned
 *
 **/
function get()
{
    $arrParameter = func_get_args();
    if (empty($arrParameter)) {
        throw new \Exception("no parameter given for execution");
    }
    if (!is_string($arrParameter[0])) {
        throw new UnexpectedParameterTypeException('string', $arrParameter[0]);
    }
    # get instance of queue and work with a copy of it
    $objQueue = Singleton::getInstance('\\DDDBL\\Queue');
    $objQueue = $objQueue->getClone();
    return $objQueue->execute($arrParameter);
}
Exemplo n.º 17
0
 public function initCore()
 {
     // get registry instance
     $this->__Registry = Singleton::getInstance('Registry');
     // get document instance
     $this->__Layout = Singleton::getInstance('Layout');
     // get session instance
     $this->__Session = Singleton::getInstance('Session');
     // get cookie instance
     $this->__Cookie = Singleton::getInstance('Cookie');
     // get cache instance
     $this->__Cache = Singleton::getInstance('Cache');
     // end function
 }
Exemplo n.º 18
0
 public static function suite()
 {
     $suite = new TestSuite('onPHP-' . ONPHP_VERSION);
     foreach (self::$paths as $testPath) {
         foreach (glob($testPath . '*Test' . EXT_CLASS, GLOB_BRACE) as $file) {
             $suite->addTestFile($file);
         }
     }
     // meta, DB and DAOs ordered tests portion
     if (self::$dbs) {
         try {
             Singleton::getInstance('DBTestPool', self::$dbs)->connect();
         } catch (Exception $e) {
             Singleton::dropInstance('DBTestPool');
             Singleton::getInstance('DBTestPool');
         }
         // build stuff from meta
         $metaDir = ONPHP_TEST_PATH . 'meta' . DIRECTORY_SEPARATOR;
         $path = ONPHP_META_PATH . 'bin' . DIRECTORY_SEPARATOR . 'build.php';
         $_SERVER['argv'] = array();
         $_SERVER['argv'][0] = $path;
         $_SERVER['argv'][1] = $metaDir . 'config.inc.php';
         $_SERVER['argv'][2] = $metaDir . 'config.meta.xml';
         $_SERVER['argv'][] = '--force';
         $_SERVER['argv'][] = '--no-schema-check';
         $_SERVER['argv'][] = '--drop-stale-files';
         include $path;
         // provide paths to autogenerated stuff
         set_include_path(get_include_path() . PATH_SEPARATOR . ONPHP_META_AUTO_BUSINESS_DIR . PATH_SEPARATOR . ONPHP_META_AUTO_DAO_DIR . PATH_SEPARATOR . ONPHP_META_AUTO_PROTO_DIR . PATH_SEPARATOR . ONPHP_META_DAO_DIR . PATH_SEPARATOR . ONPHP_META_BUSINESS_DIR . PATH_SEPARATOR . ONPHP_META_PROTO_DIR);
         $daoTest = new DAOTest();
         $out = MetaConfiguration::me()->getOutput();
         foreach (DBTestPool::me()->getPool() as $connector => $db) {
             DBPool::me()->setDefault($db);
             $out->info('Using ')->info(get_class($db), true)->infoLine(' connector.');
             try {
                 $daoTest->drop();
             } catch (DatabaseException $e) {
                 // previous shutdown was clean
             }
             $daoTest->create()->fill(false);
             MetaConfiguration::me()->checkIntegrity();
             $out->newLine();
             $daoTest->drop();
         }
         DBPool::me()->dropDefault();
     }
     $suite->addTestSuite('DAOTest');
     return $suite;
 }
 public function testRecursionObjects()
 {
     foreach (DBTestPool::me()->getPool() as $db) {
         DBPool::me()->setDefault($db);
         $parentProperties = Singleton::getInstance('ProtoTestParentObject')->getPropertyList();
         $resultRoot = $parentProperties['root']->getFetchStrategyId() == FetchStrategy::LAZY;
         $childProperties = Singleton::getInstance('ProtoTestChildObject')->getPropertyList();
         $resultParent = $childProperties['parent']->getFetchStrategyId() == FetchStrategy::LAZY;
         $selfRecursiveProperties = Singleton::getInstance('ProtoTestSelfRecursion')->getPropertyList();
         $resultSelfRecursive = $selfRecursiveProperties['parent']->getFetchStrategyId() == FetchStrategy::LAZY;
         $this->assertTrue($resultRoot);
         $this->assertTrue($resultParent);
         $this->assertTrue($resultSelfRecursive);
     }
 }
Exemplo n.º 20
0
 static function register($username, $email, $password)
 {
     $db = Singleton::getInstance();
     $conn = $db->conn;
     $q = $conn->prepare("insert into users values('', :username, :email, password(:password),'0')");
     $q->bindParam(":username", $username);
     $q->bindParam(":email", $email);
     $q->bindParam(":password", $password);
     $q->execute();
     if ($q->rowCount() > 0) {
         return true;
     } else {
         return false;
     }
 }
 private function createContainers()
 {
     $ringDir = ONPHP_TEMP_PATH . 'tests/main/data/ring';
     $converter = ObjectToDirectoryBinder::create(Singleton::getInstance('EntityProtoDirectoryItem'))->setDirectory($ringDir);
     $itemsConverter = $converter->cloneInnerBuilder('items');
     $ringListHead = DirectoryItem::create()->setId('421');
     $result = $itemsConverter->makeList(array($ringListHead));
     $ringListHead->setInner($items[2] = DirectoryItem::create()->setId('422')->setInner($items[1] = DirectoryItem::create()->setId('423')->setInner($items[0] = DirectoryItem::create()->setId('424')->setInner($ringListHead))));
     // storing head again to update inner link
     $items[3] = $ringListHead;
     $result = $itemsConverter->makeList($items);
     $mainContainer = DirectoryItem::create()->setTextField('main container');
     $mainContainer->setInner($ringListHead);
     // storing the container with its link to ring list head
     $result = $converter->make($mainContainer);
 }
Exemplo n.º 22
0
 public static function suite()
 {
     $suite = new TestSuite('onPHP-' . ONPHP_VERSION);
     // meta, DB and DAOs ordered tests portion
     if (self::$dbs) {
         try {
             /**
              * @todo fail - constructor with argument, but static method 'me' - without
              */
             Singleton::getInstance('DBTestPool', self::$dbs)->connect();
         } catch (Exception $e) {
             Singleton::dropInstance('DBTestPool');
             Singleton::getInstance('DBTestPool');
         }
         // build stuff from meta
         $metaDir = ONPHP_TEST_PATH . 'meta' . DIRECTORY_SEPARATOR;
         $path = ONPHP_META_PATH . 'bin' . DIRECTORY_SEPARATOR . 'build.php';
         $_SERVER['argv'] = array();
         $_SERVER['argv'][0] = $path;
         $_SERVER['argv'][1] = $metaDir . 'config.inc.php';
         $_SERVER['argv'][2] = $metaDir . 'config.meta.xml';
         $_SERVER['argv'][] = '--force';
         $_SERVER['argv'][] = '--no-schema-check';
         $_SERVER['argv'][] = '--drop-stale-files';
         include $path;
         AutoloaderPool::get('onPHP')->addPaths(array(ONPHP_META_AUTO_BUSINESS_DIR, ONPHP_META_AUTO_DAO_DIR, ONPHP_META_AUTO_PROTO_DIR, ONPHP_META_DAO_DIR, ONPHP_META_BUSINESS_DIR, ONPHP_META_PROTO_DIR));
         $dBCreator = DBTestCreator::create()->setSchemaPath(ONPHP_META_AUTO_DIR . 'schema.php')->setTestPool(DBTestPool::me());
         $out = MetaConfiguration::me()->getOutput();
         foreach (DBTestPool::me()->getPool() as $connector => $db) {
             DBPool::me()->setDefault($db);
             $out->info('Using ')->info(get_class($db), true)->infoLine(' connector.');
             $dBCreator->dropDB(true);
             $dBCreator->createDB()->fillDB();
             MetaConfiguration::me()->checkIntegrity();
             $out->newLine();
             $dBCreator->dropDB();
         }
         DBPool::me()->dropDefault();
     }
     foreach (self::$paths as $testPath) {
         foreach (glob($testPath . '*Test' . EXT_CLASS, GLOB_BRACE) as $file) {
             $suite->addTestFile($file);
         }
     }
     return $suite;
 }
Exemplo n.º 23
0
 public function update()
 {
     $db = Singleton::getInstance();
     $conn = $db->conn;
     $q = "update " . static::$table . " set ";
     foreach ($this as $k => $v) {
         if ($k == static::$key) {
             continue;
         }
         $q .= $k . "='" . $v . "',";
     }
     $q = rtrim($q, ",");
     $keyField = static::$key;
     $q .= " where " . $keyField . " = " . $this->{$keyField};
     $prep = $conn->prepare($q);
     $prep->execute();
 }
 public function testArguments()
 {
     // cleaning up
     try {
         Singleton::dropInstance(self::SINGLE_CLASS_NAME);
     } catch (MissingElementException $e) {
         // that's ok for the first pass
     }
     try {
         Singleton::getInstance(self::SINGLE_CLASS_NAME);
         $this->fail();
     } catch (BaseException $e) {
         // pass
     }
     $this->assertSameInstances(self::SINGLE_CLASS_NAME, Singleton::getInstance(self::SINGLE_CLASS_NAME, 'val1'), Singleton::getInstance(self::SINGLE_CLASS_NAME, 'val2'));
     $this->assertSameInstances(self::MULTI_CLASS_NAME, Singleton::getInstance(self::MULTI_CLASS_NAME, 'val1', 'val2', 'val3'), Singleton::getInstance(self::MULTI_CLASS_NAME, 'val1', 'val2'));
 }
Exemplo n.º 25
0
 protected function __construct()
 {
     $this->_cookieModule = Singleton::getInstance('CookieModule');
     $this->_sessionModule = Singleton::getInstance('SessionModule');
     if (defined('SALT')) {
         $this->salt = SALT;
     } else {
         throw new Exception('"SALT" is not defined.');
     }
     if (!isset($this->_sessionModule->username) || !isset($this->_sessionModule->password)) {
         $username = $this->_cookieModule->get(md5('username' . $this->salt));
         $password = $this->_cookieModule->get(md5('password' . $this->salt));
         if (isset($username) && isset($password)) {
             $password = Basic::authcode($password, 'DECODE', $this->salt);
             $this->_sessionModule->username = $username;
             $this->_sessionModule->password = $password;
         }
     }
     $this->username = $this->_sessionModule->username;
     $this->password = $this->_sessionModule->password;
 }
Exemplo n.º 26
0
 private function checkUrl()
 {
     if ($this->controllerName == 'index' && $this->actionName == 'index' && !$this->array_parameter) {
         $url = '';
     } elseif ($this->actionName == 'index' && !$this->array_parameter) {
         $url = '/' . $this->controllerName;
     } else {
         $url = '/' . $this->controllerName . '/' . $this->actionName;
     }
     if ($this->array_parameter) {
         foreach ($this->array_parameter as $v) {
             $url .= '/' . $v;
         }
     }
     if (!$url) {
         $url = '/';
     }
     if ($this->url_get) {
         $url .= '?' . $this->url_get;
     }
     if ($url != $this->full_url_path) {
         Singleton::getInstance('ResponseModule')->redirect($url, true);
     }
 }
Exemplo n.º 27
0
 public static function main()
 {
     $instance = Singleton::getInstance();
     $instance->test();
 }
Exemplo n.º 28
0
                $code = 'class ' . $class . ' extends Model
                         {
                             public function __construct($mixed = null, $column = \'id\')
                             {
                                 parent::__construct($mixed, $column);
                             }
                         }';
                eval($code);
            }
        }
    }
}
spl_autoload_register('autoload');
/* INIT */
// --- clockwork
Singleton::getInstance('Clockwork')->init();
// --- error handling
if (!Config::getSetting('debug')) {
    error_reporting(0);
    ini_set('display_errors', false);
}
// --- sanitize
if (Clockwork::isLibraryLoaded('sanitize') && Config::getSetting('sanitize_request')) {
    $_REQUEST = array();
    $_GET = sanitize($_GET);
    $_POST = sanitize($_POST);
}
// --- CSRF
if (Clockwork::isModuleLoaded('CSRF') && $_POST) {
    try {
        CSRF::check($_POST['CSRF-key']);
Exemplo n.º 29
0
 /**
  * @depends testStaticAttributesBackupPre
  */
 public function testStaticAttributesBackupPost()
 {
     $this->assertNotSame($GLOBALS['singleton'], Singleton::getInstance());
     $this->assertSame(0, self::$_testStatic);
 }
Exemplo n.º 30
0
<?php

class Singleton
{
    private static $instance;
    private function __construct()
    {
        echo "You created Singleton";
    }
    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }
    }
}
Singleton::getInstance();
Singleton::getInstance();