public function __toString() { if ($this->_ob_cache !== null) { return $this->_ob_cache; } $path = $this->_path; $locale = \Gini\Config::get('system.locale'); $localeSpecificPath = "@{$locale}/{$path}"; $engines = \Gini\Config::get('view.engines'); if (isset($GLOBALS['gini.view_map'][$localeSpecificPath])) { $realPath = $GLOBALS['gini.view_map'][$localeSpecificPath]; $engine = $engines[pathinfo($realPath, PATHINFO_EXTENSION)]; } elseif (isset($GLOBALS['gini.view_map'][$path])) { $realPath = $GLOBALS['gini.view_map'][$path]; $engine = $engines[pathinfo($realPath, PATHINFO_EXTENSION)]; } else { foreach ($engines as $ext => $engine) { $realPath = \Gini\Core::locatePharFile(VIEW_DIR, "{$localeSpecificPath}.{$ext}"); if (!$realPath) { $realPath = \Gini\Core::locatePharFile(VIEW_DIR, "{$path}.{$ext}"); } if ($realPath) { break; } } } if ($engine && $realPath) { $class = '\\Gini\\View\\' . $engine; $output = \Gini\IoC::construct($class, $realPath, $this->_vars); } return $this->_ob_cache = (string) $output; }
public static function setup() { $session_conf = (array) \Gini\Config::get('system.session'); $cookie_params = (array) $session_conf['cookie']; $session_name = $session_conf['name'] ?: 'gini-session'; $host_hash = sha1($cookie_params['domain'] ?: $_SERVER['HTTP_HOST']); ini_set('session.name', $session_name . '_' . $host_hash); if ($session_conf['save_handler']) { self::$_handlerName = $session_conf['save_handler']; // save_handler = internal/files if (0 == strncmp(self::$_handlerName, 'internal/', 9)) { ini_set('session.save_handler', substr(self::$_handlerName, 9)); } else { // save_handler = Database $class = '\\Gini\\Session\\' . self::$_handlerName; if (class_exists($class)) { self::$_handler = \Gini\IoC::construct($class); session_set_save_handler(self::$_handler, false); } } } if ($session_conf['save_path']) { session_save_path($session_conf['save_path']); } if ($session_conf['gc_maxlifetime']) { ini_set('session.gc_maxlifetime', $session_conf['gc_maxlifetime']); } if (isset($_POST['gini-session'])) { session_id($_POST['gini-session']); } elseif (isset($_SERVER['HTTP_X_GINI_SESSION'])) { session_id($_SERVER['HTTP_X_GINI_SESSION']); } session_set_cookie_params($cookie_params['lifetime'], $cookie_params['path'], $cookie_params['domain']); self::open(); }
public function testBind() { $a = \Gini\IoC::construct('stdClass'); $this->assertFalse(isset($a->foo)); \Gini\IoC::bind('stdClass', function () { return (object) ['foo' => 'bar', 'uniqid' => uniqid()]; }); $a = \Gini\IoC::construct('stdClass'); $this->assertEquals($a->foo, 'bar'); $b = \Gini\IoC::construct('stdClass'); $this->assertNotEquals($a->uniqid, $b->uniqid); \Gini\IoC::singleton('stdClass', function () { return (object) ['foo' => 'bar', 'uniqid' => uniqid()]; }); $a = \Gini\IoC::construct('stdClass'); $this->assertEquals($a->foo, 'bar'); $b = \Gini\IoC::construct('stdClass'); $this->assertEquals($b->foo, 'bar'); $this->assertEquals($a->uniqid, $b->uniqid); \Gini\IoC::instance('stdClass', $a); $c = \Gini\IoC::construct('stdClass'); $this->assertEquals($c->foo, 'bar'); $this->assertEquals($a->uniqid, $c->uniqid); \Gini\IoC::clear('stdClass'); $a = \Gini\IoC::construct('stdClass'); $this->assertFalse(isset($a->foo)); }
protected function __postAction($action, &$params, $response) { parent::__postAction($action, $params, $response); if (null === $response) { $response = \Gini\IoC::construct('\\Gini\\CGI\\Response\\HTML', $this->view); } return $response; }
/** * Instantiate a database object with options. * * @param string|null $name Name of the database configured in database.yml **/ public function __construct($dsn, $username = null, $password = null, $options = null) { list($driver_name) = explode(':', $dsn, 2); $driver_class = '\\Gini\\Database\\' . $driver_name; $this->_driver = \Gini\IoC::construct($driver_class, $dsn, $username, $password, $options); if (!$this->_driver instanceof Database\Driver) { throw new Database\Exception('unknown database driver: ' . $driver_name); } }
public static function of($name) { $conf = (array) (\Gini\Config::get("cache.{$name}") ?: \Gini\Config::get("cache.default")); $_driver = $conf['driver']; if (!isset(self::$_CACHE[$_driver])) { self::$_CACHE[$_driver] = \Gini\IoC::construct('\\Gini\\Cache', $name, $conf['driver'] ?: 'none', (array) $conf['options']); } return self::$_CACHE[$_driver]; }
public function __index() { $request = @json_decode(\Gini\CGI::content(), true); if ($request === null) { $response = ['jsonrpc' => '2.0', 'error' => ['code' => -32700, 'message' => 'Parse error'], 'id' => $id]; } else { $response = \Gini\API::dispatch((array) $request); } return \Gini\IoC::construct('\\Gini\\CGI\\Response\\JSON', $response); }
public static function request($route, array $env = array()) { $args = array_map('rawurldecode', explode('/', $route)); $path = ''; $candidates = array('/index' => $args) + Util::pathAndArgs($args); $class = null; foreach (array_reverse($candidates) as $path => $params) { $path = strtr(ltrim($path, '/'), ['-' => '', '_' => '']); $basename = basename($path); $dirname = dirname($path); $class_namespace = '\\Gini\\Controller\\CGI\\'; if ($dirname != '.') { $class_namespace .= strtr($dirname, ['/' => '\\']) . '\\'; } $class = $class_namespace . $basename . '\\Index'; if (class_exists($class)) { break; } $class = $class_namespace . $basename; if (class_exists($class)) { break; } $class = $class_namespace . 'Controller' . $basename; if (class_exists($class)) { break; } if ($basename != 'index') { $class = $class_namespace . 'Index'; if (class_exists($class)) { array_unshift($params, $basename); break; } } } if (!$class || !class_exists($class, false)) { self::redirect('error/404'); } \Gini\Config::set('runtime.controller_path', $path); \Gini\Config::set('runtime.controller_class', $class); $controller = \Gini\IoC::construct($class); $action = strtr($params[0], ['-' => '', '_' => '']); if ($action && $action[0] != '_' && method_exists($controller, 'action' . $action)) { $action = 'action' . $action; array_shift($params); } elseif (method_exists($controller, '__index')) { $action = '__index'; } else { self::redirect('error/404'); } $controller->action = $action; $controller->params = $params; $controller->env = $env; return $controller; }
/** * @brief 一卡通密码验证 * * @param $username * @param $password * * @return boolean */ protected function verify($username, $password) { try { $config = (array) \Gini\Config::get('app.rpc'); $config = $config['nankai_gateway']; $api = $config['url']; $rpc = \Gini\IoC::construct('\\Gini\\RPC', $api); return !!$rpc->nankai->auth->verify($username, $password); } catch (\Exception $e) { } return false; }
public function actionCheckRemoteExists() { $dtstart = date('Y-m-d', strtotime("-3 days")); $dtend = date('Y-m-d'); $start = 0; $limit = 20; $conf = \Gini\Config::get('app.rpc')['chemdb']; $rpc1 = \Gini\IoC::construct('\\Gini\\RPC', $conf['url']); $rpc2 = self::getRPC('lab-inventory'); while (true) { $orders = Those('order')->whose('customized')->is(false)->andWhose('ctime')->isGreaterThan($dtstart)->andWhose('ctime')->isLessThan($dtend)->limit($start, $limit); if (!count($orders)) { break; } $start += $limit; $sync_inv = true; foreach ($orders as $order) { $group = $order->group; $items = $order->items; foreach ($items as $item) { $pid = $item['id']; $product = a('product', $pid); $cas_no = $product->cas_no; $type = $product->type; if ($type == 'chem_reagent' && $cas_no) { $results = $rpc1->chemDB->getChemicalTypes($cas_no); if (isset($results[$cas_no])) { $result = $results[$cas_no]; /* $result : '100-19-2'=>[hazardous, highly_toxic] */ $hazs = ['drug_precursor', 'highly_toxic', 'hazardous', 'explosive', 'psychotropic', 'narcotic']; if (count(array_intersect($hazs, $result))) { $criteria = []; $criteria['order_voucher'] = $order->voucher; $criteria['product'] = $pid; $data = $rpc2->mall->inventory->getInventory($criteria); if (!isset($data['id'])) { echo "no data\n"; // 危化品没有生成对应的存货记录, 重新生成 $product = a('product', $pid); $data = ['name' => $product->name, 'manufacturer' => $product->manufacturer, 'brand' => $product->brand, 'catalog_no' => $product->catalog_no, 'package' => $product->package, 'price' => $item['unit_price'], 'quantity' => $item['quantity'], 'user' => $order->requester->id, 'group' => $order->group->id, 'product' => $pid, 'order_voucher' => $order->voucher, 'vendor_id' => $order->vendor->id, 'vendor_name' => $order->vendor->name, 'location' => '--']; $rpc2->mall->inventory->createItem($data); } else { echo "has data\n"; } } } } } } } }
public static function setup() { $session_conf = (array) \Gini\Config::get('system.session'); $cookie_params = (array) $session_conf['cookie']; $session_name = $session_conf['name'] ?: 'gini-session'; $host_hash = sha1($cookie_params['domain'] ?: $_SERVER['HTTP_HOST']); ini_set('session.name', $session_name . '_' . $host_hash); if ($session_conf['save_handler']) { $handler_name = $session_conf['save_handler']; // save_handler = internal/files if (0 == strncmp($handler_name, 'internal/', 9)) { ini_set('session.save_handler', substr($handler_name, 9)); } else { // save_handler = Database $class = '\\Gini\\Session\\' . $handler_name; self::$_handler = \Gini\IoC::construct($class); session_set_save_handler(self::$_handler, false); } } if ($session_conf['save_path']) { session_save_path($session_conf['save_path']); } if (PHP_SAPI == 'cli') { ini_set('session.use_cookies', 0); // TODO: find a better way to save and load session id $idPath = self::_idPath(); if (file_exists($idPath)) { session_id(file_get_contents($idPath)); } } session_set_cookie_params($cookie_params['lifetime'], $cookie_params['path'], $cookie_params['domain']); if (isset($_POST['gini-session'])) { session_id($_POST['gini-session']); } elseif (isset($_SERVER['HTTP_X_GINI_SESSION'])) { session_id($_SERVER['HTTP_X_GINI_SESSION']); } set_error_handler(function () { }, E_ALL ^ E_NOTICE); session_start(); restore_error_handler(); if (!ini_get('session.use_cookies')) { // close session immediately to avoid deadlock session_write_close(); } $now = time(); foreach ((array) $_SESSION['@TIMEOUT'] as $token => $timeout) { if ($now > $timeout) { unset($_SESSION[$token]); unset($_SESSION['@TIMEOUT'][$token]); } } }
public function __index() { //获取系统维护模块的状态信息 $config = \Gini\Config::get('maintenance'); if ($config['status'] && $config['status'] == 'on') { $view_vars = $config['view_vars']; //维护模块开启时跳转到维护页面 return \Gini\IoC::construct('\\Gini\\CGI\\Response\\HTML', V('maintenance', array('maintain_end_date' => $view_vars['maintain_end_date']))); } else { //维护模块关闭时跳转到首页 return $this->redirect('/'); } }
public function __call($method, $params) { if ($method == __CLASS__) { return; } if (method_exists('\\Gini\\Those', $method)) { if (!$this->those) { $this->those = \Gini\IoC::construct('\\Gini\\Those', $this->name()); } call_user_func_array(array($this->those, $method), $params); return $this; } return call_user_func_array(array($this->object, $method), $params); }
/** * Instantiate Logger object by name. * * @param string $name Logger name */ public function __construct($name) { $this->_name = $name; $config = \Gini\Config::get("logger.{$this->_name}") ?: \Gini\Config::get('logger.default'); foreach ($config as $handlerName => $options) { if (!is_array($options)) { continue; } // ignore when "disabled" or invalid value passed. $level = isset($options['level']) ? $options['level'] : Logger\Level::DEBUG; $handlerClass = "\\Gini\\Logger\\{$handlerName}"; $handler = \Gini\IoC::construct($handlerClass, $this->_name, $level, $options); $this->_handlers[] = $handler; } }
public function actionAuthorize($clientID, $clientSecret) { $confs = \Gini\Config::get('mall.rpc'); $conf = $confs['node']; try { $rpc = \Gini\IoC::construct('\\Gini\\RPC', $conf['url']); $bool = $rpc->mall->authorize($clientID, $clientSecret); } catch (\Exception $e) { throw new \Gini\API\Exception('网络故障', 503); } if ($bool) { $this->setCurrentApp($clientID); return session_id(); } throw new \Gini\API\Exception('非法的APP', 404); }
private static function _getTagRPC() { if (self::$_tagRPC) { return self::$_tagRPC; } $conf = \Gini\Config::get('tag-db.rpc'); $tagURL = $conf['url']; $client = \Gini\Config::get('tag-db.client'); $clientID = $client['id']; $clientSecret = $client['secret']; $rpc = \Gini\IoC::construct('\\Gini\\RPC', $tagURL); if ($rpc->tagdb->authorize($clientID, $clientSecret)) { self::$_tagRPC = $rpc; } return self::$_tagRPC; }
public static function dispatch(array $data) { try { $id = $data['id'] ?: null; if (!isset($data['method']) || !isset($data['params']) || !isset($data['jsonrpc']) || !$data['method'] || $data['jsonrpc'] != '2.0') { throw new API\Exception('Invalid Request', -32600); } $path = strtolower(strtr($data['method'], ['.' => '/', '::' => '/'])); $params = $data['params']; $path_arr = explode('/', $path); $class = '\\Gini\\Controller\\API\\' . implode('\\', $path_arr); if (class_exists($class) && method_exists($class, '__invoke')) { // might not be necessary, since __invoke is the magic method since PHP 5.3 $callback = array($class, '__invoke'); } else { $method = array_pop($path_arr); if (count($path_arr) > 0) { $class = '\\Gini\\Controller\\API\\' . implode('\\', $path_arr); } else { $class = '\\Gini\\Controller\\API'; } if (class_exists($class) && $method[0] != '_') { $method = 'action' . $method; $o = \Gini\IoC::construct($class); if (method_exists($o, $method)) { $callback = array($o, $method); } elseif (function_exists($class . '\\' . $method)) { $callback = $class . '\\' . $method; } } } if (!is_callable($callback)) { throw new API\Exception('Method not found', -32601); } $result = call_user_func_array($callback, $params); if ($id !== null) { $response = ['jsonrpc' => '2.0', 'result' => $result, 'id' => $id]; } } catch (API\Exception $e) { $response = ['jsonrpc' => '2.0', 'error' => ['code' => $e->getCode(), 'message' => $e->getMessage()], 'id' => $id]; } return $response; }
public function actionExport($args) { printf("Exporting ORM structures...\n\n"); $orm_dirs = \Gini\Core::pharFilePaths(CLASS_DIR, 'Gini/ORM'); foreach ($orm_dirs as $orm_dir) { if (!is_dir($orm_dir)) { continue; } \Gini\File::eachFilesIn($orm_dir, function ($file) use($orm_dir) { $oname = strtolower(preg_replace('|.php$|', '', $file)); if ($oname == 'object') { return; } $class_name = '\\Gini\\ORM\\' . str_replace('/', '\\', $oname); // Check if it is abstract class $rc = new \ReflectionClass($class_name); if ($rc->isAbstract()) { return; } printf(" %s\n", $oname); $o = \Gini\IoC::construct($class_name); $structure = $o->structure(); // unset system fields unset($structure['id']); unset($structure['_extra']); $i = 1; $max = count($structure); foreach ($structure as $k => $v) { if ($i == $max) { break; } printf(" ├─ %s (%s)\n", $k, implode(',', array_map(function ($k, $v) { return $v ? "{$k}:{$v}" : $k; }, array_keys($v), $v))); ++$i; } printf(" └─ %s (%s)\n\n", $k, implode(',', array_map(function ($k, $v) { return $v ? "{$k}:{$v}" : $k; }, array_keys($v), $v))); }); } }
/** * Install related modules. * * @param string $argv */ public function actionInstall($argv) { count($argv) > 0 || APP_ID != 'gini' or die("Usage: gini install <module> <version>\n\n"); $controller = \Gini\IoC::construct('\\Gini\\Controller\\CLI\\Index'); $controller->actionInstall($argv); }
public static function dispatch(array $argv) { if (!isset($GLOBALS['gini.class_map'])) { echo "[33mNOTICE: You are currently executing commands without cache![0m\n\n"; } $candidates = Util::pathAndArgs($argv, true); $class = null; foreach (array_reverse($candidates) as $path => $params) { $path = strtr(ltrim($path, '/'), ['-' => '', '_' => '']); $basename = basename($path); $dirname = dirname($path); $class_namespace = '\\Gini\\Controller\\CLI\\'; if ($dirname != '.') { $class_namespace .= strtr($dirname, ['/' => '\\']) . '\\'; } $class = $class_namespace . $basename; if (class_exists($class)) { break; } $class = $class_namespace . 'Controller' . $basename; if (class_exists($class)) { break; } } if (!$class || !class_exists($class, false)) { $class = '\\Gini\\Controller\\CLI\\App'; $params = $argv; } \Gini\Config::set('runtime.controller_path', $path); \Gini\Config::set('runtime.controller_class', $class); $controller = \Gini\IoC::construct($class); $action = strtr($params[0], ['-' => '', '_' => '']); if ($action && method_exists($controller, 'action' . $action)) { $action = 'action' . $action; array_shift($params); } elseif (method_exists($controller, '__index')) { $action = '__index'; } else { $action = '__unknown'; } $controller->action = $action; $controller->params = $params; $controller->execute(); }
public function actionUpgradeId() { // ORM required class map. if (!isset($GLOBALS['gini.class_map'])) { echo "[31mYou need to run [1m\"gini cache class\"[0;31m before upgrade ORM id.[0m\n"; return; } // enumerate orms echo "Updating database structures according ORM definition...\n"; $orm_dirs = \Gini\Core::pharFilePaths(CLASS_DIR, 'Gini/ORM'); foreach ($orm_dirs as $orm_dir) { if (!is_dir($orm_dir)) { continue; } \Gini\File::eachFilesIn($orm_dir, function ($file) use($orm_dir) { $oname = preg_replace('|.php$|', '', $file); if ($oname == 'Object') { return; } $class_name = '\\Gini\\ORM\\' . str_replace('/', '\\', $oname); // Check if it is abstract class $rc = new \ReflectionClass($class_name); if ($rc->isAbstract()) { return; } $o = \Gini\IoC::construct($class_name); // some object might not have database backend $db = $o->db(); if (!$db) { return; } printf(" %s\n", $oname); $structure = $o->structure(); foreach ($structure as $field => $option) { if (isset($option['object'])) { $db->query('UPDATE :table SET :field=NULL WHERE :field=0', [':table' => $o->tableName(), ':field' => $field . '_id']); } } }); } echo " [32mdone.[0m\n"; }
public function actionSubmitApplication() { $me = _G('ME'); $group = _G('GROUP'); if (!$me->id || !$group->id || !$me->isAllowedTo('设置')) { return; } $form = $this->form('post'); $type = trim($form['type']); $casNO = trim($form['cas_no']); $volume = trim($form['volume']); $reason = trim($form['reason']); if (!$reason) { return \Gini\IoC::construct('\\Gini\\CGI\\Response\\JSON', ['code' => 1, 'message' => T('请填写申请理由')]); } $title = \Gini\ORM\ChemicalLimits\Request::getTypeTtile($type); if (!$type || !$title) { return \Gini\IoC::construct('\\Gini\\CGI\\Response\\JSON', ['code' => 2, 'message' => T('请选择分类')]); } if ($casNO) { $chemInfo = \Gini\ChemDB\Client::getChemicalInfo($casNO); if (empty($chemInfo)) { return \Gini\IoC::construct('\\Gini\\CGI\\Response\\JSON', ['code' => 3, 'message' => T('请重新选择化学品')]); } $chem = ['cas' => $casNO, 'state' => $chemInfo['state'], 'default']; } else { $chem = ['default']; } if (!\Gini\Unit\Conversion::of($chem)->validate($volume)) { return \Gini\IoC::construct('\\Gini\\CGI\\Response\\JSON', ['code' => 4, 'message' => T('上限设置格式错误,请输入数字+单位,例5mg(目前系统支持单位: 瓶/bottle/ml/g/cm3/ul/μl/ml/cl/dl/l/gal/lb/ug/μg/mg/kg/oz/lb/)')]); } $rpc = \Gini\Module\HazardousControlOrders::getRPC('chemical-limits'); $result = (bool) $rpc->admin->inventory->addRequest(['type' => $type, 'cas_no' => $casNO, 'volume' => $volume, 'group_id' => $group->id, 'owner_id' => $me->id, 'reason' => $reason]); return \Gini\IoC::construct('\\Gini\\CGI\\Response\\JSON', ['code' => $result ? 0 : 5, 'message' => $result ? T('上限申请提交成功') : T('提交上限申请失败,请重试')]); }
public function tearDown() { \Gini\IoC::clear('\\Gini\\ORM\\User'); parent::tearDown(); }
function SQL($SQL) { return \Gini\IoC::construct('\\Gini\\Those\\SQL', $SQL); }
/** * Set raw data of the object. * * @param string $data */ public function setData(array $data) { $this->_db_data = $data; $this->_db_time = time(); $this->_objects = []; $this->_oinfo = []; foreach ($this->structure() as $k => $v) { if (array_key_exists('object', $v)) { $oname = $v['object']; $o = $data[$k]; if (isset($o) && $o instanceof \Gini\ORM\Object && isset($oname) && $o->name() == $oname) { $this->{$k} = $o; } else { //object need to be bind later to avoid deadlock. unset($this->{$k}); if (!isset($oname)) { $oname = strval($data[$k . '_name']); } if ($oname) { $oi = (object) ['name' => $oname, 'id' => $data[$k . '_id']]; $this->_oinfo[$k] = $oi; } } } elseif (array_key_exists('array', $v)) { $this->{$k} = @json_decode(strval($data[$k]), true); } elseif (array_key_exists('object_list', $v)) { $objects = \Gini\IoC::construct('\\Gini\\ORMIterator', $v['object_list']); $oids = (array) @json_decode(strval($data[$k]), true); array_walk($oids, function ($id) use($objects) { $objects[$id] = true; }); $this->{$k} = $objects; } else { $this->{$k} = $data[$k]; } } return $this; }
function V($path, $vars = null) { return \Gini\IoC::construct('\\Gini\\View', $path, $vars); }
public static function getRPC($type = 'lab-inventory') { $confs = \Gini\Config::get('app.rpc'); $conf = $confs[$type] ?: []; if (!self::$_RPCs[$type]) { $rpc = \Gini\IoC::construct('\\Gini\\RPC', $conf['url']); self::$_RPCs[$type] = $rpc; if ($type == 'lab-inventory') { $token = $rpc->mall->authorize($conf['client_id'], $conf['client_secret']); if (!$token) { \Gini\Logger::of('lab-orders')->error('Mall\\RObject getRPC: authorization failed with {client_id}/{client_secret} !', ['client_id' => $conf['client_id'], 'client_secret' => $conf['client_secret']]); } } } return self::$_RPCs[$type]; }