/** * pharのパスを通す * @param string $path * @param string $namespace */ public static function phar($path, $namespace = null) { /** * @param string $arg1 pahrが格納されているディレクトリ */ $base = \ebi\Conf::get('path', getcwd()); $path = realpath(\ebi\Util::path_absolute($base, $path)); if (isset(self::$read[$path])) { return true; } if ($path === false) { throw new \ebi\exception\InvalidArgumentException($path . ' not found'); } if (!empty($namespace)) { $namespace = str_replace("\\", '/', $namespace); if ($namespace[0] == '/') { $namespace = substr($namespace, 1); } } $package_dir = 'phar://' . (is_dir('phar://' . $path . '/src/') ? $path . '/src' : $path); spl_autoload_register(function ($c) use($package_dir, $namespace) { $c = str_replace(array('\\', '_'), '/', $c); if ((empty($namespace) || strpos($c, $namespace) === 0) && is_file($f = $package_dir . '/' . $c . '.php')) { require_once $f; } return false; }, true, false); self::$read[$path] = true; return true; }
/** * セッションを開始する * @param string $name * @return $this * */ public function __construct($name = 'sess') { $this->ses_n = $name; if ('' === session_id()) { $cookie_params = \ebi\Conf::cookie_params(); session_name($cookie_params['session_name']); session_cache_expire($cookie_params['session_expire']); session_cache_limiter($cookie_params['session_limiter']); if ($cookie_params['cookie_lifetime'] > 0 || $cookie_params['cookie_path'] != '/' || !empty($cookie_params['cookie_domain']) || $cookie_params['cookie_secure'] !== false) { session_set_cookie_params($cookie_params['cookie_lifetime'], $cookie_params['cookie_path'], $cookie_params['cookie_domain'], $cookie_params['cookie_secure']); } if (static::has_class_plugin('session_read')) { ini_set('session.save_handler', 'user'); session_set_save_handler([$this, 'open'], [$this, 'close'], [$this, 'read'], [$this, 'write'], [$this, 'destroy'], [$this, 'gc']); if (isset($this->vars[session_name()])) { session_regenerate_id(true); } } session_start(); register_shutdown_function(function () { if ('' != session_id()) { session_write_close(); } }); } }
/** * @plugin ebi.Flow * @param \Exception $exception */ public function flow_exception(\Exception $exception) { if (!$exception instanceof \ebi\Exceptions) { $exception = ['' => $exception]; } if (strpos(strtolower((new \ebi\Env())->get('HTTP_ACCEPT')), 'application/json') !== false) { $message = []; foreach ($exception as $g => $e) { $em = ['message' => $e->getMessage(), 'type' => basename(str_replace("\\", '/', get_class($e)))]; if (!empty($g)) { $em['group'] = $g; } $message[] = $em; } \ebi\HttpHeader::send('Content-Type', 'application/json'); print \ebi\Json::encode(['error' => $message]); } else { $xml = new \ebi\Xml('error'); foreach ($exception as $g => $e) { $message = new \ebi\Xml('message', $e->getMessage()); $type = basename(str_replace("\\", '/', get_class($e))); if (!empty($g)) { $message->add('group', $g); } $message->add('type', $type); $xml->add($message); } \ebi\HttpHeader::send('Content-Type', 'application/xml'); /** * @param string $encoding XML宣言のencoding */ print $xml->get(\ebi\Conf::get('encoding')); } }
public function before_flow_action() { /** * @param string $origin 許可するURL */ $origin = \ebi\Conf::get('origin'); \ebi\HttpHeader::cors_origin($origin); }
/** * 入力された文字を返す * @request string $abc 返す文字列 * @context string $abc 入力された文字列 */ public function abc() { /** * Confのダミー * @param string $aa ダミー * @see https://github.com/tokushima/ebi */ $value = \ebi\Conf::get('value'); $var = isset($_GET['abc']) ? $_GET['abc'] : null; return ['abc' => $var]; }
/** * @plugin ebi.Temaplte * @param string $src * @return Ambigous <string, string, mixed>|string */ public function before_template($src) { /** * @param string $path テンプレートパーツのファイルがあるディレクトリ */ $path = \ebi\Util::path_slash(\ebi\Conf::get('path', \ebi\Conf::resource_path('parts')), null, true); return \ebi\Xml::find_replace($src, 'rt:parts', function ($xml) use($path) { $href = \ebi\Util::path_absolute($path, $xml->in_attr('href')); if (!is_file($href)) { throw new \ebi\exception\InvalidArgumentException($href . ' not found'); } return file_get_contents($href); }); }
/** * コンストラクタ * @param string{} $def 接続情報 [type,host,name,port,user,password,sock,encode,timezone] */ public function __construct(array $def = []) { if (empty($def)) { /** * @param string{} $connection デフォルトの接続情報 [type,host,name,port,user,password,sock,encode,timezone] */ $def = \ebi\Conf::gets('connection'); } $type = isset($def['type']) ? $def['type'] : null; $host = isset($def['host']) ? $def['host'] : null; $dbname = isset($def['name']) ? $def['name'] : null; $port = isset($def['port']) ? $def['port'] : null; $user = isset($def['user']) ? $def['user'] : null; $password = isset($def['password']) ? $def['password'] : null; $sock = isset($def['sock']) ? $def['sock'] : null; $encode = isset($def['encode']) ? $def['encode'] : null; $timezone = isset($def['timezone']) ? $def['timezone'] : null; if (empty($type)) { $type = \ebi\SqliteConnector::type(); } if (empty($encode)) { $encode = 'utf8'; } try { $type = \ebi\Util::get_class_name($type); } catch (\InvalidArgumentException $e) { throw new \ebi\exception\ConnectionException('could not find connector `' . $type . '`'); } $r = new \ReflectionClass($type); $this->dbname = $dbname; $this->connector = $r->newInstanceArgs([$encode, $timezone]); if (!$this->connector instanceof \ebi\DbConnector) { throw new \ebi\exception\ConnectionException('must be an instance of \\ebi\\DbConnector'); } if (self::$autocommit === null) { /** * @param boolean $autocommit オートコミットを行うかの真偽値 */ self::$autocommit = \ebi\Conf::get('autocommit', false); } $this->connection = $this->connector->connect($this->dbname, $host, $port, $user, $password, $sock, self::$autocommit); if (empty($this->connection)) { throw new \ebi\exception\ConnectionException('connection fail ' . $this->dbname); } if (self::$autocommit !== true) { $this->connection->beginTransaction(); } }
/** * @plugin \ebi\Log * @param \ebi\Log $log */ public function log_output(\ebi\Log $log) { $msg = (string) $log; /** * @param boolean $color 出力にカラーコードを適用する */ if (\ebi\Conf::get('color', true) === true) { $color = [-1 => 0, 0 => '1;35', 1 => '1;35', 2 => '0;31', 3 => '0;31', 4 => '0;33', 5 => '0;36', 6 => '0;36', 7 => 0]; if (!empty($color[$log->level()])) { $msg = "[0;" . $color[$log->level()] . "m" . $msg . "[0m"; } } if ($log->level() > 3 || $log->level() == -1) { file_put_contents('php://stdout', $msg . PHP_EOL); } else { file_put_contents('php://stderr', $msg . PHP_EOL); } }
private function ___fm___($f = null, $d = null) { $p = $this->_; $v = method_exists($this, $m = '__get_' . $p . '__') ? call_user_func([$this, $m]) : $this->___get___(); switch ($this->prop_anon($p, 'type')) { case 'timestamp': return $v === null ? null : date(empty($f) ? \ebi\Conf::timestamp_format() : $f, (int) $v); case 'date': return $v === null ? null : date(empty($f) ? \ebi\Conf::date_format() : $f, (int) $v); case 'time': if ($v === null) { return 0; } $h = floor($v / 3600); $i = floor(($v - $h * 3600) / 60); $s = floor($v - $h * 3600 - $i * 60); $m = str_replace(' ', '0', rtrim(str_replace('0', ' ', substr($v - $h * 3600 - $i * 60 - $s, 2, 12)))); return ($h == 0 ? '' : $h . ':') . sprintf('%02d:%02d', $i, $s) . ($m == 0 ? '' : '.' . $m); case 'intdate': if ($v === null) { return null; } return str_replace(['Y', 'm', 'd'], [substr($v, 0, -4), substr($v, -4, 2), substr($v, -2, 2)], empty($f) ? \ebi\Conf::date_format() : $f); case 'boolean': return $v ? isset($d) ? $d : 'true' : (empty($f) ? 'false' : $f); } return $v; }
<?php \ebi\Conf::set(\ebi\Db::class, 'autocommit', true); \testman\Conf::set('urls', \ebi\Dt::get_urls()); \testman\Conf::set('ssl-verify', false); \testman\Conf::set('coverage-dir', dirname(__DIR__) . '/lib');
/** * ライブラリ一覧 * @return array */ public static function classes($parent_class = null, $ignore = true) { $result = []; $include_path = []; $ignore_class = []; if (is_dir(getcwd() . DIRECTORY_SEPARATOR . 'lib')) { $include_path[] = realpath(getcwd() . DIRECTORY_SEPARATOR . 'lib'); } if (class_exists('Composer\\Autoload\\ClassLoader')) { $r = new \ReflectionClass('Composer\\Autoload\\ClassLoader'); $vendor_dir = dirname(dirname($r->getFileName())); if (is_file($loader_php = $vendor_dir . DIRECTORY_SEPARATOR . 'autoload.php')) { $loader = (include $loader_php); // vendor以外の定義されているパスを探す foreach ($loader->getPrefixes() as $ns) { foreach ($ns as $path) { $path = realpath($path); if (strpos($path, $vendor_dir) === false) { $include_path[] = $path; } } } } } $valid_find_class_file = function ($f) { if (strpos($f->getPathname(), DIRECTORY_SEPARATOR . '.') === false && strpos($f->getPathname(), DIRECTORY_SEPARATOR . '_') === false && strpos($f->getPathname(), DIRECTORY_SEPARATOR . 'cmd' . DIRECTORY_SEPARATOR) === false && ctype_upper(substr($f->getFilename(), 0, 1)) && substr($f->getFilename(), -4) == '.php') { try { include_once $f->getPathname(); } catch (\Exeption $e) { } } }; foreach ($include_path as $libdir) { if ($libdir !== '.' && is_dir($libdir)) { foreach (\ebi\Util::ls($libdir, true) as $f) { $valid_find_class_file($f); } } } /** * @param string[] $vendor 利用するvendorのクラス */ $use_vendor = \ebi\Conf::gets('use_vendor'); /** * @param callback $callback 利用するvendorのクラス配列を返すメソッド */ $use_vendor_callback = \ebi\Conf::get('use_vendor_callback'); if (!empty($use_vendor_callback)) { $callback_result = call_user_func($use_vendor_callback); if (is_array($callback_result)) { $use_vendor = array_merge($use_vendor, $callback_result); } } if (is_array($use_vendor)) { foreach ($use_vendor as $class) { $find_package = false; if (substr($class, -1) == '*') { $class = substr($class, 0, -1); $find_package = true; } $class = str_replace('.', '\\', $class); if (class_exists($class)) { if ($find_package) { $r = new \ReflectionClass($class); foreach (\ebi\Util::ls(dirname($r->getFileName()), true) as $f) { $valid_find_class_file($f); } } } } } $valid_find_class = function ($r, $parent_class) { if (!$r->isInterface() && (empty($parent_class) || is_subclass_of($r->getName(), $parent_class)) && $r->getFileName() !== false && strpos($r->getName(), '_') === false && strpos($r->getName(), 'Composer') === false && strpos($r->getName(), 'cmdman') === false && strpos($r->getName(), 'testman') === false) { return true; } return false; }; foreach (get_declared_classes() as $class) { if ($valid_find_class($r = new \ReflectionClass($class), $parent_class)) { (yield ['filename' => $r->getFileName(), 'class' => '\\' . $r->getName()]); } } }
/** * @param \ebi\Log $log */ public function log_output(\ebi\Log $log) { $mail = new \ebi\Mail(); /** * @param mixed{} $arg1 メールにバインドする変数 */ $vars = \ebi\Conf::gets('vars'); /** * @param string $arg1 fromのメールアドレス */ $from = \ebi\Conf::get('from'); /** * @param string $arg1 toのメールアドレス */ $to = \ebi\Conf::get('to'); if (!empty($from)) { if (is_string($from)) { $mail->from($from); } else { if (isset($from['address'])) { $mail->from($from['address'], isset($from['name']) ? $from['name'] : null); } } } if (!empty($to)) { if (is_string($to)) { $mail->to($to); } else { if (isset($to['address'])) { $mail->to($to['address'], isset($to['name']) ? $to['name'] : null); } else { if (is_array($to)) { foreach ($to as $t) { if (isset($t['address'])) { $mail->to($t['address'], isset($t['name']) ? $t['name'] : null); } } } } } } if (!is_array($vars)) { $vars = []; } $template = ''; switch ($log->level()) { case 0: $template = 'logs/emergency.xml'; break; case 1: $template = 'logs/alert.xml'; break; case 2: $template = 'logs/critical.xml'; break; case 3: $template = 'logs/error.xml'; break; case 4: $template = 'logs/warning.xml'; break; case 5: $template = 'logs/notice.xml'; break; case 6: $template = 'logs/info.xml'; break; case 7: $template = 'logs/debug.xml'; break; } try { $mail->send_template($template, array_merge($vars, ['log' => $log, 'env' => new \ebi\Env()])); } catch (\ebi\exception\InvalidArgumentException $e) { } }
public function time($format = null) { if (empty($format)) { $format = \ebi\Conf::timestamp_format(); } return date($format, $this->time); }
<?php \ebi\Conf::set([\ebi\Conf::class => ['appmode_group' => ['dev' => ['local', 'mamp']]], \ebi\Log::class => ['level' => 'debug', 'file' => dirname(__DIR__) . '/work/ebi.log'], 'ebi.Flow' => ['app_url' => 'http://localhost:8000/**', 'accept_debug' => true], \ebi\flow\plugin\Cors::class => ['origin' => 'http://localhost:8000'], 'ebi.Dt' => ['test_dir' => dirname(__DIR__) . '/test', 'ignore' => [], 'use_vendor' => [\ebi\SmtpBlackholeDao::class, \ebi\SessionDao::class]], \ebi\Dao::class => ['connection' => ['*' => ['type' => \ebi\SqliteConnector::class, 'timezone' => '+09:00']]]]); \ebi\Conf::set_class_plugin(['ebi.Mail' => [\ebi\SmtpBlackholeDao::class], 'ebi.Session' => [\ebi\SessionDao::class], 'ebi.Log' => ['ebi.LogMailSender'], \test\flow\RequestFlow::class => [\test\plugin\RequestPlugin::class]]);
private static function expand_patterns($pk, $patterns, $extends, &$automap_idx) { $result = []; $ext_arr = ['plugins' => [], 'vars' => []]; foreach ($ext_arr as $k => $v) { if (array_key_exists($k, $extends)) { $ext_arr[$k] = $extends[$k]; unset($extends[$k]); } } foreach ($patterns as $k => $v) { if (is_callable($v)) { $v = ['action' => $v]; } if (!isset($v['mode']) || \ebi\Conf::in_mode($v['mode'])) { if (!empty($extends)) { $v = array_merge($extends, $v); } foreach ($ext_arr as $ek => $ev) { if (!empty($ev)) { $v[$ek] = array_key_exists($ek, $v) ? is_array($v[$ek]) ? $v[$ek] : [$v[$ek]] : []; $v[$ek] = array_merge($ev, $v[$ek]); } } $pt = (empty($pk) ? '' : $pk . '/') . $k; if (array_key_exists('patterns', $v)) { if (!array_key_exists('mode', $v) || \ebi\Conf::in_mode($v['mode'])) { $vp = $v['patterns']; unset($v['patterns']); $result = array_merge($result, self::expand_patterns($pt, $vp, $v, $automap_idx)); } } else { if (!isset($v['name'])) { $v['name'] = $pt; } if (isset($v['action'])) { if (!is_callable($v['action']) && strpos($v['action'], '::') === false) { foreach (self::automap($pt, $v['action'], $v['name'], $automap_idx++) as $ak => $av) { $result[$ak] = array_merge($v, $av); } } else { $result[$pt] = $v; } } else { $result[$pt] = $v; } } } } return $result; }
/** * Template Code * @param string $template_path * @return string */ public static function xtc($template_path) { /** * @param string $xtc_length Template Code length */ $length = \ebi\Conf::get('xtc_length', 5); return strtoupper(substr(sha1(md5(str_repeat($template_path, 5))), 0, $length)); }
public function __construct() { call_user_func_array('parent::__construct', func_get_args()); if (func_num_args() == 1) { foreach (func_get_arg(0) as $n => $v) { switch ($n) { case '_has_hierarchy_': case '_class_id_': case '_hierarchy_': $this->{$n} = $v; break; default: } } } $p = get_class($this); if (!isset($this->_class_id_)) { $this->_class_id_ = $p; } if (isset(self::$_dao_[$this->_class_id_])) { foreach (self::$_dao_[$this->_class_id_]->_has_dao_ as $name => $dao) { $this->{$name}($dao); } return; } $annotation = \ebi\Annotation::get_class($p, ['readonly', 'table']); $anon = [null, isset($annotation['table']['name']) ? $annotation['table']['name'] : null, $annotation['readonly'] !== null]; if (empty(self::$_connection_settings_)) { /** * DBの接続情報 * * `````````````````````````````````````````````````````````` * [ * 'ebi.SessionDao'=>[ // ebi.SessionDaoモデルの接続情報となります * 'type'=>'ebi.MysqlConnector', * 'name'=>'ebitest' * ], * '*'=>[ // *を指定した場合は他のパターンにマッチしたなかったもの全てがこの接続になります * 'type'=>'ebi.MysqlConnector', * 'name'=>'ebitest' * ], * ] * `````````````````````````````````````````````````````````` * * @param string{} $connection 接続情報配列 */ self::$_connection_settings_ = \ebi\Conf::gets('connection'); if (empty(self::$_connection_settings_)) { self::$_connection_settings_ = ['*' => ['host' => getcwd()]]; } } // find connection settings $findns = explode('\\', $p); while (!array_key_exists(implode('.', $findns), self::$_connection_settings_) && !empty($findns)) { array_pop($findns); } if (empty($findns) && !isset(self::$_connection_settings_['*'])) { throw new \ebi\exception\ConnectionException('could not find the connection settings `' . $p . '`'); } $anon[0] = empty($findns) ? '*' : implode('.', $findns); if (empty($anon[1])) { $table_class = $p; $parent_class = get_parent_class($p); $ref = new \ReflectionClass($parent_class); while (true) { $ref = new \ReflectionClass($parent_class); if (__CLASS__ == $parent_class || $ref->isAbstract()) { break; } $table_class = $parent_class; $parent_class = get_parent_class($parent_class); } $table_class = preg_replace("/^.*\\\\(.+)\$/", "\\1", $table_class); $anon[1] = strtolower($table_class[0]); for ($i = 1; $i < strlen($table_class); $i++) { $anon[1] .= ctype_lower($table_class[$i]) ? $table_class[$i] : '_' . strtolower($table_class[$i]); } } $db_settings = self::get_db_settings($anon[0], $p); $prefix = isset($db_settings['prefix']) ? $db_settings['prefix'] : ''; $upper = isset($db_settings['upper']) && $db_settings['upper'] === true; $lower = isset($db_settings['lower']) && $db_settings['lower'] === true; self::$_con_[get_called_class()] = self::$_connections_[$anon[0]]->connector(); $set_table_name = function ($name, $class) use($prefix, $upper, $lower) { $name = $prefix . $name; if ($upper) { $name = strtoupper($name); } else { if ($lower) { $name = strtolower($name); } } return $name; }; self::$_co_anon_[$p] = $anon; self::$_co_anon_[$p][1] = $set_table_name(self::$_co_anon_[$p][1], $p); $has_hierarchy = isset($this->_hierarchy_) ? $this->_hierarchy_ - 1 : $this->_has_hierarchy_; $root_table_alias = 't' . self::$_cnt_++; $_self_columns_ = $_where_columns_ = $_conds_ = $_join_conds_ = $_alias_ = $_has_many_conds_ = $_has_dao_ = []; $prop = $last_cond_column = []; $ref = new \ReflectionClass($this); foreach ($ref->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED) as $prop) { if ($prop->getName()[0] != '_' && $this->prop_anon($prop->getName(), 'extra') !== true) { $props[] = $prop->getName(); } } while (!empty($props)) { $name = array_shift($props); $anon_cond = $this->prop_anon($name, 'cond'); $column_type = $this->prop_anon($name, 'type'); if (empty($column_type)) { if ($name == 'id') { $this->prop_anon($name, 'type', 'serial', true); } else { if ($name == 'created_at' || $name == 'create_date' || $name == 'created') { $this->prop_anon($name, 'type', 'timestamp', true); $this->prop_anon($name, 'auto_now_add', true, true); } else { if ($name == 'updated_at' || $name == 'update_date' || $name == 'modified') { $this->prop_anon($name, 'type', 'timestamp', true); $this->prop_anon($name, 'auto_now', true, true); } else { if ($name == 'code') { $this->prop_anon($name, 'type', 'string', true); $this->prop_anon($name, 'auto_code_add', true, true); } } } } $column_type = $this->prop_anon($name, 'type', 'string'); } if ($this->prop_anon($name, 'type') == 'serial') { $this->prop_anon($name, 'primary', true, true); } $column = new \ebi\Column(); $column->name($name); $column->column($this->prop_anon($name, 'column', $name)); $column->column_alias('c' . self::$_cnt_++); if ($anon_cond === null) { if (ctype_upper($column_type[0]) && class_exists($column_type) && is_subclass_of($column_type, __CLASS__)) { throw new \ebi\exception\InvalidQueryException('undef ' . $name . ' annotation `cond`'); } $column->table($this->table()); $column->table_alias($root_table_alias); $column->primary($this->prop_anon($name, 'primary', false) || $column_type === 'serial'); $column->auto($column_type === 'serial'); $_alias_[$column->column_alias()] = $name; $_self_columns_[$name] = $column; } else { if (false !== strpos($anon_cond, '(')) { $is_has = class_exists($column_type) && is_subclass_of($column_type, __CLASS__); $is_has_many = $is_has && $this->prop_anon($name, 'attr') === 'a'; if ((!$is_has || $has_hierarchy > 0) && preg_match("/^(.+)\\((.*)\\)(.*)\$/", $anon_cond, $match)) { list(, $self_var, $conds_string, $has_var) = $match; $conds = []; $ref_table = $ref_table_alias = null; if (!empty($conds_string)) { foreach (explode(',', $conds_string) as $cond) { $tcc = explode('.', $cond, 3); switch (sizeof($tcc)) { case 1: $conds[] = \ebi\Column::cond_instance($tcc[0], 'c' . self::$_cnt_++, $this->table(), $root_table_alias); break; case 2: list($t, $c1) = $tcc; $ref_table = $set_table_name($t, $p); $ref_table_alias = 't' . self::$_cnt_++; $conds[] = \ebi\Column::cond_instance($c1, 'c' . self::$_cnt_++, $ref_table, $ref_table_alias); break; case 3: list($t, $c1, $c2) = $tcc; $ref_table = $set_table_name($t, $p); $ref_table_alias = 't' . self::$_cnt_++; $conds[] = \ebi\Column::cond_instance($c1, 'c' . self::$_cnt_++, $ref_table, $ref_table_alias); $conds[] = \ebi\Column::cond_instance($c2, 'c' . self::$_cnt_++, $ref_table, $ref_table_alias); break; default: throw new \ebi\exception\InvalidAnnotationException('annotation error : `' . $name . '`'); } } } if ($is_has_many) { if (empty($has_var)) { throw new \ebi\exception\InvalidAnnotationException('annotation error : `' . $name . '`'); } $dao = new $column_type(['_class_id_' => $p . '___' . self::$_cnt_++]); $_has_many_conds_[$name] = [$dao, $has_var, $self_var]; } else { if ($is_has) { if (empty($has_var)) { throw new \ebi\exception\InvalidAnnotationException('annotation error : `' . $name . '`'); } $dao = new $column_type(['_class_id_' => $p . '___' . self::$_cnt_++, '_hierarchy_' => $has_hierarchy]); $this->{$name}($dao); $_has_many_conds_[$name] = [$dao, $has_var, $self_var]; } else { if ($self_var[0] == '@') { $cond_var = null; $cond_name = substr($self_var, 1); if (strpos($cond_name, '.') !== false) { list($cond_name, $cond_var) = explode('.', $cond_name); } if (!isset($last_cond_column[$cond_name]) && in_array($cond_name, $props)) { $props[] = $name; continue; } $cond_column = clone $last_cond_column[$cond_name]; if (isset($cond_var)) { $cond_column->column($cond_var); $cond_column->column_alias('c' . self::$_cnt_++); } array_unshift($conds, $cond_column); } else { array_unshift($conds, \ebi\Column::cond_instance($self_var, 'c' . self::$_cnt_++, $this->table(), $root_table_alias)); } $column->table($ref_table); $column->table_alias($ref_table_alias); $_alias_[$column->column_alias()] = $name; if (sizeof($conds) % 2 != 0) { throw new \ebi\exception\InvalidQueryException($name . '[' . $column_type . '] is illegal condition'); } if ($this->prop_anon($name, 'join', false)) { $this->prop_anon($name, 'get', false, true); $this->prop_anon($name, 'set', false, true); for ($i = 0; $i < sizeof($conds); $i += 2) { $_join_conds_[$name][] = [$conds[$i], $conds[$i + 1]]; } } else { for ($i = 0; $i < sizeof($conds); $i += 2) { $_conds_[] = [$conds[$i], $conds[$i + 1]]; } } $_where_columns_[$name] = $column; } } if (!empty($conds)) { $cond_column = clone $conds[sizeof($conds) - 1]; $cond_column->column($column->column()); $cond_column->column_alias('c' . self::$_cnt_++); $last_cond_column[$name] = $cond_column; } } } else { if ($anon_cond[0] === '@') { $cond_name = substr($anon_cond, 1); if (in_array($cond_name, $props)) { $props[] = $name; continue; } if (isset($_self_columns_[$cond_name])) { $column->table($_self_columns_[$cond_name]->table()); $column->table_alias($_self_columns_[$cond_name]->table_alias()); } else { if (isset($_where_columns_[$cond_name])) { $column->table($_where_columns_[$cond_name]->table()); $column->table_alias($_where_columns_[$cond_name]->table_alias()); } else { throw new \ebi\exception\InvalidQueryException('undef var `' . $name . '`'); } } $_alias_[$column->column_alias()] = $name; $_where_columns_[$name] = $column; } } } } self::$_dao_[$this->_class_id_] = (object) ['_self_columns_' => $_self_columns_, '_where_columns_' => $_where_columns_, '_conds_' => $_conds_, '_join_conds_' => $_join_conds_, '_alias_' => $_alias_, '_has_dao_' => $_has_dao_, '_has_many_conds_' => $_has_many_conds_]; }
/** * クラスのプラグインを取得 * @param string $n * @return array */ protected static function get_class_plugin_funcs($n) { $rtn = []; $g = get_called_class(); foreach (\ebi\Conf::get_class_plugin($g) as $o) { static::set_class_plugin($o); } if (isset(self::$_plug_funcs[$g])) { foreach (self::$_plug_funcs[$g] as $o) { if (is_array($o)) { if ($n == $o[1]) { $rtn[] = $o[0]; } } else { if (method_exists($o, $n)) { $rtn[] = [$o, $n]; } } } } return $rtn; }
private function request($method, $url, $download_path = null) { if (!isset($this->resource)) { $this->resource = curl_init(); } $url_info = parse_url($url); $cookie_base_domain = (isset($url_info['host']) ? $url_info['host'] : '') . (isset($url_info['path']) ? $url_info['path'] : ''); switch ($method) { case 'RAW': case 'POST': curl_setopt($this->resource, CURLOPT_POST, true); break; case 'GET': if (isset($url_info['query'])) { parse_str($url_info['query'], $vars); foreach ($vars as $k => $v) { if (!isset($this->request_vars[$k])) { $this->request_vars[$k] = $v; } } list($url) = explode('?', $url, 2); } curl_setopt($this->resource, CURLOPT_HTTPGET, true); break; case 'HEAD': curl_setopt($this->resource, CURLOPT_NOBODY, true); break; case 'PUT': curl_setopt($this->resource, CURLOPT_PUT, true); break; case 'DELETE': curl_setopt($this->resource, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; } switch ($method) { case 'POST': if (!empty($this->request_file_vars)) { $vars = []; if (!empty($this->request_vars)) { foreach (explode('&', http_build_query($this->request_vars)) as $q) { $s = explode('=', $q, 2); $vars[urldecode($s[0])] = isset($s[1]) ? urldecode($s[1]) : null; } } foreach (explode('&', http_build_query($this->request_file_vars)) as $q) { $s = explode('=', $q, 2); if (isset($s[1])) { if (!is_file($f = urldecode($s[1]))) { throw new \ebi\exception\InvalidArgumentException($f . ' not found'); } $vars[urldecode($s[0])] = class_exists('\\CURLFile', false) ? new \CURLFile($f) : '@' . $f; } } curl_setopt($this->resource, CURLOPT_POSTFIELDS, $vars); } else { curl_setopt($this->resource, CURLOPT_POSTFIELDS, http_build_query($this->request_vars)); } break; case 'RAW': if (!isset($this->request_header['Content-Type'])) { $this->request_header['Content-Type'] = 'text/plain'; } curl_setopt($this->resource, CURLOPT_POSTFIELDS, $this->raw); break; case 'GET': case 'HEAD': case 'PUT': case 'DELETE': $url = $url . (!empty($this->request_vars) ? '?' . http_build_query($this->request_vars) : ''); } curl_setopt($this->resource, CURLOPT_URL, $url); curl_setopt($this->resource, CURLOPT_FOLLOWLOCATION, false); curl_setopt($this->resource, CURLOPT_HEADER, false); curl_setopt($this->resource, CURLOPT_RETURNTRANSFER, false); curl_setopt($this->resource, CURLOPT_FORBID_REUSE, true); curl_setopt($this->resource, CURLOPT_FAILONERROR, false); curl_setopt($this->resource, CURLOPT_TIMEOUT, $this->timeout); if (self::$recording_request) { curl_setopt($this->resource, CURLINFO_HEADER_OUT, true); } /** * @param boolean $ssl_verify SSL証明書を確認するかの真偽値 */ if (\ebi\Conf::get('ssl-verify', true) === false) { curl_setopt($this->resource, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($this->resource, CURLOPT_SSL_VERIFYPEER, false); } if (!empty($this->user)) { curl_setopt($this->resource, CURLOPT_USERPWD, $this->user . ':' . $this->password); } if (!isset($this->request_header['Expect'])) { $this->request_header['Expect'] = null; } if (!isset($this->request_header['Cookie'])) { $cookies = ''; foreach ($this->cookie as $domain => $cookie_value) { if (strpos($cookie_base_domain, $domain) === 0 || strpos($cookie_base_domain, $domain[0] == '.' ? $domain : '.' . $domain) !== false) { foreach ($cookie_value as $k => $v) { if (!$v['secure'] || $v['secure'] && substr($url, 0, 8) == 'https://') { $cookies .= sprintf('%s=%s; ', $k, $v['value']); } } } } curl_setopt($this->resource, CURLOPT_COOKIE, $cookies); } if (!isset($this->request_header['User-Agent'])) { curl_setopt($this->resource, CURLOPT_USERAGENT, empty($this->agent) ? isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null : $this->agent); } curl_setopt($this->resource, CURLOPT_HTTPHEADER, array_map(function ($k, $v) { return $k . ': ' . $v; }, array_keys($this->request_header), $this->request_header)); curl_setopt($this->resource, CURLOPT_HEADERFUNCTION, [$this, 'callback_head']); if (empty($download_path)) { curl_setopt($this->resource, CURLOPT_WRITEFUNCTION, [$this, 'callback_body']); } else { if (strpos($download_path, '://') === false && !is_dir(dirname($download_path))) { mkdir(dirname($download_path), 0777, true); } $fp = fopen($download_path, 'wb'); curl_setopt($this->resource, CURLOPT_WRITEFUNCTION, function ($resource, $data) use(&$fp) { if ($fp) { fwrite($fp, $data); } return strlen($data); }); } $this->request_header = $this->request_vars = []; $this->head = $this->body = $this->raw = ''; curl_exec($this->resource); if (!empty($download_path) && $fp) { fclose($fp); } if (($err_code = curl_errno($this->resource)) > 0) { if ($err_code == 47 || $err_code == 52) { return $this; } throw new \ebi\exception\ConnectionException($err_code . ': ' . curl_error($this->resource)); } $this->url = curl_getinfo($this->resource, CURLINFO_EFFECTIVE_URL); $this->status = curl_getinfo($this->resource, CURLINFO_HTTP_CODE); if (self::$recording_request) { self::$record_request[] = curl_getinfo($this->resource, CURLINFO_HEADER_OUT); } if (preg_match_all('/Set-Cookie:[\\s]*(.+)/i', $this->head, $match)) { foreach ($match[1] as $cookies) { $cookie_name = $cookie_value = $cookie_domain = $cookie_path = $cookie_expires = null; $cookie_domain = $cookie_base_domain; $cookie_path = '/'; $secure = false; foreach (explode(';', $cookies) as $cookie) { $cookie = trim($cookie); if (strpos($cookie, '=') !== false) { list($k, $v) = explode('=', $cookie, 2); $k = trim($k); $v = trim($v); switch (strtolower($k)) { case 'expires': $cookie_expires = ctype_digit($v) ? (int) $v : strtotime($v); break; case 'domain': $cookie_domain = preg_replace('/^[\\w]+:\\/\\/(.+)$/', '\\1', $v); break; case 'path': $cookie_path = $v; break; default: if (!isset($cookie_name)) { $cookie_name = $k; $cookie_value = $v; } } } else { if (strtolower($cookie) == 'secure') { $secure = true; } } } $cookie_domain = substr(\ebi\Util::path_absolute('http://' . $cookie_domain, $cookie_path), 7); if ($cookie_expires !== null && $cookie_expires < time()) { if (isset($this->cookie[$cookie_domain][$cookie_name])) { unset($this->cookie[$cookie_domain][$cookie_name]); } } else { $this->cookie[$cookie_domain][$cookie_name] = ['value' => $cookie_value, 'expires' => $cookie_expires, 'secure' => $secure]; } } } curl_close($this->resource); unset($this->resource); if ($this->redirect_count++ < $this->redirect_max) { switch ($this->status) { case 300: case 301: case 302: case 303: case 307: if (preg_match('/Location:[\\040](.*)/i', $this->head, $redirect_url)) { return $this->request('GET', trim(\ebi\Util::path_absolute($url, $redirect_url[1])), $download_path); } } } $this->redirect_count = 1; return $this; }
/** * 現在のアプリケーションモードがモードに所属しているか * @param string $mode アプリケーションモード * @return boolean */ public static function in_mode($mode) { /** * ````````````````````````` * [ * グループ名 => [モード,モード] * ] * ````````````````````````` * * @param string{} $group アプリケーションモードのグループ */ $group = self::get_self_conf_get('appmode_group', []); $chkmode = is_array($mode) ? $mode : (strpos($mode, ',') === false ? [$mode] : explode(',', $mode)); foreach ($chkmode as $m) { if (substr($m, 0, 1) == '@') { $mode = substr($mode, 1); if (array_key_exists($mode, $group) && in_array(\ebi\Conf::appmode(), $group[$mode])) { return true; } } else { if ($m == self::appmode()) { return true; } } } return false; }
public static function mail_template_list() { $path = \ebi\Conf::get(\ebi\Mail::class . '@resource_path', \ebi\Conf::resource_path('mail')); $template_list = []; try { foreach (\ebi\Util::ls($path, true, '/\\.xml$/') as $f) { $info = new \ebi\Dt\DocInfo(); $info->name(str_replace(\ebi\Util::path_slash($path, null, true), '', $f->getPathname())); try { $xml = \ebi\Xml::extract(file_get_contents($f->getPathname()), 'mail'); $info->document($xml->find_get('subject')->value()); $info->set_opt('x_t_code', \ebi\Mail::xtc($info->name())); $template_list[] = $info; } catch (\ebi\exception\NotFoundException $e) { } } } catch (\ebi\exception\InvalidArgumentException $e) { } return $template_list; }
<?php \test\db\DateTime::create_table(); \test\db\DateTime::find_delete(); $time = time(); $obj = new \test\db\DateTime(); $obj->ts(date('Y/m/d H:i:s', $time)); $obj->date(date('Y/m/d H:i:s', $time)); $obj->idate(date('Y/m/d H:i:s', $time)); $obj->save(); foreach (\test\db\DateTime::find() as $o) { eq(date('c', $time), $o->fm_ts()); eq(date('Y-m-d', $time), $o->fm_date()); eq(date('Ymd', $time), $o->idate()); } $db = \ebi\Dao::connection(\test\db\DateTime::class); $db->query('select ts,date,idate from date_time'); foreach ($db as $data) { $t = new \DateTime(date('Y/m/d H:i:s', $time)); $t->setTimezone(new \DateTimeZone('UTC')); if (\ebi\Conf::appmode() == 'mamp') { eq(date('Y-m-d H:i:s', $time), $data['ts']); // mysqlの接続設定でtimezoneをJSTで取得している } else { eq($t->format('Y-m-d H:i:s'), $data['ts']); } eq(date('Y-m-d', $time), $data['date']); eq(date('Ymd', $time), $data['idate']); }
/** * クッキーへの書き出し * @param string $name 書き込む変数名 * @param int $expire 有効期限(秒) (+ time) */ public function write_cookie($name, $expire = null) { $cookie_params = \ebi\Conf::cookie_params(); if ($expire === null) { $expire = $cookie_params['cookie_lifetime']; if ($expire > 0) { $expire = $expire + time(); } } setcookie($name, $this->in_vars($name), time() + $expire, $cookie_params['cookie_path'], $cookie_params['cookie_domain'], $cookie_params['cookie_secure']); }
/** * フォーマットした日付を返す * @param integer $value 時間 * @param string $format フォーマット文字列 ( http://jp2.php.net/manual/ja/function.date.php ) * @return string */ public function date_format($format = null, $value = null) { if (empty($format)) { $format = \ebi\Conf::timestamp_format(); } if (empty($value)) { $value = time(); } return date($format, $value); }
<?php \ebi\Conf::set(['ebi.Dao' => ['connection' => [\ebi\SessionDao::class => ['type' => \ebi\MysqlConnector::class, 'name' => 'ebitest'], '*' => ['type' => \ebi\MysqlConnector::class, 'name' => 'ebitest', 'timezone' => '+09:00'], \test\db\ReplicationSlave::class => ['type' => \ebi\MysqlUnbufferedConnector::class, 'name' => 'ebitest'], '\\test\\db\\Unbuffered' => ['type' => \ebi\MysqlUnbufferedConnector::class, 'name' => 'ebitest']]]]); include_once __DIR__ . '/local.php';