Esempio n. 1
0
 /**
  * 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;
 }
Esempio n. 2
0
 /**
  * Template loading and setup routine.
  */
 public function __construct($initSession = TRUE)
 {
     self::$msgNotice[0] = _('Access Denied');
     self::$msgNotice[1] = _('Login First Please');
     parent::__construct();
     $this->autoMinifiy = Lemon::config('core.output_minify');
     // checke request is ajax
     $this->ajaxRequest = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
     $this->logon = Logon::getInstance();
     $this->cookieLogon();
     // do init session
     if ($initSession == TRUE) {
         $PHPSESSIONID = $this->input->get('PHPSESSIONID');
         if (!empty($PHPSESSIONID)) {
             $this->sessionInstance = Session::instance($PHPSESSIONID);
         } else {
             $this->sessionInstance = Session::instance();
         }
         $getLogonInfo = $this->logon->getLogonInfo();
         if ($getLogonInfo['userId'] == 0 || $this->check_mgr && $getLogonInfo['mgrRole'] == Logon::$MGR_ROLE_LABEL_GUEST) {
             // 未登录用户才尝试去session里尝试获取一下用户信息。
             $this->setLogonInfoBySession();
         }
     }
     $this->userRoleLabel = $this->logon->getLogonInfoValueByKey('userRoleLabel', Logon::$USER_ROLE_LABEL_GUEST);
     $this->mgrRole = $this->logon->getLogonInfoValueByKey('mgrRole', Logon::$MGR_ROLE_LABEL_GUEST);
     // Load the app
     $this->template = new View($this->template);
     if ($this->autoRender == TRUE) {
         // Render the app immediately after the controller method
         Event::add('system.post_controller', array($this, '_render'));
     }
 }
Esempio n. 3
0
 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'));
 }
Esempio n. 4
0
 /**
  * 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;
 }
Esempio n. 5
0
 /**
  * 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);
 }
Esempio n. 6
0
 /**
  * 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;
 }
Esempio n. 7
0
 /**
  * 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;
     }
 }
Esempio n. 8
0
 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;
 }
Esempio n. 10
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;
     }
 }
Esempio n. 11
0
 private function getApiKey()
 {
     if ($this->apiKey === NULL) {
         $this->apiKey = Lemon::config('phprpc.local.' . $this->objectName . '.apiKey');
     }
     return $this->apiKey;
 }
Esempio n. 12
0
 public function write($id, $data)
 {
     $id = 'session_' . $id;
     $data = Lemon::config('session.encryption') ? $this->encrypt->encode($data) : $data;
     return $this->cache->set($id, $data);
 }
Esempio n. 13
0
 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;
         }
     }
 }
Esempio n. 14
0
 /**
  * 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;
 }
Esempio n. 15
0
 /**
  * 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;
         }
     }
 }
Esempio n. 16
0
 */
