/** * 备份 * * @access public * @param array $tables * @param mixed $file_name * @return mixed */ public function back($tables = array(), $file_name = null) { //$model = new Model(); $sql = ""; foreach ($tables as $table) { $row = $this->db->doSql("show create table `{$table}` "); $sql .= "DROP TABLE IF EXISTS `" . $row[0]['Table'] . "`;\n"; $sql .= $row[0]['Create Table'] . ";\n"; $rows = $this->db->doSql("select * from `{$table}`"); if (count($rows) > 0) { $sql .= 'INSERT INTO `' . $table . '` (`'; $fields = (array) current($rows); $keys = array_keys($fields); $sql .= implode("`,`", $keys) . "`) VALUES "; foreach ($rows as $row) { $values = array_values($row); foreach ($values as $key => $value) { $values[$key] = mysql_real_escape_string($value); } $sql .= "('" . implode("','", $values) . "'),"; } $sql = rtrim($sql, ","); $sql .= ";\n"; } } if ($file_name == null) { $file_name = date('YmdH') . '_' . rand(1000, 9999) . '_' . rand(1000, 9999) . '.sql'; } $database_path = Tiny::getPath('database') . $file_name; $file = new File($database_path, 'w+'); return $file->write($sql); }
public function before($obj = null) { // 推荐商户设置 add by t-btei 2015/05/04 $companyId = Req::args('companyId'); if (isset($companyId)) { // 保存推荐ID setcookie('company_affiliate_uid', $companyId); } //测试平板或者手机端主题 $clientType = Chips::clientType(); if ($clientType == 'tablet' || $clientType == 'mobile') { $config_path = APP_CODE_ROOT . 'config/config.php'; $config = (require $config_path); if (isset($config['themes_mobile'])) { $themes_mobile = Tiny::app()->setTheme($config['themes_mobile']); } else { Tiny::app()->setTheme("default"); } } $config = Config::getInstance(); $site = $config->get('globals'); $other = $config->get('other'); $currency_symbol = isset($other['other_currency_symbol']) ? $other['other_currency_symbol'] : '¥'; $site_logo = isset($site['site_logo']) && $site['site_logo'] != '' ? $site['site_logo'] : 'static/images/logo.png'; $site_qr = isset($site['site_qr']) && $site['site_qr'] != '' ? $site['site_qr'] : 'static/images/qr-app.png'; $site_name = isset($site['site_name']) ? $site['site_name'] : 'TinyShop商城'; $site_icp = isset($site['site_icp']) ? $site['site_icp'] : '鲁ICP备00000100号'; $obj->assign('currency_symbol', $currency_symbol); $obj->assign('site_logo', $site_logo); $obj->assign('site_qr', $site_qr); $obj->assign('site_name', $site_name); $obj->assign('site_icp', $site_icp); }
/** * 取得数据库信息 * * @access public * @return mixed */ public static function getDbInfo() { if (self::$dbinfo == null) { self::$dbinfo = Tiny::app()->db; } return self::$dbinfo; }
/** * 构造初始化 * * @access public * @param mixed $fieldName * @param string $uploadPath * @param string $size * @param string $types * @param string $nameType * @param string $nameId */ public function __construct($fieldName, $uploadPath = "", $size = '500k', $types = '', $nameType = 'date', $nameId = '') { if (isset($_FILES[$fieldName])) { $this->files = $_FILES[$fieldName]; if ($uploadPath == '') { $this->uploadPath = Tiny::getPath('uploads'); } else { $this->uploadPath = $uploadPath; } $endchar = strtolower(substr($size, -1)); if ($endchar == 'k') { $this->size = substr($size, 0, -1) << 10; } else { if ($endchar == 'm') { $this->size = substr($size, 0, -1) << 20; } else { $this->size = intval($size); } } if ($types != '') { $this->types = ",{$types},"; } $this->nameType = $nameType; $this->fileNameId = $nameId; } }
public static function text($str) { $config = HTMLPurifier_Config::createDefault(); $cache_dir = Tiny::getPath('cache') . "/htmlpurifier/"; if (!file_exists($cache_dir)) { File::mkdir($cache_dir); } $config = HTMLPurifier_Config::createDefault(); //配置 缓存目录 $config->set('Cache.SerializerPath', $cache_dir); //设置cache目录 //配置 允许flash $config->set('HTML.SafeEmbed', true); $config->set('HTML.SafeObject', true); $config->set('Output.FlashCompat', true); //$config->set('HTML.Allowed', 'p'); //$config->set('AutoFormat.AutoParagraph', true); //$config->set('AutoFormat.RemoveEmpty', true); //允许<a>的target属性 $def = $config->getHTMLDefinition(true); $def->addAttribute('a', 'target', 'Enum#_blank,_self,_target,_top'); $purifier = new HTMLPurifier($config); if (get_magic_quotes_gpc()) { $str = stripslashes($str); $str = $purifier->purify($str); $str = addslashes($str); } else { $str = $purifier->purify($str); } return self::sql($str); }
/** * 构造函数 * * @access public * @param mixed $tpl */ public function __construct($tpl) { $this->tplfile = Tiny::app()->getRuntimePath() . $tpl . '.php'; if (!file_exists($this->tplfile) || filemtime($this->tplfile) < filemtime($tpl)) { $file = new File($this->tplfile, 'w+'); $template = $file->getContents($tpl); $t = new Tag(); $tem = $t->resolve($template); $file->write($tem); } }
public function getFlashSaleWithProducts() { $model = new Model("flash_sale"); // $productSel = $model->limit(1)->fields("tiny_flash_sale.*, tiny_goods.name, tiny_goods.store_nums left join tiny_goods")->find(); $productSel = $model->fields("*")->findAll(); if ($productSel) { Tiny::log($productSel); return $productSel; } else { return NULL; } }
public function getBundlingList($ids) { $products = array(); // $model = new Model("products as pr"); Tiny::log(__FILE__ . __LINE__ . "------product---id----{$ids}---" . var_export($ids, true)); if ($ids != '') { $str_ids = trim(implode(",", $ids), ','); $products = $this->model->fields("pr.*,go.img,go.name,go.prom_id,go.point,go.series_id as series_id, go.ship_id as ship_id")->join("left join goods as go on pr.goods_id = go.id ")->where("pr.id in({$str_ids})")->findAll(); return $products; } else { return NULL; } }
public static function getInstance($type = 'session') { if (!self::$obj instanceof self) { $type = strtolower($type); if ($type == 'session') { self::$box = new Session(); } else { self::$box = new Cookie(); self::$box->setSafeCode(Tiny::app()->getSafeCode()); } self::$obj = new self(); } return self::$box; }
public function __construct($id, $parent, $config = null) { $this->id = $id; $this->parentModule = $parent; if (is_string($config)) { $config = (require $config); } if (isset($config['basePath'])) { $this->setBasePath($config['basePath']); unset($config['basePath']); } $this->configure($config); Tiny::setPath($id, $this->getBasePath()); }
public function get_pic_url() { $this->apiModel = new ApiModel(); // 取得欢迎页面图片的URL $data = $this->apiModel->getWelPicUrl(); $url = $data['url']; Tiny::log($url); $retData = array("modifiedTime" => "", "imgUrl" => ""); if (isset($url)) { $picUrl = Url::fullUrlFormat("/{$url}"); Tiny::log($picUrl); $picTime = strtotime($data['last_update_time']); $time = date('YmdHis', $picTime); $retData["modifiedTime"] = $time; $retData["imgUrl"] = $picUrl; } // echo JSON::encode($retData,JSON_UNESCAPED_SLASHES); echo json_encode($retData, JSON_UNESCAPED_SLASHES); }
/** * 引入css文件有调用方法 * * @access public * @param mixed $package 框架包名 * @param mixed $name * @return String */ public static function import($package, $name = null) { if (isset(self::$CSSPackages[$package])) { $file = null; $is_file = false; if (is_string(self::$CSSPackages[$package])) { $is_file = true; $file = self::$CSSPackages[$package]; } else { $csspackage = self::$CSSPackages[$package]; reset($csspackage); $file = current($csspackage); } if (!isset(self::$createfiles[$package])) { $file_path = $file; if (!$is_file) { $file_path = dirname($file); } if (!file_exists(Tiny::app()->getRuntimePath() . '/systemcss/' . $file_path)) { File::xcopy(TINY_ROOT . '/web/css/source/' . $file_path, Tiny::app()->getRuntimePath() . '/systemcss/' . $file_path); } self::$createfiles[$package] = true; } $webcsspath = Tiny::app()->getRuntimeUrl() . '/systemcss/'; if ($is_file || $name !== null) { if (isset(self::$CSSPackages[$package][$name])) { return '<link rel="stylesheet" type="text/css" href="' . $webcsspath . self::$CSSPackages[$package][$name] . '"/>'; } else { return ''; } } else { $tmp = ''; foreach (self::$CSSPackages[$package] as $file) { $tmp .= '<link rel="stylesheet" type="text/css" href="' . $webcsspath . $file . '"/>'; } return $tmp; } } else { return ''; } }
public function logout() { $this->safebox->clear('user'); $cookie = new Cookie(); $cookie->setSafeCode(Tiny::app()->getSafeCode()); $cookie->set('autologin', null, 0); $this->redirect('login'); }
/** * 执行SQL * * @access public * @param mixed $sql * @return mixed */ public function doSql($sql) { //更好的处理表前缀 //$mainStr = ltrim(self::$dbinfo['tablePre'],'tiny_'); $sql = preg_replace('/(\\s+|,)(tiny_)+/i', '$1' . self::$dbinfo['tablePre'], $sql); $sql = trim($sql); if (DEBUG) { $doSqlBeforTime = microtime(true); $result = mysql_query($sql, self::$conn); $useTime = microtime(true) - $doSqlBeforTime; Tiny::setSqlLog($sql, $useTime); } else { $result = mysql_query($sql, self::$conn); } //查询不成功时返回空数组 $rows = array(); //分析出读写操作 if (preg_match("/^(select|show)(.*)/i", $sql) == 0) { if ($result) { if (stripos($sql, 'insert') !== false) { return $this->lastId(); } else { if (stripos($sql, 'update') !== false) { return mysql_affected_rows(); } } return $result; } return false; } else { if (is_resource($result)) { while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $rows[] = $row; } mysql_free_result($result); return $rows; } else { if (DEBUG) { throw new Exception("SQLError:{$sql} ," . mysql_error() . "", E_USER_ERROR); } } return array(); } }
/** *路径格式化处理 */ static function urlFormat($path) { if ($path == '') { return self::baseDir(); } if (preg_match('@[/\\@#*!]?(http://.+)$@i', $path, $matches)) { return $matches[1]; } switch (substr($path, 0, 1)) { case '/': $path = self::createUrl($path); return rtrim(self::baseUri(), '/') . $path; //解释成绝对路由地址 case '@': return self::baseDir() . substr($path, 1); //解析成绝对路径 //解析成绝对路径 case '#': if (Tiny::app()->getTheme() !== null) { return Tiny::app()->getTheme()->getBaseUrl() . '/' . substr($path, 1); } else { return self::baseDir() . substr($path, 1); } case '*': if (Tiny::app()->getTheme() !== null && Tiny::app()->getSkin() !== null) { $theme = Tiny::app()->getTheme(); return $theme->getBaseUrl() . '/skins/' . Tiny::app()->getSkin() . '/' . substr($path, 1); } else { if (Tiny::app()->getSkin() !== null) { return self::baseDir() . 'skins/' . Tiny::app()->getSkin() . '/' . substr($path, 1); } else { return self::urlFormat('#' . substr($path, 1)); } } case '!': return Tiny::app()->getRuntimeUrl() . '/' . substr($path, 1); default: $q = Req::get(); $url = '/' . $q['con'] . '/' . $q['act']; unset($q['con'], $q['act']); $query = explode('/', trim($path, '/')); $new_q = array(); $len = count($query); for ($i = 0; $i < $len; $i++) { if ($i % 2 == 1) { $new_q[$query[$i - 1]] = $query[$i]; } } $q = array_merge($q, $new_q); foreach ($q as $k => $v) { if (is_string($k)) { $url .= '/' . $k . '/' . $v; } } $path = self::createUrl($url); return rtrim(self::baseUri(), '/') . $path; //解释成绝对路由地址 } }
/** * 生成短信验证码接口 * AJAX * apikey 为云片分配的apikey * text 为短信内容 * mobile 为接受短信的手机号 */ public function send_auth_code() { $info = array('status' => false, 'msg' => '验证码发送失败!'); // $apikey = "06ec231c5d876ffe119b38013662f661"; // todo 短信接口部署时,需修改这里的APIKEY $phoneNumber = Filter::int(Req::args("mobile")); $config_inst = Config::getInstance(); $config = $config_inst->get("sms"); $apikey = $config['api_key']; $authChars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; //验证码生成 $authCode = ''; for ($i = 0; $i < 4; $i++) { $authCode .= substr($authChars, mt_rand(0, strlen($authChars) - 1), 1); } $authCode = strtolower($authCode); // 变成小写 // $text = "【全品电台】您的验证码是".$authCode; $text = "【全品电台】感谢您的注册,您的验证码是 {$authCode} 。有效期为3分钟,请尽快验证"; //$text = "【云片网】您的验证码是".$authCode; Tiny::log(__FILE__ . '--' . __LINE__ . '--' . $phoneNumber . "--" . $authCode . "--" . $text); //验证码与手机号码绑定 $model = $this->model->table("auth_code"); $obj = $model->where('phone_number=' . $phoneNumber)->find(); $time = date('Y-m-d H:i:s', strtotime("+3 minutes")); if ($obj == null) { $data['phone_number'] = $phoneNumber; $data['auth_code'] = $authCode; $data['start_time'] = date('Y-m-d H:i:s'); $data['end_time'] = $time; $auth_code_id = $this->model->table("auth_code")->data($data)->insert(); if ($auth_code_id) { //发送验证码,发送成功 //Tiny::log("auth_code 表 ID--".$auth_code_id); // todo SKM 要发短信验证码时,把下面注释去掉 $sms = new Sms(); $ret = $sms->send_sms($apikey, $text, $phoneNumber); // todo SKM SMS服务正式提供后,把下面一行代码注释掉 //$ret = array('code' => 0, 'msg' => 'OK'); if (isset($ret['code']) && $ret['code'] == 0) { $info['status'] = true; //$info['msg'] = "发送验证码成功!短信API接口返回:".$ret['msg']; $info['msg'] = "发送验证码成功!"; } else { $info['status'] = false; //$info['msg'] = "发送验证码失败!短信API接口返回:".$ret['msg']; Tiny::log(__FILE__ . '-' . __LINE__ . '-' . "短信接口发送失败:" . var_export($ret, true)); $info['msg'] = "发送验证码失败!"; } echo JSON::encode($info); } else { // 插入失败 Tiny::log(__FILE__ . '-' . __LINE__ . '-' . "插入失败:auth_code--" . $auth_code_id); echo JSON::encode($info); } } else { // 1分钟内不能发送2次验证码 $expired_time = strtotime("+3 minutes", intval($obj['start_time'])); if ($expired_time > strtotime(date('y-m-d h:i:s'))) { $info['status'] = false; $info['msg'] = "两次验证码发送间隔不能少于60秒!"; echo JSON::encode($info); } else { // 已经存在验证码,更新验证码, 从新发送到手机上 $obj['auth_code'] = $authCode; $obj['start_time'] = date('Y-m-d H:i:s'); $obj['end_time'] = $time; $model->data($obj)->update(); // 重新发送 $sms = new Sms(); $ret = $sms->send_sms($apikey, $text, $phoneNumber); //$ret = array('code' => 0, 'msg' => 'OK'); $info['status'] = true; $info['msg'] = "发送验证码成功!"; echo JSON::encode($info); } } }
/** * 渲染 * * @access public * @param mixed $viewFile * @param bool $return * @return mixed */ public function renderInternal($viewFile, $return = false) { $data = $this->properties; if (is_array($data)) { extract($data, EXTR_PREFIX_SAME, 'data'); } $tplfile = $this->getViewFile($viewFile); if (file_exists($tplfile)) { $runfile = Tiny::app()->getRuntimePath() . DIRECTORY_SEPARATOR . 'widgets/' . $viewFile . '.php'; if (!file_exists($runfile) || filemtime($runfile) < filemtime($tplfile)) { $file = new File($runfile, 'w+'); $template = $file->getContents($tplfile); $t = new Tag(); $tem = $t->resolve($template); $file->write($tem); } header("Content-type: text/html; charset=" . $this->encoding); if ($return) { ob_start(); ob_implicit_flush(false); require $runfile; return ob_get_clean(); } else { require $runfile; } } else { if ($this->id != Tiny::app()->getId()) { trigger_error("{$this->id}Widget->{$this->getAction()}() not exists", E_USER_ERROR); } else { Tiny::msg('', '无法找到请求的页面', 404); } } }
private function returnXML($success = "true", $errorCode = "", $errorMsg = "") { echo '<?xml version="1.0" encoding="UTF-8" ?> <response> <success>' . $success . '</success> <errorCode>' . $errorCode . '</errorCode> <errorMsg>' . $errorMsg . '</errorMsg> </response>'; Tiny::log("returnXML【success:" . $success . "】errorCode【" . $errorCode . "】errorMsg【" . $errorMsg . "】"); exit; }
/** * 创建控制器 * * @access public * @return mixed */ public function createController() { $controllerName = Req::args('con') !== null ? ucfirst(Req::args('con')) : $this->defaultController; $controllerClass = $controllerName . 'Controller'; $widgetClass = $controllerName . 'Widget'; if (class_exists($controllerClass)) { return new $controllerClass(strtolower($controllerName), $this); } else { if (class_exists($widgetClass)) { return new $widgetClass($controllerName, $this); } else { if (Tiny::getErrorsController() !== null) { $errorsController = Tiny::getErrorsController(); return $errorsController; } else { return new Controller($controllerName, $this); } } } }
public function all() { // 计算税金 foreach ($this->items as $ship_id => $ship_item) { $ret = $this->getTaxAmountByShip($ship_id); if (isset($ret['status']) && $ret['status'] == 1) { $this->items[$ship_id]['tax_amount'] = $ret['data']; } else { $this->items[$ship_id]['tax_amount'] = 0; } } Tiny::log(__FILE__ . __LINE__ . "------------carts----------" . var_export($this->items, true)); return $this->items; }
/** * 引用方法 * * @access public * @param mixed $name * @param string $charset * @return String */ public static function import($name, $charset = 'UTF-8') { $parames = explode('?', $name); $name = $parames[0]; if (isset($parames[1])) { $parames = '?' . $parames[1]; } else { $parames = ''; } if (isset(self::$JSPackages[$name])) { if (!isset(self::$createfiles[$name])) { $is_file = false; $file = null; if (is_string(self::$JSPackages[$name])) { if (stripos(self::$JSPackages[$name], '/') === false) { $is_file = true; $file = self::$JSPackages[$name]; } else { $file = dirname(self::$JSPackages[$name]); } } else { if (is_array(self::$JSPackages[$name]['js'])) { $file = dirname(self::$JSPackages[$name]['js'][0]); } else { $file = dirname(self::$JSPackages[$name]['js']); } } if (!file_exists(APP_ROOT . 'runtime/systemjs/' . $file)) { self::$createfiles[$name] = true; File::xcopy(TINY_ROOT . '/web/js/source/' . $file, APP_ROOT . 'runtime/systemjs/' . $file); } } $webjspath = Tiny::app()->getRuntimeUrl() . '/systemjs/'; if (is_string(self::$JSPackages[$name])) { return '<script type="text/javascript" charset="' . $charset . '" src="' . $webjspath . self::$JSPackages[$name] . $parames . '"></script>'; } else { if (is_array(self::$JSPackages[$name])) { $str = ''; if (isset(self::$JSPackages[$name]['css'])) { if (is_string(self::$JSPackages[$name]['css'])) { $str .= '<link rel="stylesheet" type="text/css" href="' . $webjspath . self::$JSPackages[$name]['css'] . '"/>'; } else { if (is_array(self::$JSPackages[$name]['css'])) { foreach (self::$JSPackages[$name]['css'] as $css) { $str .= '<link rel="stylesheet" type="text/css" href="' . $webjspath . $css . '"/>'; } } } } if (isset(self::$JSPackages[$name]['js'])) { if (is_array(self::$JSPackages[$name]['js'])) { foreach (self::$JSPackages[$name]['js'] as $js) { $str .= '<script type="text/javascript" charset="' . $charset . '" src="' . $webjspath . $js . $parames . '"></script>'; } } else { $str .= '<script type="text/javascript" charset="' . $charset . '" src="' . $webjspath . self::$JSPackages[$name]['js'] . $parames . '"></script>'; } } return $str; } } } else { return ''; } }
public function order_detail() { $id = Filter::int(Req::args("id")); $order = $this->model->table("order as od")->fields("od.*,pa.pay_name")->join("left join payment as pa on od.payment = pa.id")->where("od.id = {$id} and od.user_id=" . $this->user['id'])->find(); if ($order) { $invoice = $this->model->table("doc_invoice as di")->fields("di.*,ec.code as ec_code,ec.name as ec_name,ec.alias as ec_alias")->join("left join express_company as ec on di.express_company_id = ec.id")->where("di.order_id=" . $id)->find(); $order_goods = $this->model->table("order_goods as og ")->join("left join goods as go on og.goods_id = go.id left join products as pr on og.product_id = pr.id")->where("og.order_id=" . $id)->findAll(); $this->assign("order_goods", $order_goods); $this->assign("invoice", $invoice); $this->assign("order", $order); $order_init = new Order(); $order_id = Filter::int(Req::args("id")); $ret = $order_init->getOrderWithDetail($order_id); if ($ret['status'] == 1) { $order_list = $ret['data']; } $order_goods_list = $order_list['OrderGoods']; if ($order_goods_list) { foreach ($order_goods_list as $key => $item) { if ($item['prom_type'] == 'bundling') { $goods_attrs[] = $item['products_ids']; $products_init = new Products(); $ret = $products_init->getProducts($goods_attrs); if ($ret['status'] == 1) { $products_list = $ret['data']; } $order_goods_list[$key]["products_list"] = $products_list; } } $this->assign('order_goods_list', $order_goods_list); } $this->redirect(); } else { Tiny::Msg($this, 404); } }
/** * 取得编译后的运行路径 * * @access public * @return mixed */ public function getRuntimePath() { if ($this->runtimePath !== null) { return $this->runtimePath; } else { if (($theme = Tiny::app()->getTheme()) !== null) { $this->setRuntimePath('runtime' . DIRECTORY_SEPARATOR . $theme->getName()); } else { $this->setRuntimePath('runtime'); } return $this->runtimePath; } }
/** * 处理设定的每一个标签 * * @access public * @param mixed $matches * @return mixed */ public function translate($matches) { $suffix = '_' . self::$num++; if ($matches[1] !== '/') { switch ($matches[2] . $matches[3]) { case '$': $str = trim($matches[4]); $data = explode('|', $str); if ($str[0] == '.' || $str[0] == '(') { return $matches[0]; } $len = count($data); if ($len == 1) { return '<?php echo isset($' . $matches[4] . ')?$' . $matches[4] . ':"";?>'; } else { if ($len == 2) { return '<?php echo isset($' . $data[0] . ')?$' . $data[0] . ':' . $data[1] . ';?>'; } else { if ($len > 2) { $filter = strtolower($data[$len - 1]); switch ($filter) { case 'encode': return '<?php echo isset($' . $data[0] . ')?htmlspecialchars($' . $data[0] . '):' . $data[1] . ';?>'; case 'int': case 'str': case 'float': case 'txt': case 'sql': case 'text': return '<?php echo isset($' . $data[0] . ')?Filter::' . $filter . '($' . $data[0] . '):' . $data[1] . ';?>'; default: return '<?php echo isset($' . $data[0] . ') && $' . $data[0] . '?' . $data[1] . ':' . $data[2] . ';?>'; } } } } case 'echo:': return '<?php echo ' . rtrim($matches[4], ';/') . ';?>'; case 'url:': return '<?php echo urldecode(Url::urlFormat("' . trim($matches[4]) . '"));?>'; case 'if:': return '<?php if(' . $matches[4] . '){?>'; case 'elseif:': return '<?php }elseif(' . $matches[4] . '){?>'; case 'else:': return '<?php }else{' . $matches[4] . '?>'; case 'set:': return '<?php ' . rtrim($matches[4], ';/') . ';?>'; case 'while:': return '<?php while(' . $matches[4] . '){?>'; case 'dump:': return '<pre><?php var_dump(' . $matches[4] . '); ?></pre>'; case 'list:': case 'foreach:': $attr = $this->getAttrs($matches[4]); if (!isset($attr['items'])) { $attr['items'] = '$items'; } else { $attr['items'] = $attr['items']; } if (!isset($attr['key'])) { $attr['key'] = '$key'; } else { $attr['key'] = $attr['key']; } if (!isset($attr['item'])) { $attr['item'] = '$item'; } else { $attr['item'] = $attr['item']; } return '<?php foreach(' . $attr['items'] . ' as ' . $attr['key'] . ' => ' . $attr['item'] . '){?>'; case 'for:': $attr = $this->getAttrs($matches[4]); if (!isset($attr['item'])) { $attr['item'] = '$i'; } else { $attr['item'] = $attr['item']; } if (!isset($attr['from'])) { $attr['from'] = 0; } if (!isset($attr['to'])) { $attr['to'] = 10; } if (!isset($attr['step'])) { $attr['step'] = 1; } return '<?php for($total' . $suffix . ' = (int) ceil((' . $attr['step'] . ' > 0 ? ' . $attr['to'] . '+1 - (' . $attr['from'] . ') : ' . $attr['from'] . '-(' . $attr['to'] . ')+1)/abs(' . $attr['step'] . ')),' . $attr['item'] . ' = ' . $attr['from'] . ',$start' . $suffix . '=1 ; $total' . $suffix . '>0 && $start' . $suffix . '<=$total' . $suffix . ' ; ' . $attr['item'] . ' += ' . $attr['step'] . ',$start' . $suffix . ' += 1){?>'; case 'widget:': $attr = $this->getAttrs($matches[4]); $className = isset($attr['name']) ? $attr['name'] : null; $method = isset($attr['method']) ? $attr['method'] : 'init'; $args = isset($attr['args']) ? $attr['args'] : null; $attr['cache'] = isset($attr['cache']) ? "true" : "false"; //$cacheTime = isset($attr['cachetime'])?intval($attr['cachetime']):30; $old_char = array(' ne ', ' eq ', ' lt ', ' gt ', ' le ', ' ge '); $new_char = array(' != ', ' = ', ' < ', ' > ', ' <= ', ' >= '); $tem = "<div id='widget_{$className}'><?php \$widget = Widget::createWidget('{$className}');"; foreach ($attr as $k => $v) { if ($k != 'name') { $v = str_replace($old_char, $new_char, $v); if (substr($v, 0, 1) == '$') { $tem .= '$widget->' . $k . ' = ' . $v . ';'; } else { $tem .= '$widget->' . $k . ' = "' . $v . '";'; } } } $tem .= "\$widget->run();?></div>"; return $tem; case 'query:': $endchart = substr(trim($matches[4]), -1); $attrs = $this->getAttrs(rtrim($matches[4], '/')); if (!isset($attrs['id'])) { $id = '$query'; } else { $id = $attrs['id']; } if (!isset($attrs['items'])) { $items = '$items'; } else { $items = $attrs['items']; } $tem = $id . ' = new Query("' . $attrs['name'] . '");'; //实现属性中符号表达式的问题 $old_char = array(' ne ', ' eq ', ' lt ', ' gt ', ' le ', ' ge '); $new_char = array(' != ', ' = ', ' < ', ' > ', ' <= ', ' >= '); foreach ($attrs as $k => $v) { if ($k != 'name' && $k != 'id' && $k != 'items') { $tem .= $id . '->' . $k . ' = "' . str_replace($old_char, $new_char, $v) . '";'; } } $tem .= $items . ' = ' . $id . '->find();'; if (!isset($attrs['key'])) { $attrs['key'] = '$key'; } else { $attrs['key'] = $attrs['key']; } if (!isset($attrs['item'])) { $attrs['item'] = '$item'; } else { $attrs['item'] = $attrs['item']; } if ($endchart == '/') { return '<?php ' . $tem . '?>'; } else { return '<?php ' . $attrs['item'] . '=null; ' . $tem . ' foreach(' . $items . ' as ' . $attrs['key'] . ' => ' . $attrs['item'] . '){?>'; } case 'token:': $attr = $this->getAttrs(rtrim($matches[4], '/')); if (isset($attr['key']) && is_string($attr['key'])) { $key = $attr['key']; } else { $key = ''; } return "<input type='hidden' name='tiny_token_" . $key . "' value='<?php echo Tiny::app()->getToken(\"" . $key . "\");?>'/>"; case 'debug:': $matches[4] = rtrim($matches[4], ';/'); if ($matches[4] != '') { return '<pre>' . $matches[4] . ' = <?php var_dump(' . $matches[4] . ');?></pre>'; } else { return '<?php $debug = new Debug(); $out = get_defined_vars(); $debug->out($out); $debug->display();?>'; } case 'code:': return '<?php ' . $matches[4]; case 'require:': case 'include:': $fileName = trim($matches[4]); $viewfile = Tiny::app()->getViewPath() . DIRECTORY_SEPARATOR . $this->viewPath . DIRECTORY_SEPARATOR . $fileName; $runfile = Tiny::app()->getRuntimePath() . DIRECTORY_SEPARATOR . $this->viewPath . DIRECTORY_SEPARATOR . $fileName; if (!file_exists($runfile) || filemtime($runfile) < filemtime($viewfile)) { $file = new File($runfile, 'w+'); $template = $file->getContents($viewfile); $t = new Tag(); $tem = $t->resolve($template, dirname($viewfile)); $file->write($tem); } return '<?php include("' . trim($matches[4]) . '")?>'; default: return $matches[0]; } } else { if ($matches[2] == 'code') { return '?>'; } else { if ($matches[2] != 'widget') { return '<?php }?>'; } } } }
<?php /** * Handle creation of tiny url. */ require_once "../Library/Tiny.php"; require_once "../Library/functions.php"; if (isset($_POST["url"])) { $url = rtrim($_POST["url"], "/"); if (!filter_var($url, FILTER_VALIDATE_URL)) { $response = array("status" => 'error', "message" => "Submitted URL is not a valid URL", "error_code" => 20); echo json_encode($response); } else { try { $tiny = new Tiny(); echo $tiny->createUrl($url); } catch (Exception $e) { $response = array("status" => 'error', "message" => "Error connecting. Try again", "error_code" => 50); echo json_encode($response); } } } else { redirectPage("index.php"); }
function photoshop_upload() { $file = $_FILES['upfile']; if ($file['error'] == 4) { $msg = array('error', '请选择文件后再上传!'); $this->redirect("photoshop", true, array('msg' => $msg)); } else { if ($file['error'] == 1) { $msg = array('error', '文件超出了php.ini文件指定大小!'); $this->redirect("photoshop", true, array('msg' => $msg)); } else { if ($file['size'] > 0) { $key = md5_file($file['tmp_name']); $gallery = new Model('gallery'); $img = $gallery->where("`key`='" . $key . "'")->find(); echo JS::import('dialog?skin=brief'); echo JS::import('dialogtools'); if (!$img) { $upfile_path = Tiny::getPath("uploads"); $upfile_url = preg_replace("|^" . APP_URL . "|", '', Tiny::getPath("uploads_url")); $upfile = new UploadFile('upfile', $upfile_path, '10m'); $upfile->save(); $info = $upfile->getInfo(); $result = array(); if ($info[0]['status'] == 1) { $url = $upfile_url . $info[0]['path']; $key = md5_file($upfile_path . $info[0]['path']); $type = Req::args("type") == null ? 0 : intval(Req::args('type')); $gallery->data(array('key' => $key, 'type' => $type, 'img' => $url))->save(); echo "<script>art.dialog.opener.setImg('{$url}');</script>"; } else { $msg = array('error', $info[0]['msg']); $this->msg = $msg; $this->redirect("photoshop", false); } } else { $url = $img['img']; echo "<script>art.dialog.opener.setImg('{$url}');</script>"; } } } } exit; }
/** * 取得对应的错误处理文件 * * @access protected * @param mixed $code * @return mixed */ protected function getViewFile($code) { $viewPaths = array(Tiny::app() == null ? null : Tiny::app()->getLayoutPath(), TINY_ROOT . 'views'); foreach ($viewPaths as $i => $viewPath) { if ($viewPath !== null) { $viewFile = $viewPath . DIRECTORY_SEPARATOR . 'error_' . $code . '.php'; if (is_file($viewFile)) { return $viewFile; } $viewFile = $viewPath . DIRECTORY_SEPARATOR . 'error.php'; if (is_file($viewFile)) { return $viewFile; } } } }
/** * 重新定位 * * @access public * @param string $operator 操作path * @param bool $jump 真假跳转方式 * @param array $args 需要传送的数据 * @return void */ public function redirect($operator = '', $jump = true, $args = array()) { //初始化 $con $act $old_args_num = count($args); $con = $this->getId(); $act = Req::get('act') == null ? $this->defaultAction : Req::get('act'); $controllerId = $con; if (stripos($operator, "http://") === false) { if ($operator != '') { $operator = trim($operator, '/'); $operator = explode('/', $operator); $args_num = count($operator); if ($args_num >= 2) { $con = $operator[0]; //$controllerName = ucfirst($operator[0]).'Controller'; //if(class_exists($controllerName))$controller = new $controllerName($operator[1],$this->module); //else if($con != $this->getId()) $controller = new Controller($operator[1],$this->module); if ($args_num > 2) { for ($i = 2; $i < $args_num; $i = $i + 2) { $args[$operator[$i]] = isset($operator[$i + 1]) ? $operator[$i + 1] : ''; } } $operator = $operator[1]; } else { $operator = $operator[0]; } } else { $operator = $act; } } //如果请求的action 和新的跳转是同一action则进入到对应的视图Action if ($act == $operator && $controllerId == $con) { $this->action = new ViewAction($this, $act); $this->action->setData($args); $this->action->run(); } else { if ($jump == false) { if ($controllerId == $con) { $_GET['act'] = $operator; $this->setDatas($args); $this->run(); } else { $_GET['act'] = $operator; $_GET['con'] = $con; $controller = $this->module->createController(); $controller->setDatas($args); $this->module->setController($controller); $this->module->getController()->run(); } } else { if ($old_args_num != 0 && is_array($args) && !empty($args)) { $args['tiny_token_redirect'] = Tiny::app()->getToken('redirect'); //var_dump($args);exit(); header("Content-type: text/html; charset=" . $this->encoding); $str = '<!doctype html><html lang="zh"><head></head><body>'; if (stripos($operator, "http://") !== false) { $str .= '<form id="hiddenForm" name="hiddenForm" action="' . $operator . '" method="post">'; } else { $str .= '<form id="hiddenForm" name="hiddenForm" action="' . Url::urlFormat('/' . $con . '/' . $operator) . '" method="post">'; } foreach ($args as $key => $value) { if (is_array($value)) { foreach ($value as $k => $v) { $str .= '<input type="hidden" name="' . $key . '[' . $k . ']" value="' . $v . '" />'; } } else { $str .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />'; } } $str .= '</form><script type="text/javascript">document.forms["hiddenForm"].submit();</script></body></html>'; echo $str; exit; } else { $urlargs = ''; if (is_array($args) && !empty($args)) { $urlargs = '?' . http_build_query($args); } header('Location:' . Url::urlFormat('/' . $con . '/' . $operator . $urlargs)); } } } }
<?php /** * Where redirect happens */ require_once "../Library/Tiny.php"; require_once "../Library/functions.php"; require_once "../Library/LogMessage.php"; $url = isset($_GET['url']) ? $_GET['url'] : null; $url = rtrim($url, '/'); $url = explode('/', $url); if (count($url) == 1) { try { $tiny = new Tiny(); $tiny->registerRequest($url[0]); $request = $tiny->getRequestUrl($url[0]); $urlObj = json_decode($request); if ($urlObj->status == 'success') { redirectPage($urlObj->url); } else { redirectPage("error.php"); } } catch (Exception $e) { LogMessage::exception($e->getMessage(), "run.php", "run.php"); redirectPage("404.php"); } } else { redirectPage("error.php"); }
return $HexN; } public static function reverseTiny($str) { $set = self::$set; $radix = strlen($set); $strlen = strlen($str); $N = 0; for ($i = 0; $i < $strlen; $i++) { $N += strpos($set, $str[$i]) * pow($radix, $strlen - $i - 1); } return "{$N}"; } public static function generate_set() { $arr = array(); for ($i = 65; $i <= 122; $i++) { if ($i < 91 || $i > 96) { $arr[] = chr($i); } } $arr = array_merge($arr, range(0, 9)); shuffle($arr); return join('', $arr); } } // Testing echo Tiny::generate_set() . "<br />"; echo Tiny::toTiny(123) . "<br />"; echo Tiny::reverseTiny(Tiny::toTiny(123));