/** * Loads encryption configuration and validates the data. * * @param array|string custom configuration or config group name * @throws LemonRuntimeException */ public function __construct($config = FALSE) { if (!defined('MCRYPT_ENCRYPT')) { throw new LemonRuntimeException('encrypt.requires_mcrypt', 500); } if (is_string($config)) { $name = $config; // Test the config group name if (($config = Lemon::config('encryption.' . $config)) === NULL) { throw new LemonRuntimeException('encrypt.undefined_group ' . $name, 500); } } if (is_array($config)) { // Append the default configuration options $config += Lemon::config('encryption.default'); } else { // Load the default group $config = Lemon::config('encryption.default'); } if (empty($config['key'])) { throw new LemonRuntimeException('encrypt.no_encryption_key', 500); } // Find the max length of the key, based on cipher and mode $size = mcrypt_get_key_size($config['cipher'], $config['mode']); if (strlen($config['key']) > $size) { // Shorten the key to the maximum size $config['key'] = substr($config['key'], 0, $size); } // Find the initialization vector size $config['iv_size'] = mcrypt_get_iv_size($config['cipher'], $config['mode']); // Cache the config in the object $this->config = $config; }
public function setup() { $settings = $this->routeInstance->getSetup(); //TODO 调用对应的驱动配置 require_once Lemon::find_file('vendor', 'MixFS', TRUE); $this->instance = MixFS::factory($settings['fsBasePath'], $this->routeInstance->getRouteKey(), $settings['fsDomain']); $this->isAvailable = $this->instance->connect() === FALSE ? FALSE : TRUE; }
public function setup() { $settings = $this->routeInstance->getSetup(); //TODO 调用对应的驱动配置 require_once Lemon::find_file('vendor', 'phprpc/phprpc_client', TRUE); $this->instance = new PHPRPC_Client($settings['phprpcHost']); $this->isAvailable = $this->instance ? TRUE : FALSE; }
public function write($id, $data) { $data = empty($this->encrypt) ? base64_encode($data) : $this->encrypt->encode($data); if (strlen($data) > 4048) { throw new LemonRuntimeException('Session (' . $id . ') data exceeds the 4KB limit, ignoring write.', 500); return FALSE; } return cookie::set($this->cookie_name, $data, Lemon::config('session.expiration')); }
/** * Handles methods that do not exist. * * @param string method name * @param array arguments * @return void */ public function __call($method, $args) { // get(Db/Mem/Tt/Fs)Instance($routeStamp) if (substr($method, 0, 3) == 'get' && substr($method, -8) == 'Instance') { $baseDriverKey = substr($method, 3, strlen($method) - 11); if ($this->configObject->isExistsDriverKey($baseDriverKey) == FALSE) { throw new ServRouteInstanceException(_('Instance.driver_not_supported:') . $baseDriverKey, 500); } // 路由驱动 $routeDriver = 'ServRoute_' . $baseDriverKey . '_Driver'; // 实例驱动 $instanceDriver = 'ServInstance_' . $baseDriverKey . '_Driver'; if (!Lemon::auto_load($routeDriver)) { throw new ServRouteInstanceException(_('Instance.route_driver_not_found:') . $baseDriverKey, 500); } if (!Lemon::auto_load($instanceDriver)) { throw new ServRouteInstanceException(_('Instance.instance_driver_not_found:') . $baseDriverKey, 500); } // 实例池 $driverInstancePoolName = $baseDriverKey; if (!array_key_exists($driverInstancePoolName, $this->instancePools)) { $this->instancePools[$driverInstancePoolName] = array(); } // fast but unflexible $thisRouteClassInstance = new $routeDriver($this->configObject->getDriverSetup($baseDriverKey), $args); // slow but flexible //$rc = new ReflectionClass($routeDriver);$thisRouteClassInstance = $rc->newInstanceArgs($args); if (!$thisRouteClassInstance instanceof ServRoute_Driver || !is_subclass_of($thisRouteClassInstance, 'ServRoute_Driver')) { throw new ServRouteInstanceException(_('Instance.route_driver_implements:') . $driverKey, 500); } // 路由key $routeKey = $thisRouteClassInstance->getRouteKey(); // 初始化Pool中的routeKey !isset($this->instancePools[$driverInstancePoolName][$routeKey]) && ($this->instancePools[$driverInstancePoolName][$routeKey] = false); if ($this->instancePools[$driverInstancePoolName][$routeKey] !== FALSE && $this->instancePools[$driverInstancePoolName][$routeKey]->isAvailable() == TRUE) { // 池中有对应的实例并且可用 return $this->instancePools[$driverInstancePoolName][$routeKey]; } // 设定池中的实例 $thisInstanceClassInstance = new $instanceDriver($thisRouteClassInstance); if (!$thisInstanceClassInstance instanceof ServInstance_Driver || !is_subclass_of($thisInstanceClassInstance, 'ServInstance_Driver')) { throw new ServRouteInstanceException(_('Instance.instance_driver_implements:') . $driverKey, 500); } $this->instancePools[$driverInstancePoolName][$routeKey] = $thisInstanceClassInstance; if ($this->instancePools[$driverInstancePoolName][$routeKey] !== FALSE) { $this->instancePools[$driverInstancePoolName][$routeKey]->isAvailable() or $this->instancePools[$driverInstancePoolName][$routeKey]->setup(); if ($this->instancePools[$driverInstancePoolName][$routeKey]->isAvailable() != TRUE) { throw new ServRouteInstanceException(_('Instance.getInstance Failed,Service Not Available.'), 500); } // 池中有对应的实例并且可用 return $this->instancePools[$driverInstancePoolName][$routeKey]; } throw new ServRouteInstanceException(_('Instance.getInstance Failed,critical error'), 500); } else { throw new ServRouteInstanceException(_('Unknown Method'), 500); } }
/** * Loads URI, and Input into this controller. * * @return void */ public function __construct() { if (Lemon::$instance == NULL) { // Set the instance to the first controller loaded Lemon::$instance = $this; } // URI should always be available $this->uri = URI::instance(); // Input should always be available $this->input = Input::instance(); }
/** * Fetches an absolute site URL based on a URI segment. * * @param string site URI to convert * @param string non-default protocol * @return string */ public static function site($uri = '', $protocol = FALSE) { if ($path = trim(parse_url($uri, PHP_URL_PATH), '/')) { // Add path suffix $path .= Lemon::config('core.url_suffix'); } if ($query = parse_url($uri, PHP_URL_QUERY)) { // ?query=string $query = '?' . $query; } if ($fragment = parse_url($uri, PHP_URL_FRAGMENT)) { // #fragment $fragment = '#' . $fragment; } // Concat the URL return url::base(TRUE, $protocol) . $path . $query . $fragment; }
/** * Sets a cookie with the given parameters. * * @param string cookie name or array of config options * @param string cookie value * @param integer number of seconds before the cookie expires * @param string URL path to allow * @param string URL domain to allow * @param boolean HTTPS only * @param boolean HTTP only (requires PHP 5.2 or higher) * @return boolean */ public static function set($name, $value = NULL, $expire = NULL, $path = NULL, $domain = NULL, $secure = NULL, $httponly = NULL) { if (headers_sent()) { return FALSE; } // If the name param is an array, we import it is_array($name) and extract($name, EXTR_OVERWRITE); // Fetch default options $config = Lemon::config('cookie'); foreach (array('value', 'expire', 'domain', 'path', 'secure', 'httponly') as $item) { if (${$item} === NULL and isset($config[$item])) { ${$item} = $config[$item]; } } // Expiration timestamp $expire = $expire == 0 ? 0 : time() + (int) $expire; return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly); }
/** * Sets the view filename. * * @chainable * @param string view filename * @param string view file type * @return object */ public function set_filename($name, $type = NULL) { if ($type == NULL) { // Load the filename and set the content type $this->lemon_filename = Lemon::find_file('view', $name, TRUE); $this->lemon_filetype = '.php'; } else { // Check if the filetype is allowed by the configuration if (!in_array($type, Lemon::config('view.allowed_filetypes'))) { throw new LemonRuntimeException('core.invalid_filetype ' . $type, 500); } // Load the filename and set the content type $this->lemon_filename = Lemon::find_file('view', $name, TRUE, $type); $this->lemon_filetype = Lemon::config('mimes.' . $type); if ($this->lemon_filetype == NULL) { // Use the specified type $this->lemon_filetype = $type; } } return $this; }
/** * Loads the configured driver and validates it. * * @param array|string custom configuration or config group name * @return void */ public function __construct($config = FALSE) { if (is_string($config)) { $name = $config; // Test the config group name if (($config = Lemon::config('cache.' . $config)) === NULL) { throw new LemonRuntimeException('cache.undefined_group ' . $name, 500); } } if (is_array($config)) { // Append the default configuration options $config += Lemon::config('cache.default'); } else { // Load the default group $config = Lemon::config('cache.default'); } // Cache the config in the object $this->config = $config; // Set driver name $driver = 'Cache_' . ucfirst($this->config['driver']) . '_Driver'; // Load the driver if (!Lemon::auto_load($driver)) { throw new LemonRuntimeException('core.driver_not_found ' . $this->config['driver'], 500); } // Initialize the driver $this->driver = new $driver($this->config['params']); // Validate the driver if (!$this->driver instanceof Cache_Driver) { throw new LemonRuntimeException('core.driver_implements ' . $this->config['driver'], 500); } if (Cache::$loaded !== TRUE) { $this->config['requests'] = (int) $this->config['requests']; if ($this->config['requests'] > 0 and mt_rand(1, $this->config['requests']) === 1) { // Do garbage collection $this->driver->delete_expired(); } // Cache has been loaded once Cache::$loaded = TRUE; } }
public function setup() { $settings = $this->routeInstance->getSetup(); //TODO 调用对应的驱动配置 require_once Lemon::find_file('vendor', 'ez_sql/shared/ez_sql_core', TRUE); require_once Lemon::find_file('vendor', 'ez_sql/mysql/ez_sql_mysql', TRUE); $curInst = new ezSQL_mysql($settings['dbUser'], $settings['dbPasswd'], $settings['dbSchema'], $settings['dbHost']); $curInst->cache_timeout = $settings['dbCacheTimeout']; $curInst->cache_dir = $settings['dbDiskCachePath']; $curInst->use_disk_cache = $settings['dbCache'] == 1; $curInst->cache_queries = $settings['dbCache'] == 1; if ($settings['dbShowError'] == 1) { $curInst->show_errors(); } else { $curInst->hide_errors(); } $curInst->set_charset('utf8'); //$curInst->quick_connect($settings['dbUser'], $settings['dbPasswd'], $settings['dbSchema'], $settings['dbHost']); $this->instance = $curInst; //$this->isAvailable = $this->instance->dbh?TRUE:FALSE; $this->isAvailable = TRUE; }
public function __construct() { if (!extension_loaded('memcache')) { throw new LemonRuntimeException('cache.extension_not_loaded', 500); } $this->backend = new Memcache(); $this->flags = Lemon::config('cache_memcache.compression') ? MEMCACHE_COMPRESSED : FALSE; $servers = Lemon::config('cache_memcache.servers'); foreach ($servers as $server) { // Make sure all required keys are set $server += array('host' => '127.0.0.1', 'port' => 11211, 'persistent' => FALSE); // Add the server to the pool $this->backend->addServer($server['host'], $server['port'], (bool) $server['persistent']); } // Load tags self::$tags = $this->backend->get(self::TAGS_KEY); if (!is_array(self::$tags)) { // Create a new tags array self::$tags = array(); // Tags have been created self::$tags_changed = TRUE; } }
/** * 读取解析配置对象(array) * @param array $configObject */ public function loadConfig($configObject = NULL) { if ($configObject == NULL) { $configPath = Lemon::config('instance.configPath'); empty($configPath) && ($configPath = PROJECT_ROOT . 'etc/web/instance.ini'); if (!is_file($configPath)) { throw new ServRouteConfigException(_('defaultConfigureObject Not Found'), 404); } $thisConfigObject = parse_ini_file($configPath, TRUE); } else { $thisConfigObject = $configObject; } $drivers = array(); $cfgKeys = !is_null($thisConfigObject) ? array_keys($thisConfigObject) : NULL; if (!empty($cfgKeys)) { foreach ($cfgKeys as $cfgKey) { if (substr($cfgKey, 0, 8) == 'Instance') { $drivers[substr($cfgKey, 8)] = $thisConfigObject[$cfgKey]; } } } $this->configObject = $thisConfigObject; $this->drivers = $drivers; }
/** * 函数说明: 截取文件Mime类型 * * @author 樊振兴(nick)<*****@*****.**> * @history 2006-08-25 樊振兴 添加了本方法 * @param string field 文件域名称 * @param int index 如果是多文件则获取指定索引的文件的Mime类型 * @return string /bool(false) */ public static function getFileType($field, $index = 0) { if (isset($_FILES[$field]) && !empty($_FILES[$field]['type'])) { if (!is_array($_FILES[$field]['type'])) { if (!isset(page::$mimemap) || empty(page::$mimemap)) { page::$mimemap = Lemon::config('mimemap.type2postfix'); } if (array_key_exists($_FILES[$field]['type'], page::$mime_map)) { return page::$mimemap[$_FILES[$field]['type']]; } else { return false; } } else { if (!isset(page::$mimemap) || empty(page::$mimemap)) { page::$mimemap = Lemon::config('mimemap.type2postfix'); } if (array_key_exists($_FILES[$field]['type'][$index], page::$mimemap)) { return page::$mimemap[$_FILES[$field]['type'][$index]]; } else { return false; } } } else { return false; } }
/** * Parse a single token * @param string token */ function parseonetoken($token) { $x = $token; $this->a = 0; // for referencing in WAITING_FOR_DECL_KEYWORD if (DEBUG) { printf("%s:%d: Token=[%s] state=%d\n", $this->filename, $this->tokenlineno, $token, $this->state); } switch ($this->state) { case self::INITIALIZE: $this->prevrule = 0; $this->preccounter = 0; $this->firstrule = $this->lastrule = 0; $this->gp->nrule = 0; /* Fall thru to next case */ /* Fall thru to next case */ case self::WAITING_FOR_DECL_OR_RULE: if ($x[0] == '%') { $this->state = self::WAITING_FOR_DECL_KEYWORD; } elseif (preg_match('/[a-z]/', $x[0])) { $this->lhs = LemonSymbol::Symbol_new($x); $this->nrhs = 0; $this->lhsalias = 0; $this->state = self::WAITING_FOR_ARROW; } elseif ($x[0] == '{') { if ($this->prevrule === 0) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "There is no prior rule opon which to attach the code\n fragment which begins on this line."); $this->errorcnt++; } elseif ($this->prevrule->code != 0) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Code fragment beginning on this line is not the first \\\n to follow the previous rule."); $this->errorcnt++; } else { $this->prevrule->line = $this->tokenlineno; $this->prevrule->code = substr($x, 1); } } elseif ($x[0] == '[') { $this->state = self::PRECEDENCE_MARK_1; } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Token \"%s\" should be either \"%%\" or a nonterminal name.", $x); $this->errorcnt++; } break; case self::PRECEDENCE_MARK_1: if (!preg_match('/[A-Z]/', $x[0])) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "The precedence symbol must be a terminal."); $this->errorcnt++; } elseif ($this->prevrule === 0) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "There is no prior rule to assign precedence \"[%s]\".", $x); $this->errorcnt++; } elseif ($this->prevrule->precsym != 0) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Precedence mark on this line is not the first to follow the previous rule."); $this->errorcnt++; } else { $this->prevrule->precsym = LemonSymbol::Symbol_new($x); } $this->state = self::PRECEDENCE_MARK_2; break; case self::PRECEDENCE_MARK_2: if ($x[0] != ']') { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Missing \"]\" on precedence mark."); $this->errorcnt++; } $this->state = self::WAITING_FOR_DECL_OR_RULE; break; case self::WAITING_FOR_ARROW: if ($x[0] == ':' && $x[1] == ':' && $x[2] == '=') { $this->state = self::IN_RHS; } elseif ($x[0] == '(') { $this->state = self::LHS_ALIAS_1; } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Expected to see a \":\" following the LHS symbol \"%s\".", $this->lhs->name); $this->errorcnt++; $this->state = self::RESYNC_AFTER_RULE_ERROR; } break; case self::LHS_ALIAS_1: if (preg_match('/[A-Za-z]/', $x[0])) { $this->lhsalias = $x; $this->state = self::LHS_ALIAS_2; } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "\"%s\" is not a valid alias for the LHS \"%s\"\n", $x, $this->lhs->name); $this->errorcnt++; $this->state = self::RESYNC_AFTER_RULE_ERROR; } break; case self::LHS_ALIAS_2: if ($x[0] == ')') { $this->state = self::LHS_ALIAS_3; } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Missing \")\" following LHS alias name \"%s\".", $this->lhsalias); $this->errorcnt++; $this->state = self::RESYNC_AFTER_RULE_ERROR; } break; case self::LHS_ALIAS_3: if ($x == '::=') { $this->state = self::IN_RHS; } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Missing \"->\" following: \"%s(%s)\".", $this->lhs->name, $this->lhsalias); $this->errorcnt++; $this->state = self::RESYNC_AFTER_RULE_ERROR; } break; case self::IN_RHS: if ($x[0] == '.') { $rp = new LemonRule(); $rp->ruleline = $this->tokenlineno; for ($i = 0; $i < $this->nrhs; $i++) { $rp->rhs[$i] = $this->rhs[$i]; $rp->rhsalias[$i] = $this->alias[$i]; } $rp->lhs = $this->lhs; $rp->lhsalias = $this->lhsalias; $rp->nrhs = $this->nrhs; $rp->code = 0; $rp->precsym = 0; $rp->index = $this->gp->nrule++; $rp->nextlhs = $rp->lhs->rule; $rp->lhs->rule = $rp; $rp->next = 0; if ($this->firstrule === 0) { $this->firstrule = $this->lastrule = $rp; } else { $this->lastrule->next = $rp; $this->lastrule = $rp; } $this->prevrule = $rp; $this->state = self::WAITING_FOR_DECL_OR_RULE; } elseif (preg_match('/[a-zA-Z]/', $x[0])) { if ($this->nrhs >= Lemon::MAXRHS) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Too many symbols on RHS or rule beginning at \"%s\".", $x); $this->errorcnt++; $this->state = self::RESYNC_AFTER_RULE_ERROR; } else { if (isset($this->rhs[$this->nrhs - 1])) { $msp = $this->rhs[$this->nrhs - 1]; if ($msp->type == LemonSymbol::MULTITERMINAL) { $inf = array_reduce($msp->subsym, array($this, '_printmulti'), ''); Lemon::ErrorMsg($this->filename, $this->tokenlineno, 'WARNING: symbol ' . $x . ' will not' . ' be part of previous multiterminal %s', substr($inf, 0, strlen($inf) - 1)); } } $this->rhs[$this->nrhs] = LemonSymbol::Symbol_new($x); $this->alias[$this->nrhs] = 0; $this->nrhs++; } } elseif (($x[0] == '|' || $x[0] == '/') && $this->nrhs > 0) { $msp = $this->rhs[$this->nrhs - 1]; if ($msp->type != LemonSymbol::MULTITERMINAL) { $origsp = $msp; $msp = new LemonSymbol(); $msp->type = LemonSymbol::MULTITERMINAL; $msp->nsubsym = 1; $msp->subsym = array($origsp); $msp->name = $origsp->name; $this->rhs[$this->nrhs - 1] = $msp; } $msp->nsubsym++; $msp->subsym[$msp->nsubsym - 1] = LemonSymbol::Symbol_new(substr($x, 1)); if (preg_match('/[a-z]/', $x[1]) || preg_match('/[a-z]/', $msp->subsym[0]->name[0])) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Cannot form a compound containing a non-terminal"); $this->errorcnt++; } } elseif ($x[0] == '(' && $this->nrhs > 0) { $this->state = self::RHS_ALIAS_1; } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Illegal character on RHS of rule: \"%s\".", $x); $this->errorcnt++; $this->state = self::RESYNC_AFTER_RULE_ERROR; } break; case self::RHS_ALIAS_1: if (preg_match('/[A-Za-z]/', $x[0])) { $this->alias[$this->nrhs - 1] = $x; $this->state = self::RHS_ALIAS_2; } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n", $x, $this->rhs[$this->nrhs - 1]->name); $this->errorcnt++; $this->state = self::RESYNC_AFTER_RULE_ERROR; } break; case self::RHS_ALIAS_2: if ($x[0] == ')') { $this->state = self::IN_RHS; } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Missing \")\" following LHS alias name \"%s\".", $this->lhsalias); $this->errorcnt++; $this->state = self::RESYNC_AFTER_RULE_ERROR; } break; case self::WAITING_FOR_DECL_KEYWORD: if (preg_match('/[A-Za-z]/', $x[0])) { $this->declkeyword = $x; $this->declargslot =& $this->a; $this->decllnslot =& $this->a; $this->state = self::WAITING_FOR_DECL_ARG; if ('name' == $x) { $this->declargslot =& $this->gp->name; } elseif ('include' == $x) { $this->declargslot =& $this->gp->include_code; $this->decllnslot =& $this->gp->includeln; } elseif ('include_class' == $x) { $this->declargslot =& $this->gp->include_classcode; $this->decllnslot =& $this->gp->include_classln; } elseif ('declare_class' == $x) { $this->declargslot =& $this->gp->declare_classcode; $this->decllnslot =& $this->gp->declare_classln; } elseif ('code' == $x) { $this->declargslot =& $this->gp->extracode; $this->decllnslot =& $this->gp->extracodeln; } elseif ('token_destructor' == $x) { $this->declargslot =& $this->gp->tokendest; $this->decllnslot =& $this->gp->tokendestln; } elseif ('default_destructor' == $x) { $this->declargslot =& $this->gp->vardest; $this->decllnslot =& $this->gp->vardestln; } elseif ('token_prefix' == $x) { $this->declargslot =& $this->gp->tokenprefix; } elseif ('syntax_error' == $x) { $this->declargslot =& $this->gp->error; $this->decllnslot =& $this->gp->errorln; } elseif ('parse_accept' == $x) { $this->declargslot =& $this->gp->accept; $this->decllnslot =& $this->gp->acceptln; } elseif ('parse_failure' == $x) { $this->declargslot =& $this->gp->failure; $this->decllnslot =& $this->gp->failureln; } elseif ('stack_overflow' == $x) { $this->declargslot =& $this->gp->overflow; $this->decllnslot =& $this->gp->overflowln; } else { if ('extra_argument' == $x) { $this->declargslot =& $this->gp->arg; } elseif ('token_type' == $x) { $this->declargslot =& $this->gp->tokentype; } elseif ('default_type' == $x) { $this->declargslot =& $this->gp->vartype; } elseif ('stack_size' == $x) { $this->declargslot =& $this->gp->stacksize; } elseif ('start_symbol' == $x) { $this->declargslot =& $this->gp->start; } elseif ('left' == $x) { $this->preccounter++; $this->declassoc = LemonSymbol::LEFT; $this->state = self::WAITING_FOR_PRECEDENCE_SYMBOL; } elseif ('right' == $x) { $this->preccounter++; $this->declassoc = LemonSymbol::RIGHT; $this->state = self::WAITING_FOR_PRECEDENCE_SYMBOL; } elseif ('nonassoc' == $x) { $this->preccounter++; $this->declassoc = LemonSymbol::NONE; $this->state = self::WAITING_FOR_PRECEDENCE_SYMBOL; } elseif ('destructor' == $x) { $this->state = self::WAITING_FOR_DESTRUCTOR_SYMBOL; } elseif ('type' == $x) { $this->state = self::WAITING_FOR_DATATYPE_SYMBOL; } elseif ('fallback' == $x) { $this->fallback = 0; $this->state = self::WAITING_FOR_FALLBACK_ID; } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Unknown declaration keyword: \"%%%s\".", $x); $this->errorcnt++; $this->state = self::RESYNC_AFTER_DECL_ERROR; } } } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Illegal declaration keyword: \"%s\".", $x); $this->errorcnt++; $this->state = self::RESYNC_AFTER_DECL_ERROR; } break; case self::WAITING_FOR_DESTRUCTOR_SYMBOL: if (!preg_match('/[A-Za-z]/', $x[0])) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Symbol name missing after %destructor keyword"); $this->errorcnt++; $this->state = self::RESYNC_AFTER_DECL_ERROR; } else { $sp = LemonSymbol::Symbol_new($x); $this->declargslot =& $sp->destructor; $this->decllnslot =& $sp->destructorln; $this->state = self::WAITING_FOR_DECL_ARG; } break; case self::WAITING_FOR_DATATYPE_SYMBOL: if (!preg_match('/[A-Za-z]/', $x[0])) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Symbol name missing after %destructor keyword"); $this->errorcnt++; $this->state = self::RESYNC_AFTER_DECL_ERROR; } else { $sp = LemonSymbol::Symbol_new($x); $this->declargslot =& $sp->datatype; $this->state = self::WAITING_FOR_DECL_ARG; } break; case self::WAITING_FOR_PRECEDENCE_SYMBOL: if ($x[0] == '.') { $this->state = self::WAITING_FOR_DECL_OR_RULE; } elseif (preg_match('/[A-Z]/', $x[0])) { $sp = LemonSymbol::Symbol_new($x); if ($sp->prec >= 0) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Symbol \"%s\" has already been given a precedence.", $x); $this->errorcnt++; } else { $sp->prec = $this->preccounter; $sp->assoc = $this->declassoc; } } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Can't assign a precedence to \"%s\".", $x); $this->errorcnt++; } break; case self::WAITING_FOR_DECL_ARG: if (preg_match('/[A-Za-z0-9{"]/', $x[0])) { if ($this->declargslot != 0) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "The argument \"%s\" to declaration \"%%%s\" is not the first.", $x[0] == '"' ? substr($x, 1) : $x, $this->declkeyword); $this->errorcnt++; $this->state = self::RESYNC_AFTER_DECL_ERROR; } else { $this->declargslot = $x[0] == '"' || $x[0] == '{' ? substr($x, 1) : $x; $this->a = 1; if (!$this->decllnslot) { $this->decllnslot = $this->tokenlineno; } $this->state = self::WAITING_FOR_DECL_OR_RULE; } } else { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "Illegal argument to %%%s: %s", $this->declkeyword, $x); $this->errorcnt++; $this->state = self::RESYNC_AFTER_DECL_ERROR; } break; case self::WAITING_FOR_FALLBACK_ID: if ($x[0] == '.') { $this->state = self::WAITING_FOR_DECL_OR_RULE; } elseif (!preg_match('/[A-Z]/', $x[0])) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "%%fallback argument \"%s\" should be a token", $x); $this->errorcnt++; } else { $sp = LemonSymbol::Symbol_new($x); if ($this->fallback === 0) { $this->fallback = $sp; } elseif (is_object($sp->fallback)) { Lemon::ErrorMsg($this->filename, $this->tokenlineno, "More than one fallback assigned to token %s", $x); $this->errorcnt++; } else { $sp->fallback = $this->fallback; $this->gp->has_fallback = 1; } } break; case self::RESYNC_AFTER_RULE_ERROR: /* if ($x[0] == '.') $this->state = self::WAITING_FOR_DECL_OR_RULE; ** break; */ /* if ($x[0] == '.') $this->state = self::WAITING_FOR_DECL_OR_RULE; ** break; */ case self::RESYNC_AFTER_DECL_ERROR: if ($x[0] == '.') { $this->state = self::WAITING_FOR_DECL_OR_RULE; } if ($x[0] == '%') { $this->state = self::WAITING_FOR_DECL_KEYWORD; } break; } }
/** * Generates routed URI from given URI. * * @param string URI to convert * @return string Routed uri */ public static function routed_uri($uri) { if (Router::$routes === NULL) { // Load routes Router::$routes = Lemon::config('routes'); } // Prepare variables $routed_uri = $uri = trim($uri, '/'); if (isset(Router::$routes[$uri])) { // Literal match, no need for regex $routed_uri = Router::$routes[$uri]; } else { // Loop through the routes and see if anything matches foreach (Router::$routes as $key => $val) { if ($key === '_default') { continue; } // Trim slashes $key = trim($key, '/'); $val = trim($val, '/'); if (preg_match('#^' . $key . '$#u', $uri)) { if (strpos($val, '$') !== FALSE) { // Use regex routing $routed_uri = preg_replace('#^' . $key . '$#u', $val, $uri); } else { // Standard routing $routed_uri = $val; } // A valid route has been found break; } } } if (isset(Router::$routes[$routed_uri])) { // Check for double routing (without regex) $routed_uri = Router::$routes[$routed_uri]; } return trim($routed_uri, '/'); }
/** * Returns quality factor at which the client accepts content type. * * @param string content type (e.g. "image/jpg", "jpg") * @param boolean set to TRUE to disable wildcard checking * @return integer|float */ public static function accepts_at_quality($type = NULL, $explicit_check = FALSE) { request::parse_accept_header(); // Normalize type $type = strtolower((string) $type); // General content type (e.g. "jpg") if (strpos($type, '/') === FALSE) { // Don't accept anything by default $q = 0; // Look up relevant mime types foreach ((array) Lemon::config('mimes.' . $type) as $type) { $q2 = request::accepts_at_quality($type, $explicit_check); $q = $q2 > $q ? $q2 : $q; } return $q; } // Content type with subtype given (e.g. "image/jpg") $type = explode('/', $type, 2); // Exact match if (isset(request::$accept_types[$type[0]][$type[1]])) { return request::$accept_types[$type[0]][$type[1]]; } // Wildcard match (if not checking explicitly) if ($explicit_check === FALSE and isset(request::$accept_types[$type[0]]['*'])) { return request::$accept_types[$type[0]]['*']; } // Catch-all wildcard match (if not checking explicitly) if ($explicit_check === FALSE and isset(request::$accept_types['*']['*'])) { return request::$accept_types['*']['*']; } // Content type not accepted return 0; }
public function delete($fileKey, $meta, $sign) { if ($this->verifySign($fileKey, $meta, $sign) == FALSE) { throw new MyRuntimeException(_('sign verify failed')); } $metaStruct = array(); !empty($meta) && ($metaStruct = json_decode($meta, TRUE)); $objectName = array_key_exists('objectName', $metaStruct) ? $metaStruct['objectName'] : 'StoreData'; $routeSet = array_key_exists('id', $metaStruct) ? array('id' => $metaStruct['id']) : array(); // 请求的存储类型 $storeType = isset($metaStruct['storeType']) ? $metaStruct['storeType'] : Lemon::config('store.apiDefaultType'); $storeType == self::STORE_TYPE_PHPRPC && ($storeType = Lemon::config('store.apiDefaultType')); // 请求的存储数据长度 $storeLength = isset($metaStruct['storeLength']) ? $metaStruct['storeLength'] : 0; $refArray = isset($metaStruct['refArray']) ? $metaStruct['refArray'] : array(); // 应用对象类型 $refType = !empty($refArray) && isset($refArray[0]['refPart']) ? $refArray[0]['refPart'] : 'default'; // 应用对象id $refId = !empty($refArray) && isset($refArray[0]['refId']) ? $refArray[0]['refId'] : 0; switch ($storeType) { case self::STORE_TYPE_FS: // 调用路由实例 $servRouteInstance = $this->getServRouteInstance(); //TODO 根据$metaStruct去调用不同的存储逻辑实例 $fsInstCurrent = $servRouteInstance->getFsInstance($objectName, $routeSet)->getInstance(); $fsInstCurrent->delete($fileKey); break; case self::STORE_TYPE_TT: // 调用路由实例 $servRouteInstance = $this->getServRouteInstance(); //TODO 根据fileMeta去调用不同的存储逻辑实例 $ttInstCurrent = $servRouteInstance->getTtInstance($objectName, $routeSet)->getInstance(); $ttInstCurrent->delete($fileKey); break; case self::STORE_TYPE_MEM: // 调用路由实例 $servRouteInstance = $this->getServRouteInstance(); //TODO 根据fileMeta去调用不同的存储逻辑实例 $memInstCurrent = $servRouteInstance->getMemInstance($objectName, $routeSet)->getInstance(); $memInstCurrent->delete($fileKey); break; default: throw new MyRuntimeException(_('unsupported store type'), 500); break; } }
Header("Location: http://www.zr4u.com"); exit; ?> <div id="doc3"> <div id="hd"> <h1 class="ui-widget-content ui-corner-all"><a href="http://www.zr4u.com" title="<?php echo Lemon::config('site.name'); ?> "><img src="http://res.zr4u.com/res/img/logo.jpg" alt="<?php echo Lemon::config('site.name'); ?> " /></a></h1> </div> <div id="bd"> <ul class="navBar ui-widget-content ui-corner-all"><li>» <a href="/" title="<?php echo Lemon::config('site.name'); ?> ">首页</a></li></ul> <div id="respTips" class="ui-corner-all"><?php isset($returnStruct['msg']) && (print $returnStruct['msg']); ?> </div> <p> </p> <p><a href="http://www.zr4u.com" title="www.zr4u.com">www.zr4u.com</a></p> <p> </p> </div> <div id="ft"> <p>-</p> </div> </div>
public function info() { $returnStruct = array('status' => 0, 'code' => 501, 'msg' => _('Not Implemented'), 'content' => array()); try { //* 初始化返回数据 */ $returnStatus = 1; $returnCode = 200; $returnMessage = ''; $returnData = array(); //* 收集请求数据 ==根据业务逻辑定制== */ $requestData = $this->input->get(); //* 实现功能后屏蔽此异常抛出 */ throw new MyRuntimeException(_('Not Implemented'), 501); //* 权限验证,数据验证,逻辑验证 ==根据业务逻辑定制== */ if (util::isAccess('*', array(Logon::$USER_ROLE_LABEL_DENIED, Logon::$USER_ROLE_LABEL_GUEST), $this->getUserRoleLabel()) == FALSE) { throw new MyRuntimeException(_('Access Denied'), 403); } //* 权限验证 ==根据业务逻辑定制== */ //* 数据验证 ==根据业务逻辑定制== */ //* 逻辑验证 ==根据业务逻辑定制== */ // 调用底层服务 // 执行业务逻辑 //* 补充&修改返回结构体 */ $returnStruct['status'] = $returnStatus; $returnStruct['code'] = $returnCode; $returnStruct['msg'] = $returnMessage; $returnStruct['content'] = $returnData; //* 请求类型 */ if ($this->isAjaxRequest()) { // ajax 请求 // json 输出 $this->template->content = $returnStruct; } else { // html 输出 //* 模板输出 */ $this->template->returnStruct = $returnStruct; $content = new View('info'); //* 变量绑定 */ $this->template->title = Lemon::config('site.name'); $this->template->content = $content; //* 请求结构数据绑定 */ $this->template->content->requestData = $requestData; //* 返回结构体绑定 */ $this->template->content->returnStruct = $returnStruct; //:: 当前应用专用数据 $this->template->content->title = Lemon::config('site.name'); } // end of request type determine } catch (MyRuntimeException $ex) { $returnStruct['status'] = 0; $returnStruct['code'] = $ex->getCode(); $returnStruct['msg'] = $ex->getMessage(); //TODO 异常处理 //throw $ex; if ($this->isAjaxRequest()) { $this->template->content = $returnStruct; } else { $this->template->returnStruct = $returnStruct; $content = new View('info'); $this->template->content = $content; //* 请求结构数据绑定 */ $this->template->content->requestData = $requestData; //* 返回结构体绑定 */ $this->template->content->returnStruct = $returnStruct; } } }
*/ $renderStruct = array('status' => 0, 'code' => 501, 'msg' => '', 'action' => array('url' => request::referrer('about:blank'), 'time' => 3, 'type' => 'back', 'frame' => 'self', 'script' => '')); isset($returnStruct['status']) && ($renderStruct['status'] = $returnStruct['status']); isset($returnStruct['code']) && ($renderStruct['code'] = $returnStruct['code']); isset($returnStruct['msg']) && ($renderStruct['msg'] = $returnStruct['msg']); if (isset($returnStruct['action'])) { isset($returnStruct['action']['url']) && ($renderStruct['action']['url'] = $returnStruct['action']['url']); //empty($renderStruct['action']['url']) && $renderStruct['action']['url'] = request::referrer('about:blank'); isset($returnStruct['action']['time']) && ($renderStruct['action']['time'] = $returnStruct['action']['time']); isset($returnStruct['action']['type']) && ($renderStruct['action']['type'] = $returnStruct['action']['type']); isset($returnStruct['action']['frame']) && ($renderStruct['action']['frame'] = $returnStruct['action']['frame']); isset($returnStruct['action']['script']) && ($renderStruct['action']['script'] = $returnStruct['action']['script']); } $renderStruct['action']['target'] = in_array($renderStruct['action']['frame'], array('blank', 'top', 'self', 'parent')) ? "_" . $renderStruct['action']['frame'] : $renderStruct['action']['frame']; //exit("<div id=\"do_debug\" style=\"clear:both;display:;\"><pre>\n".var_export($renderStruct,TRUE)."\n</pre></div>"); $actionLinkText = Lemon::config('common.proceedLinkText'); $actionLinkContext = ''; $actionActionContext = ''; if ($renderStruct['action']['type'] == 'header') { header("Location:" . $renderStruct['action']['url']); exit; } //elseif(in_array($renderStruct['action']['type'],array('location','close'))) switch ($renderStruct['action']['type']) { case 'location': case 'close': if ($renderStruct['action']['frame'] != 'self') { if ($renderStruct['action']['type'] == 'location') { $actionContextCurrent = $renderStruct['action']['script'] . ' ' . 'top.window[\'' . $renderStruct['action']['frame'] . '\'].location.href=\'' . $renderStruct['action']['url'] . '\';'; } elseif ($renderStruct['action']['type'] == 'close') { $actionContextCurrent = $renderStruct['action']['script'] . ' ' . 'top.window[\'' . $renderStruct['action']['frame'] . '\'].close();';
/** * 存储文件内容 * @param $fileData * @param $appMeta */ public function storeFileData($fileData, $appMeta = NULL) { //TODO 根据appMeta路由本地资源申请的地址 //先申请id $requestData = array('storeType' => 0); $storeId = $this->add($requestData); if (empty($storeId)) { throw new MyRuntimeException(_('request resource Id failed'), 500); } //TODO 加入appMeta的指定逻辑的解析工作 $fileMeta = $appMeta; if (!empty($fileMeta) && is_array($fileMeta)) { $storeType = isset($fileMeta['storeType']) ? $fileMeta['storeType'] : Lemon::config('store.defaultType'); $fileMeta['storeType'] = $storeType; $storeLength = isset($fileMeta['storeLength']) ? $fileMeta['storeLength'] : strlen($fileData); $fileMeta['storeLength'] = $storeLength; } else { $storeType = Lemon::config('store.defaultType'); $storeLength = strlen($fileData); $fileMeta = array('storeType' => $storeType, 'storeLength' => $storeLength); } $fileMeta['id'] = $storeId; $fileMeta['objectName'] = $this->objectName . 'Data'; //预备下一步存储流程结束后的更新数据 $requestData = array('id' => $storeId, 'storeType' => $storeType, 'storeLength' => $storeLength, 'storeMeta' => !empty($fileMeta) ? json_encode($fileMeta) : ''); //FIXME 目前只支持本地FS存储故此处暂时使用嵌入的方式解决,后面应该写成驱动形式。 switch ($storeType) { case self::STORE_TYPE_FS: $fileKey = md5(uniqid(rand(), true)); $requestData['getUri'] = $fileKey; $requestData['setUri'] = $fileKey; // 调用路由实例 $servRouteInstance = $this->getServRouteInstance(); //TODO 根据fileMeta去调用不同的存储逻辑实例 $fsInstCurrent = $servRouteInstance->getFsInstance($this->objectName . 'Data', array('id' => $requestData['id']))->getInstance(); $saveOk = $fsInstCurrent->putFileData($requestData['setUri'], $fileData); if ($saveOk == FALSE) { throw new MyRuntimeException(_('store failed'), 500); } break; case self::STORE_TYPE_TT: $fileKey = md5(uniqid(rand(), true)); $requestData['getUri'] = $fileKey; $requestData['setUri'] = $fileKey; // 调用路由实例 $servRouteInstance = $this->getServRouteInstance(); //TODO 根据fileMeta去调用不同的存储逻辑实例 $ttInstCurrent = $servRouteInstance->getTtInstance($this->objectName . 'Data', array('id' => $requestData['id']))->getInstance(); $ttInstCurrent->put($requestData['setUri'], $fileData); // $saveOk = $ttInstCurrent->put($requestData['setUri'],$fileData); // if($saveOk==FALSE){ // throw new MyRuntimeException(_('store failed'),500); // } break; case self::STORE_TYPE_MEM: $fileKey = md5(uniqid(rand(), true)); $requestData['getUri'] = $fileKey; $requestData['setUri'] = $fileKey; // 调用路由实例 $servRouteInstance = $this->getServRouteInstance(); //TODO 根据fileMeta去调用不同的存储逻辑实例 $memInstCurrent = $servRouteInstance->getMemInstance($this->objectName . 'Data', array('id' => $requestData['id']))->getInstance(); $memInstCurrent->set($requestData['setUri'], $fileData); // $saveOk = $ttInstCurrent->put($requestData['setUri'],$fileData); // if($saveOk==FALSE){ // throw new MyRuntimeException(_('store failed'),500); // } break; case self::STORE_TYPE_PHPRPC: $fileKey = md5(uniqid(rand(), true)); $requestData['getUri'] = $fileKey; $requestData['setUri'] = $fileKey; // 调用路由实例 $servRouteInstance = $this->getServRouteInstance(); //TODO 根据fileMeta去调用不同的存储逻辑实例 $phprpcInstCurrent = $servRouteInstance->getPhprpcInstance($this->objectName . 'Data', array('id' => $requestData['id']))->getInstance(); $fileMeta['storeType'] = Lemon::config('store.apiDefaultType'); $storeMeta = !empty($fileMeta) ? json_encode($fileMeta) : ''; $sign = md5($requestData['setUri'] . $storeMeta . $this->getPhprpcApiKey()); $phprpcInstCurrent->set($requestData['setUri'], $fileData, $storeMeta, $sign); break; case self::STORE_TYPE_ENTITY: default: throw new MyRuntimeException(_('store type not supportted right now.'), 500); $requestData['getUri'] = $storeId; $requestData['setUri'] = $storeId; $requestData['storeContent'] = $fileData; break; } $this->set($requestData['id'], $requestData); return $storeId; }
private function getApiKey() { if ($this->apiKey === NULL) { $this->apiKey = Lemon::config('phprpc.local.' . $this->objectName . '.apiKey'); } return $this->apiKey; }
public function sandbox() { $returnStruct = array('status' => 0, 'code' => 501, 'msg' => _('Not Implemented'), 'content' => array()); try { //* 初始化返回数据 */ $returnStatus = 1; $returnCode = 200; $returnMessage = ''; $returnData = array(); //* 收集请求数据 ==根据业务逻辑定制== */ $getData = $this->input->get(); $postData = $this->input->post(); empty($getData) && ($getData = array()); empty($postData) && ($postData = array()); $requestData = array_merge($getData, $postData); //* 实现功能后屏蔽此异常抛出 */ //throw new MyRuntimeException(_('Not Implemented'),501); //* 权限验证,数据验证,逻辑验证 ==根据业务逻辑定制== */ // if(util::isAccess(array(Logon::$MGR_ROLE_LABEL_SYS_ADMIN,), array(Logon::$MGR_ROLE_LABEL_DENIED,Logon::$MGR_ROLE_LABEL_GUEST), $this->getMgrRole())==FALSE){ // throw new MyRuntimeException(_('Access Denied'),403); // } //* 权限验证 ==根据业务逻辑定制== */ //* 数据验证 ==根据业务逻辑定制== */ //* 逻辑验证 ==根据业务逻辑定制== */ // 调用底层服务 // 执行业务逻辑 !isset($servRouteInstance) && ($servRouteInstance = ServRouteInstance::getInstance(ServRouteConfig::getInstance())); //$seqService = Seq_Service::getInstance($servRouteInstance); //$tempId = $seqService->currentSeq('Temp'); //print("<div id=\"do_debug\" style=\"clear:both;display:;\"><pre>\n".var_export($tempId,TRUE)."\n</pre></div>"); //exit; // $myTemp = Temp_Service::getInstance($servRouteInstance); //// $myt1 = Temp_Service::factory($servRouteInstance); //// $myt2 = Temp_Service::factory($servRouteInstance); // $reqObj = array('name'=>'abc'.util::reRandStr(3),'val'=>'123abc'); // $retId = $myTemp->add($reqObj); // print("<div id=\"do_debug\" style=\"clear:both;display:;\"><pre>\n".var_export($retId,TRUE)."\n</pre></div>"); // // $retObj = $myTemp->get($retId); // print("<div id=\"do_debug\" style=\"clear:both;display:;\"><pre>\n".var_export($retObj,TRUE)."\n</pre></div>"); // exit; // $tobj1 = $myTemp->get(1); // $tobj2 = $myt1->get(2); // $tobj3 = $myt2->get(1); // print("<div id=\"do_debug\" style=\"clear:both;display:;\"><pre>\n".var_export($tobj1,TRUE)."\n</pre></div>"); // print("<div id=\"do_debug\" style=\"clear:both;display:;\"><pre>\n".var_export($tobj2,TRUE)."\n</pre></div>"); // print("<div id=\"do_debug\" style=\"clear:both;display:;\"><pre>\n".var_export($tobj3,TRUE)."\n</pre></div>"); // exit; // /* == thrift 调用样例 Start == */ // // thrift 相关调用 // require_once $GLOBALS['THRIFT_ROOT'].'/Thrift.php'; // require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php'; // require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php'; // require_once $GLOBALS['THRIFT_ROOT'].'/transport/THttpClient.php'; // require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php'; // // thrift 应用接口相关调用接口类定义库 // $GEN_DIR = $GLOBALS['THRIFT_ROOT'].'/packages/zr4u'; // require_once $GEN_DIR.'/MyappInterface.php'; // require_once $GEN_DIR.'/zr4u_constants.php'; // require_once $GEN_DIR.'/zr4u_types.php'; // try { // // thrift 服务调用 // $socket = new TSocket(Lemon::config('thrift.default.Host'), Lemon::config('thrift.default.Port')); // $transport = new TBufferedTransport($socket, 1024, 1024); // $protocol = new TBinaryProtocol($transport); // $client = new ExpoInterfaceClient($protocol); // $transport->open(); // //接口业务逻辑 // $serviceVersion = $client->getVER(); // // //通讯关闭 // $transport->close(); // } catch (TException $ex) { // //print 'TException: '.$tx->getMessage()."\n"; // throw new MyRuntimeException(_('Server Communication Error'),500); // } // $returnData['serviceVersion']=$serviceVersion; // // /* == thrift 调用样例 End == */ // /* == FS 调用样例 Start == */ // // 调用路由实例 // $servRouteInstance = ServRouteInstance::getInstance(ServRouteConfig::getInstance()); // // // 当前应用模块 // $currentModuleName = 'attach'; // // 收集数据特征 // $testUserId = intval(date('YWHi',strtotime('2010-04-06 11:11:00'))); // $crts = time(); // //获取对应服务的路由实例 // $fsInst_attach = $servRouteInstance->getFsInstance($currentModuleName,array('userId'=>$testUserId,'crts'=>$crts))->getInstance(); // // // 调用对应服务的对应调用方法使用服务 // $fileKey = 'myfile_'.date('YmdHi',strtotime('2010-04-06 11:11:00')); // $putFileContent = md5(uniqid(rand(), true)); // // $saveOk = $fsInst_attach->putFileData($fileKey,$putFileContent); // $getFileContent = $fsInst_attach->getFileData($fileKey); // // $returnData['fileKey'] = $fileKey; // $returnData['saveOK'] = $saveOk?'Yes':'No'; // $returnData['putContent'] = $putFileContent; // $returnData['getContent'] = $getFileContent; // $returnData['match'] = $getFileContent==$putFileContent?'Yes':'No'; // // /* == FS 调用样例 End == */ // /* == Db 调用样例 Start == */ // // 调用路由实例 // !isset($servRouteInstance) && $servRouteInstance = ServRouteInstance::getInstance(ServRouteConfig::getInstance()); // //获取对应服务的路由实例 // !isset($dbInst_default) && $dbInst_default = $servRouteInstance->getDbInstance()->getInstance(); // $results = $dbInst_default->get_results("SHOW COLUMNS FROM Manager", OBJECT); // $returnData['dbresult'] = $results; // /* == Db 调用样例 End == */ $returnMessage = 'Test Ok'; //* 补充&修改返回结构体 */ $returnStruct['status'] = $returnStatus; $returnStruct['code'] = $returnCode; $returnStruct['msg'] = $returnMessage; $returnStruct['content'] = $returnData; //* 请求类型 */ if ($this->isAjaxRequest()) { // ajax 请求 // json 输出 $this->template->content = $returnStruct; } else { // html 输出 //* 模板输出 */ $this->template->returnStruct = $returnStruct; $content = new View($this->packageName . '/' . $this->className . '/' . __FUNCTION__); //* 变量绑定 */ $this->template->title = Lemon::config('site.name'); $this->template->content = $content; //* 请求结构数据绑定 */ $this->template->content->requestData = $requestData; //* 返回结构体绑定 */ $this->template->content->returnStruct = $returnStruct; //:: 当前应用专用数据 $this->template->content->title = Lemon::config('site.name'); } // end of request type determine } catch (MyRuntimeException $ex) { $returnStruct['status'] = 0; $returnStruct['code'] = $ex->getCode(); $returnStruct['msg'] = $ex->getMessage(); //TODO 异常处理 //throw $ex; if ($this->isAjaxRequest()) { $this->template->content = $returnStruct; } else { $this->template->returnStruct = $returnStruct; $content = new View('info'); $this->template->content = $content; //* 请求结构数据绑定 */ $this->template->content->requestData = $requestData; //* 返回结构体绑定 */ $this->template->content->returnStruct = $returnStruct; } } }
/** * Validates a credit card number using the Luhn (mod10) formula. * @see http://en.wikipedia.org/wiki/Luhn_algorithm * * @param integer credit card number * @param string|array card type, or an array of card types * @return boolean */ public static function credit_card($number, $type = NULL) { // Remove all non-digit characters from the number if (($number = preg_replace('/\\D+/', '', $number)) === '') { return FALSE; } if ($type == NULL) { // Use the default type $type = 'default'; } elseif (is_array($type)) { foreach ($type as $t) { // Test each type for validity if (valid::credit_card($number, $t)) { return TRUE; } } return FALSE; } $cards = Lemon::config('credit_cards'); // Check card type $type = strtolower($type); if (!isset($cards[$type])) { return FALSE; } // Check card number length $length = strlen($number); // Validate the card length by the card type if (!in_array($length, preg_split('/\\D+/', $cards[$type]['length']))) { return FALSE; } // Check card number prefix if (!preg_match('/^' . $cards[$type]['prefix'] . '/', $number)) { return FALSE; } // No Luhn check required if ($cards[$type]['luhn'] == FALSE) { return TRUE; } // Checksum of the card number $checksum = 0; for ($i = $length - 1; $i >= 0; $i -= 2) { // Add up every 2nd digit, starting from the right $checksum += $number[$i]; } for ($i = $length - 2; $i >= 0; $i -= 2) { // Add up every 2nd digit doubled, starting from the right $double = $number[$i] * 2; // Subtract 9 from the double where value is greater than 10 $checksum += $double >= 10 ? $double - 9 : $double; } // If the checksum is a multiple of 10, the number is valid return $checksum % 10 === 0; }
/** * 删除数据 action */ public function delete() { $returnStruct = array('status' => 0, 'code' => 501, 'msg' => _('Not Implemented'), 'content' => array()); try { // 是否调用本地服务 $useLocalService = TRUE; //$useLocalService = FALSE; //* 初始化返回数据 */ $returnStatus = 1; $returnCode = 200; $returnMessage = ''; $returnData = array(); //* 收集请求数据 ==根据业务逻辑定制== */ $requestData = $this->input->get(); //* 实现功能后屏蔽此异常抛出 */ //throw new MyRuntimeException(_('Not Implemented'),501); //* 权限验证,数据验证,逻辑验证 ==根据业务逻辑定制== */ //if(util::isAccess(array(Logon::$MGR_ROLE_LABEL_SYS_ADMIN,), array(Logon::$USER_ROLE_LABEL_DENIED,Logon::$USER_ROLE_LABEL_GUEST), $this->getUserRoleLabel())==FALSE){ // throw new MyRuntimeException(_('Access Denied'),403); //} if (util::isAccess('*', array(Logon::$USER_ROLE_LABEL_DENIED), $this->getUserRoleLabel()) == FALSE) { throw new MyRuntimeException(_('Access Denied'), 403); } //* 权限验证 ==根据业务逻辑定制== */ //* 数据验证 ==根据业务逻辑定制== */ if (!isset($requestData['id']) || empty($requestData['id']) || !is_numeric($requestData['id'])) { throw new MyRuntimeException(_('Bad Request,id required'), 400); } //* 逻辑验证 ==根据业务逻辑定制== */ // 调用底层服务 !isset($servRouteInstance) && ($servRouteInstance = ServRouteInstance::getInstance(ServRouteConfig::getInstance())); // 执行业务逻辑 // TODO 根据数据特征定制对应的服务实例 if ($useLocalService == TRUE) { !isset($attachmentService) && ($attachmentService = Attachment_Service::getInstance($servRouteInstance)); } else { require_once Lemon::find_file('vendor', 'phprpc/phprpc_client', TRUE); !isset($attachmentService) && ($attachmentService = new PHPRPC_Client(Lemon::config('phprpc.remote.Attachment.host'))); !isset($phprpcApiKey) && ($phprpcApiKey = Lemon::config('phprpc.remote.Attachment.apiKey')); } try { if ($useLocalService == TRUE) { $attachmentService->removeAttachmentDataByAttachmentId($requestData['id']); } else { $args = array($requestData['id']); $sign = md5(json_encode($args) . $phprpcApiKey); $attachmentService->phprpc_removeAttachmentDataByAttachmentId($requestData['id'], $sign); } } catch (MyRuntimeException $ex) { //* ==根据业务逻辑定制== */ //FIXME 根据service层的异常做一些对应处理并抛出用户友好的异常Message throw $ex; } $returnMessage = _('Sucess'); //* 补充&修改返回结构体 */ $returnStruct['status'] = $returnStatus; $returnStruct['code'] = $returnCode; $returnStruct['msg'] = $returnMessage; $returnStruct['content'] = $returnData; //* 请求类型 */ if ($this->isAjaxRequest()) { // ajax 请求 // json 输出 $this->template->content = $returnStruct; } else { // html 输出 //* 模板输出 */ $this->template->returnStruct = $returnStruct; $content = new View('info'); //* 变量绑定 */ $this->template->title = Lemon::config('site.name'); $this->template->content = $content; //* 请求结构数据绑定 */ $this->template->content->requestData = $requestData; //* 返回结构体绑定 */ $this->template->content->returnStruct = $returnStruct; //:: 当前应用专用数据 $this->template->content->title = Lemon::config('site.name'); } // end of request type determine } catch (MyRuntimeException $ex) { $returnStruct['status'] = 0; $returnStruct['code'] = $ex->getCode(); $returnStruct['msg'] = $ex->getMessage(); //TODO 异常处理 //throw $ex; if ($this->isAjaxRequest()) { $this->template->content = $returnStruct; } else { $this->template->returnStruct = $returnStruct; $content = new View('info'); $this->template->content = $content; //* 请求结构数据绑定 */ $this->template->content->requestData = $requestData; //* 返回结构体绑定 */ $this->template->content->returnStruct = $returnStruct; } } }
public static function _minifiyRender($output) { $headers = array(); $heads = headers_list(); if (is_array($heads)) { foreach ($heads as $ahead) { list($head_name, $head_value) = explode(":", $ahead); if ($head_name) { $headers[strtolower($head_name)] = trim($head_value); } } } if (array_key_exists('content-type', $headers)) { $contentTypeStr = $headers['content-type']; $contentTypeArr = explode(';', $contentTypeStr); $contentType = $contentTypeArr[0]; $contentType = strtolower(trim($contentType)); switch ($contentType) { case 'text/html': require_once Lemon::find_file('vendor', 'htmlmin', TRUE); require_once Lemon::find_file('vendor', 'cssmin', TRUE); require_once Lemon::find_file('vendor', 'jsmin', TRUE); $options = array('cssMinifier' => array('cssmin', 'minify'), 'jsMinifier' => array('JSMin', 'minify')); $output = Minify_HTML::minify($output, $options); break; } } return $output; }
* LEMON_IS_WIN = TRUE : FALSE * PCRE_UNICODE_PROPERTIES = TRUE : FALSE * SERVER_UTF8 = TRUE : FALSE */ require RUNTIME_PATH . 'core/Detect.php'; } /* 引入utf8库 */ require RUNTIME_PATH . 'core/utf8.php'; /* 执行清理 */ require RUNTIME_PATH . 'core/Cleanup.php'; /* 引入事件系统 */ require RUNTIME_PATH . 'core/Event.php'; /* 引入Lemon */ require RUNTIME_PATH . 'core/Lemon.php'; // Prepare the environment Lemon::setup(); !defined('APP_INIT') && is_file(APP_PATH . 'core/Init.php') && (include APP_PATH . 'core/Init.php'); !defined('APP_INIT') && define('APP_INIT', 1); // End runtime_loading DEBUG == 1 && Benchmark::stop(SYSTEM_BENCHMARK . '_runtime_loading'); if (RUNTIME_UI == 'WEB') { // Start system_initialization DEBUG == 1 && Benchmark::start(SYSTEM_BENCHMARK . '_system_initialization'); // Prepare the system Event::run('system.ready'); // Determine routing Event::run('system.routing'); // End system_initialization DEBUG == 1 && Benchmark::stop(SYSTEM_BENCHMARK . '_system_initialization'); // Make the magic happen! Event::run('system.execute');
/** * rpc服务 */ public function attachment() { $returnStruct = array('status' => 0, 'code' => 501, 'msg' => _('Not Implemented'), 'content' => array()); try { //* 初始化返回数据 */ $returnStatus = 1; $returnCode = 200; $returnMessage = ''; $returnData = array(); //* 收集请求数据 ==根据业务逻辑定制== */ $requestData = $this->input->get(); //* 实现功能后屏蔽此异常抛出 */ //throw new MyRuntimeException(_('Not Implemented'),501); //* 权限验证,数据验证,逻辑验证 ==根据业务逻辑定制== */ //if(util::isAccess(array(Logon::$MGR_ROLE_LABEL_SYS_ADMIN,), array(Logon::$USER_ROLE_LABEL_DENIED,Logon::$USER_ROLE_LABEL_GUEST), $this->getUserRoleLabel())==FALSE){ // throw new MyRuntimeException(_('Access Denied'),403); //} if (util::isAccess('*', array(Logon::$USER_ROLE_LABEL_DENIED), $this->getUserRoleLabel()) == FALSE) { throw new MyRuntimeException(_('Access Denied'), 403); } //* 权限验证 ==根据业务逻辑定制== */ //* 数据验证 ==根据业务逻辑定制== */ //* 逻辑验证 ==根据业务逻辑定制== */ // 调用底层服务 !isset($servRouteInstance) && ($servRouteInstance = ServRouteInstance::getInstance(ServRouteConfig::getInstance())); // 执行业务逻辑 require_once Lemon::find_file('vendor', 'phprpc/phprpc_server', TRUE); $server = new PHPRPC_Server(); $server->add(array('phprpc_addAttachmentFileData', 'phprpc_getAttachmentDataById', 'phprpc_getStoreDataByStoreId', 'phprpc_getStoreDataByAttachmentId', 'phprpc_removeAttachmentDataByAttachmentId', 'phprpc_getStoreInfoByStoreId'), Attachment_Service::getInstance()); $server->start(); exit; throw new MyRuntimeException(_('Internal Error'), 500); //* 补充&修改返回结构体 */ $returnStruct['status'] = $returnStatus; $returnStruct['code'] = $returnCode; $returnStruct['msg'] = $returnMessage; $returnStruct['content'] = $returnData; //* 请求类型 */ if ($this->isAjaxRequest()) { // ajax 请求 // json 输出 $this->template->content = $returnStruct; } else { // html 输出 //* 模板输出 */ $this->template->returnStruct = $returnStruct; $content = new View('info'); //* 变量绑定 */ $this->template->title = Lemon::config('site.name'); $this->template->content = $content; //* 请求结构数据绑定 */ $this->template->content->requestData = $requestData; //* 返回结构体绑定 */ $this->template->content->returnStruct = $returnStruct; //:: 当前应用专用数据 $this->template->content->title = Lemon::config('site.name'); } // end of request type determine } catch (MyRuntimeException $ex) { $returnStruct['status'] = 0; $returnStruct['code'] = $ex->getCode(); $returnStruct['msg'] = $ex->getMessage(); //TODO 异常处理 //throw $ex; if ($this->isAjaxRequest()) { $this->template->content = $returnStruct; } else { $this->template->returnStruct = $returnStruct; $content = new View('info'); $this->template->content = $content; //* 请求结构数据绑定 */ $this->template->content->requestData = $requestData; //* 返回结构体绑定 */ $this->template->content->returnStruct = $returnStruct; } } }
/** * Get a variable. Access to sub-arrays is supported with key.subkey. * * @param string variable key * @param mixed default value returned if variable does not exist * @return mixed Variable data if key specified, otherwise array containing all session data. */ public function get($key = FALSE, $default = FALSE) { if (empty($key)) { return $_SESSION; } $result = isset($_SESSION[$key]) ? $_SESSION[$key] : Lemon::key_string($_SESSION, $key); return $result === NULL ? $default : $result; }