$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();';
Esempio n. 17
0
 /**
  * Create a new session.
  *
  * @param   array  variables to set after creation
  * @return  void
  */
 public function create($vars = NULL, $_session_id = NULL)
 {
     // Destroy any current sessions
     $this->destroy();
     if (Session::$config['driver'] !== 'native') {
         // Set driver name
         $driver = 'Session_' . ucfirst(Session::$config['driver']) . '_Driver';
         // Load the driver
         if (!Lemon::auto_load($driver)) {
             throw new LemonRuntimeException('core.driver_not_found ' . Session::$config['driver'], 500);
         }
         // Initialize the driver
         Session::$driver = new $driver();
         // Validate the driver
         if (!Session::$driver instanceof Session_Driver) {
             throw new LemonRuntimeException('core.driver_implements ' . Session::$config['driver'], 500);
         }
         // Register non-native driver as the session handler
         session_set_save_handler(array(Session::$driver, 'open'), array(Session::$driver, 'close'), array(Session::$driver, 'read'), array(Session::$driver, 'write'), array(Session::$driver, 'destroy'), array(Session::$driver, 'gc'));
     }
     // Validate the session name
     if (!preg_match('~^(?=.*[a-z])[a-z0-9_]++$~iD', Session::$config['name'])) {
         throw new LemonRuntimeException('session.invalid_session_name ' . Session::$config['name'], 500);
     }
     // Name the session, this will also be the name of the cookie
     session_name(Session::$config['name']);
     // Set the session cookie parameters
     session_set_cookie_params(Session::$config['expiration'], Lemon::config('cookie.path'), Lemon::config('cookie.domain'), Lemon::config('cookie.secure'), Lemon::config('cookie.httponly'));
     // Start the session!
     if ($_session_id !== NULL) {
         //log::write('dbglog','got_sessionid not null '.$_session_id.PHP_EOL,__FILE__,__LINE__);
         session_id($_session_id);
     }
     session_start();
     // Put session_id in the session variable
     $_SESSION['session_id'] = session_id();
     // Set defaults
     if (!isset($_SESSION['_kf_flash_'])) {
         $_SESSION['total_hits'] = 0;
         $_SESSION['_kf_flash_'] = array();
         $_SESSION['user_agent'] = Lemon::$user_agent;
         $_SESSION['ip_address'] = $this->input->ip_address();
     }
     // Set up flash variables
     Session::$flash =& $_SESSION['_kf_flash_'];
     // Increase total hits
     $_SESSION['total_hits'] += 1;
     // Validate data only on hits after one
     if ($_SESSION['total_hits'] > 1) {
         // Validate the session
         foreach (Session::$config['validate'] as $valid) {
             switch ($valid) {
                 // Check user agent for consistency
                 case 'user_agent':
                     if ($_SESSION[$valid] !== Lemon::$user_agent) {
                         return $this->create(NULL, $_session_id);
                     }
                     break;
                     // Check ip address for consistency
                 // Check ip address for consistency
                 case 'ip_address':
                     if ($_SESSION[$valid] !== $this->input->{$valid}()) {
                         return $this->create(NULL, $_session_id);
                     }
                     break;
                     // Check expiration time to prevent users from manually modifying it
                 // Check expiration time to prevent users from manually modifying it
                 case 'expiration':
                     if (time() - $_SESSION['last_activity'] > ini_get('session.gc_maxlifetime')) {
                         return $this->create(NULL, $_session_id);
                     }
                     break;
             }
         }
     }
     // Expire flash keys
     $this->expire_flash();
     // Update last activity
     $_SESSION['last_activity'] = time();
     // Set the new data
     Session::set($vars);
 }
Esempio n. 18
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;
         }
     }
 }
Esempio n. 19
0
 /**
  * 函数说明: 截取文件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;
     }
 }
Esempio n. 20
0
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>&#187 <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>&nbsp;</p> 
        <p><a href="http://www.zr4u.com" title="www.zr4u.com">www.zr4u.com</a></p>
        <p>&nbsp;</p>
    </div>
    <div id="ft">
        <p>-</p>
    </div>

</div>
Esempio n. 21
0
 protected function sqlType($str)
 {
     static $sqlTypes;
     if ($sqlTypes === NULL) {
         // Load SQL data types
         $sqlTypes = Lemon::config('sql_types');
     }
     $str = strtolower(trim($str));
     if (($open = strpos($str, '(')) !== FALSE) {
         // Find closing bracket
         $close = strpos($str, ')', $open) - 1;
         // Find the type without the size
         $type = substr($str, 0, $open);
     } else {
         // No length
         $type = $str;
     }
     empty($sqlTypes[$type]) and exit('Unknown field type: ' . $type);
     // Fetch the field definition
     $field = $sqlTypes[$type];
     switch ($field['type']) {
         case 'string':
         case 'float':
             if (isset($close)) {
                 // Add the length to the field info
                 $field['length'] = substr($str, $open + 1, $close - $open);
             }
             break;
         case 'int':
             // Add unsigned value
             $field['unsigned'] = strpos($str, 'unsigned') !== FALSE;
             break;
     }
     return $field;
 }
Esempio n. 22
0
 /**
  * Creates a meta tag.
  *
  * @param   string|array   tag name, or an array of tags
  * @param   string         tag "content" value
  * @return  string
  */
 public static function meta($tag, $value = NULL)
 {
     if (is_array($tag)) {
         $tags = array();
         foreach ($tag as $t => $v) {
             // Build each tag and add it to the array
             $tags[] = html::meta($t, $v);
         }
         // Return all of the tags as a string
         return implode("\n", $tags);
     }
     // Set the meta attribute value
     $attr = in_array(strtolower($tag), Lemon::config('http.meta_equiv')) ? 'http-equiv' : 'name';
     return '<meta ' . $attr . '="' . $tag . '" content="' . $value . '" />';
 }
Esempio n. 23
0
 /**
  * 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, '/');
 }
Esempio n. 24
0
<?php

//TODO 需要更标准化的设置方式,目前阶段直接使用统一设定方式,随后精细化设计。
//$domain = Lemon::config('locale.domain');
//$lang = Lemon::config('locale.lang');
//$charset = Lemon::config('locale.charset');
function setL10n($domain = 'default', $lang = 'zh_CN', $charset = 'UTF-8')
{
    putenv("LANGUAGE={$lang}");
    putenv("LANG={$lang}");
    //setlocale(LC_MESSAGES,'');
    setlocale(LC_ALL, $lang . '.' . $charset);
    bindtextdomain($domain, APP_PATH . 'locale/');
    bind_textdomain_codeset($domain, $charset);
    textdomain($domain);
}
//setL10n();
setL10n(Lemon::config('locale.domain'), Lemon::config('locale.lang'), Lemon::config('locale.charset'));
Esempio n. 25
0
 /**
  * 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;
 }
Esempio n. 26
0
 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;
         }
     }
 }
Esempio n. 27
0
 /**
  * 存储文件内容
  * @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;
 }
Esempio n. 28
0
 /**
  * Clean cross site scripting exploits from string.
  * HTMLPurifier may be used if installed, otherwise defaults to built in method.
  * Note - This function should only be used to deal with data upon submission.
  * It's not something that should be used for general runtime processing
  * since it requires a fair amount of processing overhead.
  *
  * @param   string  data to clean
  * @param   string  xss_clean method to use ('htmlpurifier' or defaults to built-in method)
  * @return  string
  */
 public function xss_clean($data, $tool = NULL)
 {
     if ($tool === NULL) {
         // Use the default tool
         $tool = Lemon::config('core.global_xss_filtering');
     }
     if (is_array($data)) {
         foreach ($data as $key => $val) {
             $data[$key] = $this->xss_clean($val, $tool);
         }
         return $data;
     }
     // Do not clean empty strings
     if (trim($data) === '') {
         return $data;
     }
     if ($tool === TRUE) {
         // NOTE: This is necessary because switch is NOT type-sensative!
         $tool = 'default';
     }
     switch ($tool) {
         case 'htmlpurifier':
             /**
              * @todo License should go here, http://htmlpurifier.org/
              */
             if (!class_exists('HTMLPurifier_Config', FALSE)) {
                 // Load HTMLPurifier
                 require Lemon::find_file('vendor', 'htmlpurifier/HTMLPurifier.auto', TRUE);
                 require 'HTMLPurifier.func.php';
             }
             // Set configuration
             $config = HTMLPurifier_Config::createDefault();
             $config->set('HTML', 'TidyLevel', 'none');
             // Only XSS cleaning now
             // Run HTMLPurifier
             $data = HTMLPurifier($data, $config);
             break;
         default:
             // http://svn.bitflux.ch/repos/public/popoon/trunk/classes/externalinput.php
             // +----------------------------------------------------------------------+
             // | Copyright (c) 2001-2006 Bitflux GmbH                                 |
             // +----------------------------------------------------------------------+
             // | Licensed under the Apache License, Version 2.0 (the "License");      |
             // | you may not use this file except in compliance with the License.     |
             // | You may obtain a copy of the License at                              |
             // | http://www.apache.org/licenses/LICENSE-2.0                           |
             // | Unless required by applicable law or agreed to in writing, software  |
             // | distributed under the License is distributed on an "AS IS" BASIS,    |
             // | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
             // | implied. See the License for the specific language governing         |
             // | permissions and limitations under the License.                       |
             // +----------------------------------------------------------------------+
             // | Author: Christian Stocker <*****@*****.**>                        |
             // +----------------------------------------------------------------------+
             //
             // Lemon Modifications:
             // * Changed double quotes to single quotes, changed indenting and spacing
             // * Removed magic_quotes stuff
             // * Increased regex readability:
             //   * Used delimeters that aren't found in the pattern
             //   * Removed all unneeded escapes
             //   * Deleted U modifiers and swapped greediness where needed
             // * Increased regex speed:
             //   * Made capturing parentheses non-capturing where possible
             //   * Removed parentheses where possible
             //   * Split up alternation alternatives
             //   * Made some quantifiers possessive
             // Fix &entity\n;
             $data = str_replace(array('&amp;', '&lt;', '&gt;'), array('&amp;amp;', '&amp;lt;', '&amp;gt;'), $data);
             $data = preg_replace('/(&#*\\w+)[\\x00-\\x20]+;/u', '$1;', $data);
             $data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
             $data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');
             // Remove any attribute starting with "on" or xmlns
             $data = preg_replace('#(<[^>]+?[\\x00-\\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);
             // Remove javascript: and vbscript: protocols
             $data = preg_replace('#([a-z]*)[\\x00-\\x20]*=[\\x00-\\x20]*([`\'"]*)[\\x00-\\x20]*j[\\x00-\\x20]*a[\\x00-\\x20]*v[\\x00-\\x20]*a[\\x00-\\x20]*s[\\x00-\\x20]*c[\\x00-\\x20]*r[\\x00-\\x20]*i[\\x00-\\x20]*p[\\x00-\\x20]*t[\\x00-\\x20]*:#iu', '$1=$2nojavascript...', $data);
             $data = preg_replace('#([a-z]*)[\\x00-\\x20]*=([\'"]*)[\\x00-\\x20]*v[\\x00-\\x20]*b[\\x00-\\x20]*s[\\x00-\\x20]*c[\\x00-\\x20]*r[\\x00-\\x20]*i[\\x00-\\x20]*p[\\x00-\\x20]*t[\\x00-\\x20]*:#iu', '$1=$2novbscript...', $data);
             $data = preg_replace('#([a-z]*)[\\x00-\\x20]*=([\'"]*)[\\x00-\\x20]*-moz-binding[\\x00-\\x20]*:#u', '$1=$2nomozbinding...', $data);
             // Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
             $data = preg_replace('#(<[^>]+?)style[\\x00-\\x20]*=[\\x00-\\x20]*[`\'"]*.*?expression[\\x00-\\x20]*\\([^>]*+>#i', '$1>', $data);
             $data = preg_replace('#(<[^>]+?)style[\\x00-\\x20]*=[\\x00-\\x20]*[`\'"]*.*?behaviour[\\x00-\\x20]*\\([^>]*+>#i', '$1>', $data);
             $data = preg_replace('#(<[^>]+?)style[\\x00-\\x20]*=[\\x00-\\x20]*[`\'"]*.*?s[\\x00-\\x20]*c[\\x00-\\x20]*r[\\x00-\\x20]*i[\\x00-\\x20]*p[\\x00-\\x20]*t[\\x00-\\x20]*:*[^>]*+>#iu', '$1>', $data);
             // Remove namespaced elements (we do not need them)
             $data = preg_replace('#</*\\w+:\\w[^>]*+>#i', '', $data);
             do {
                 // Remove really unwanted tags
                 $old_data = $data;
                 $data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
             } while ($old_data !== $data);
             break;
     }
     return $data;
 }