feat: init project codebase

This commit is contained in:
sinde21
2026-09-14 16:32:07 +08:00
parent c4b2a15757
commit da20fde7fb
140 changed files with 27855 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
.arts/*
.codeartsdoer/*
uahpet/cat/*
uahpet/report-data/*
uahpet/report-data_bak/*.idea/
logs/
cache/
+6
View File
@@ -0,0 +1,6 @@
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
+8
View File
@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/application.iml" filepath="$PROJECT_DIR$/.idea/application.iml" />
</modules>
</component>
</project>
Generated
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MessDetectorOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCSFixerOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCodeSnifferOptionsConfiguration">
<option name="highlightLevel" value="WARNING" />
<option name="transferred" value="true" />
</component>
<component name="PhpStanOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PsalmOptionsConfiguration">
<option name="transferred" value="true" />
</component>
</project>
Generated
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/uahpet/database" vcs="Git" />
<mapping directory="$PROJECT_DIR$/uahpet/report-data" vcs="Git" />
<mapping directory="$PROJECT_DIR$/uahpet/report-data_bak" vcs="Git" />
</component>
</project>
+1
View File
@@ -0,0 +1 @@
{"rootHash":"f06c940aa695edb4d76ca57838784edade0b517c6d6d6bc4a14caf20fab19275","timestamp":1789371873112,"fileCount":5,"files":[{"path":"uahpet\\report-data_bak\\Feline\\convert.bak.py","hash":"1d470c56718115a869ce9d330ff997f525858d6ee87d0c55fdc4005b9ab627cc","size":2958,"modified":1789371596769.8796},{"path":"uahpet\\report-data_bak\\Feline\\convert.py","hash":"f47c56a14584481f2c06cdca9bdb088a431e571c8b0cf9696be5ab32e82c9125","size":3448,"modified":1789371596769.8796},{"path":"uahpet\\report-data\\Feline\\convert.bak.py","hash":"1d470c56718115a869ce9d330ff997f525858d6ee87d0c55fdc4005b9ab627cc","size":2958,"modified":1789371588699.2039},{"path":"uahpet\\report-data\\Feline\\convert.py","hash":"f47c56a14584481f2c06cdca9bdb088a431e571c8b0cf9696be5ab32e82c9125","size":3448,"modified":1789371588699.2039},{"path":"uahpet\\report-data\\Feline\\convert.sh","hash":"ee842dea3a9be975cba4cc500eba27a01e9d33d12db7ef2100ec516c35a2c4a7","size":420,"modified":1789371588699.2039}]}
+138
View File
@@ -0,0 +1,138 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| AUTO-LOADER
| -------------------------------------------------------------------
| This file specifies which systems should be loaded by default.
|
| In order to keep the framework as light-weight as possible only the
| absolute minimal resources are loaded by default. For example,
| the database is not connected to automatically since no assumption
| is made regarding whether you intend to use it. This file lets
| you globally define which systems you would like loaded with every
| request.
|
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Drivers
| 4. Helper files
| 5. Custom config files
| 6. Language files
| 7. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packages
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in system/libraries/ or your
| application/libraries/ directory, with the addition of the
| 'database' library, which is somewhat of a special case.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'email', 'session');
|
| You can also supply an alternative library name to be assigned
| in the controller:
|
| $autoload['libraries'] = array('user_agent' => 'ua');
*/
//$autoload['libraries'] = array();
// 'session' 启用 $_SESSION功能
$autoload['libraries'] = array('Permission');
/*
| -------------------------------------------------------------------
| Auto-load Drivers
| -------------------------------------------------------------------
| These classes are located in system/libraries/ or in your
| application/libraries/ directory, but are also placed inside their
| own subdirectory and they extend the CI_Driver_Library class. They
| offer multiple interchangeable driver options.
|
| Prototype:
|
| $autoload['drivers'] = array('cache');
|
| You can also supply an alternative property name to be assigned in
| the controller:
|
| $autoload['drivers'] = array('cache' => 'cch');
|
*/
$autoload['drivers'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array('url');
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();
+609
View File
@@ -0,0 +1,609 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| WARNING: You MUST set this value!
|
| If it is not set, then CodeIgniter will try guess the protocol and path
| your installation, but due to security concerns the hostname will be set
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = 'https://api.uahpet.com/';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = 'index.php';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
$config['uri_protocol'] = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| https://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| https://codeigniter.com/user_guide/general/core_classes.html
| https://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Composer auto-loading
|--------------------------------------------------------------------------
|
| Enabling this setting will tell CodeIgniter to look for a Composer
| package auto-loader script in application/vendor/autoload.php.
|
| $config['composer_autoload'] = TRUE;
|
| Or if you have your vendor/ directory located somewhere else, you
| can opt to set a specific path as well:
|
| $config['composer_autoload'] = '/path/to/vendor/autoload.php';
|
| For more information about Composer, please visit http://getcomposer.org/
|
| Note: This will NOT disable or override the CodeIgniter-specific
| autoloading (application/config/autoload.php)
*/
//$config['composer_autoload'] = FALSE;
$config['composer_autoload'] = 'vendor/autoload.php'; // 项目根目录下 vendor/autoload.php
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/*
|--------------------------------------------------------------------------
| Allow $_GET array
|--------------------------------------------------------------------------
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['allow_get_array'] = TRUE;
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 1;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ directory. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Log File Extension
|--------------------------------------------------------------------------
|
| The default filename extension for log files. The default 'php' allows for
| protecting the log files via basic scripting, when they are to be stored
| under a publicly accessible directory.
|
| Note: Leaving it blank will default to 'php'.
|
*/
$config['log_file_extension'] = '';
/*
|--------------------------------------------------------------------------
| Log File Permissions
|--------------------------------------------------------------------------
|
| The file system permissions to be applied on newly created log files.
|
| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
| integer notation (i.e. 0700, 0644, etc.)
*/
$config['log_file_permissions'] = 0644;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Error Views Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/views/errors/ directory. Use a full server path with trailing slash.
|
*/
$config['error_views_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/cache/ directory. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Whether to take the URL query string into consideration when generating
| output cache files. Valid options are:
|
| FALSE = Disabled
| TRUE = Enabled, take all query parameters into account.
| Please be aware that this may result in numerous cache
| files generated for the same page over and over again.
| array('q') = Enabled, but only take into account the specified list
| of query parameters.
|
*/
$config['cache_query_string'] = FALSE;
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class, you must set an encryption key.
| See the user guide for more info.
|
| https://codeigniter.com/user_guide/libraries/encryption.html
|
*/
$config['encryption_key'] = '';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_driver'
|
| The storage driver to use: files, database, redis, memcached
|
| 'sess_cookie_name'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sess_expiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sess_save_path'
|
| The location to save sessions to, driver dependent.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sess_match_ip'
|
| Whether to match the user's IP address when reading the session data.
|
| WARNING: If you're using the database driver, don't forget to update
| your session table's PRIMARY KEY when changing this setting.
|
| 'sess_time_to_update'
|
| How many seconds between CI regenerating the session ID.
|
| 'sess_regenerate_destroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
/*
|--------------------------------------------------------------------------
| Standardize newlines
|--------------------------------------------------------------------------
|
| Determines whether to standardize newline characters in input data,
| meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value.
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['standardize_newlines'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| Only used if zlib.output_compression is turned off in your php.ini.
| Please do not use it together with httpd-level output compression.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
| Note: You need to have eval() enabled for this to work.
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
// JWT 自定义配置
$config['jwt_key'] = 'pocoyo';
$config['jwt_access_token_exp'] = 7200; // 单位秒
$config['jwt_refresh_token_exp'] = 604800; // 单位秒
$config['jwt_refresh_count'] = 7; // 调用refresh_token接口超过此次数时, 会重置刷新token过期时间
$config['jwt_api_prefix'] = 'api/v2';
// 白名单里的uri不认证
$config['jwt_white_list'] = [
'/sys/user/login',
'/sys/user/logout',
'/sys/user/refreshtoken', // 刷新token接口需要在控制器内作权限验证,比较特殊
// 下面接口uri 可以在菜单权限里面添加,再分配给对应角色即可, 方便/安全?
// 如果不想在前端菜单里添加,也可以直接在后端在控制器里单独做token验证,不用做权限认证
// 参考/sys/user/refreshtoken
'/sys/user/info',
'/sys/user/list',
'/sys/user/getroleoptions',
'/sys/role/allroles',
'/sys/role/allmenus',
'/sys/role/rolemenu',
'/sys/role/rolerole',
'/sys/menu/treeoptions'
];
// 自定义jwt token 过期或异常返回值,根据前端需要可以分开
// SignatureInvalidException 签名不正确
// BeforeValidException签名在某个时间点之后才能用
// ExpiredException token过期
// Exception 其他错误
$config['jwt_token_expired'] = ["code" => 50014, "message" => "Token 过期了oo"];
$config['jwt_token_exception'] = ['code' => 50008, 'message' => "非法的token"];
/*
|--------------------------------------------------------------------------
| 微信公众号配置
|--------------------------------------------------------------------------
*/
//精准宠爱
//define('WEIXIN_APPID','wx2527f37a99f36591');
//define('WEIXIN_APPSECERT','1fa0a4f1866a270fccbc3b5c9bccf2ab');
//深知生物
//define('WEIXIN_APPID','wx5d49b7f2f3f0b364');
//define('WEIXIN_APPSECERT','f4980e8e790986aa9b04445b56111276');
//有哈公众号
$config['weixin_uah'] = [
'AppId'=>'wx68a9516b40596f7c',
'AppSecert'=>'617bb0abbe9988198a4be7e79f6ec877',
'Token'=>'rpR69GDeKO5Ap37aojeEieTv6CXdn6zR',
'EncodingAESKey'=>'tgmB5BG6EdVxudQkI9tuCQrPhjDvb50nMCsgCHBtD2J',
//微信支付
'mch_id'=>'1575062461',//微信支付商户号
'pay_api_key'=>'6410724d88504fac0e2e0ac49f40da4e',//微信支付密钥
'pay_api_key_v3'=>'9a99c6046a960c1d572b4c198532a132',//微信支付密钥v3
'pay_cert_path'=>APPPATH.'cert/apiclient_cert.pem',//证书
'pay_key_path'=>APPPATH.'cert/apiclient_key.pem',//证书密钥
];
//有哈小程序后端服务token
$config['uah_server_token'] = '0d5b7617-890f-ff07-1e57-a3e4ab91ca39';
/*
|--------------------------------------------------------------------------
| 中通快递配置 https://zop.zto.com/consoleBoard/home
|--------------------------------------------------------------------------
*/
$config['zto'] = [
'id'=>'70720bf074944864923a13debd69b50a',
'key'=>'aace38d17062',
'host'=>'http://japi.zto.cn/'
];
/*
|--------------------------------------------------------------------------
| 顺风快递配置 https://qiao.sf-express.com/pages/developDoc/index.html?level2=194867
|--------------------------------------------------------------------------
*/
$config['sf-express'] = [
'clientCode'=>'YHKJ_HQJYM',
'checkword'=>'HSJPtAvNanJlUHaK4y6nr5ldjiw8C8Te',
'custid'=>'7550176107',//月结卡号:测试卡号7551234567
];
+85
View File
@@ -0,0 +1,85 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Display Debug backtrace
|--------------------------------------------------------------------------
|
| If set to TRUE, a backtrace will be displayed along with php errors. If
| error_reporting is disabled, the backtrace will not display, regardless
| of this setting
|
*/
defined('SHOW_DEBUG_BACKTRACE') OR define('SHOW_DEBUG_BACKTRACE', TRUE);
/*
|--------------------------------------------------------------------------
| File and Directory Modes
|--------------------------------------------------------------------------
|
| These prefs are used when checking and setting modes when working
| with the file system. The defaults are fine on servers with proper
| security, but you may wish (or even need) to change the values in
| certain environments (Apache running a separate process for each
| user, PHP under CGI with Apache suEXEC, etc.). Octal values should
| always be used to set the mode correctly.
|
*/
defined('FILE_READ_MODE') OR define('FILE_READ_MODE', 0644);
defined('FILE_WRITE_MODE') OR define('FILE_WRITE_MODE', 0666);
defined('DIR_READ_MODE') OR define('DIR_READ_MODE', 0755);
defined('DIR_WRITE_MODE') OR define('DIR_WRITE_MODE', 0755);
/*
|--------------------------------------------------------------------------
| File Stream Modes
|--------------------------------------------------------------------------
|
| These modes are used when working with fopen()/popen()
|
*/
defined('FOPEN_READ') OR define('FOPEN_READ', 'rb');
defined('FOPEN_READ_WRITE') OR define('FOPEN_READ_WRITE', 'r+b');
defined('FOPEN_WRITE_CREATE_DESTRUCTIVE') OR define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care
defined('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE') OR define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care
defined('FOPEN_WRITE_CREATE') OR define('FOPEN_WRITE_CREATE', 'ab');
defined('FOPEN_READ_WRITE_CREATE') OR define('FOPEN_READ_WRITE_CREATE', 'a+b');
defined('FOPEN_WRITE_CREATE_STRICT') OR define('FOPEN_WRITE_CREATE_STRICT', 'xb');
defined('FOPEN_READ_WRITE_CREATE_STRICT') OR define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b');
/*
|--------------------------------------------------------------------------
| Exit Status Codes
|--------------------------------------------------------------------------
|
| Used to indicate the conditions under which the script is exit()ing.
| While there is no universal standard for error codes, there are some
| broad conventions. Three such conventions are mentioned below, for
| those who wish to make use of them. The CodeIgniter defaults were
| chosen for the least overlap with these conventions, while still
| leaving room for others to be defined in future versions and user
| applications.
|
| The three main conventions used for determining exit status codes
| are as follows:
|
| Standard C/C++ Library (stdlibc):
| http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
| (This link also contains other GNU-specific conventions)
| BSD sysexits.h:
| http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
| Bash scripting:
| http://tldp.org/LDP/abs/html/exitcodes.html
|
*/
defined('EXIT_SUCCESS') OR define('EXIT_SUCCESS', 0); // no errors
defined('EXIT_ERROR') OR define('EXIT_ERROR', 1); // generic error
defined('EXIT_CONFIG') OR define('EXIT_CONFIG', 3); // configuration error
defined('EXIT_UNKNOWN_FILE') OR define('EXIT_UNKNOWN_FILE', 4); // file not found
defined('EXIT_UNKNOWN_CLASS') OR define('EXIT_UNKNOWN_CLASS', 5); // unknown class
defined('EXIT_UNKNOWN_METHOD') OR define('EXIT_UNKNOWN_METHOD', 6); // unknown class member
defined('EXIT_USER_INPUT') OR define('EXIT_USER_INPUT', 7); // invalid user input
defined('EXIT_DATABASE') OR define('EXIT_DATABASE', 8); // database error
defined('EXIT__AUTO_MIN') OR define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code
defined('EXIT__AUTO_MAX') OR define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code
+96
View File
@@ -0,0 +1,96 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['dsn'] The full DSN string describe a connection to the database.
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database driver. e.g.: mysqli.
| Currently supported:
| cubrid, ibase, mssql, mysql, mysqli, oci8,
| odbc, pdo, postgre, sqlite, sqlite3, sqlsrv
| ['dbprefix'] You can add an optional prefix, which will be added
| to the table name when using the Query Builder class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
| NOTE: For MySQL and MySQLi databases, this setting is only used
| as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
| (and in table creation queries made with DB Forge).
| There is an incompatibility in PHP with mysql_real_escape_string() which
| can make your site vulnerable to SQL injection if you are using a
| multi-byte character set and are running versions lower than these.
| Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
| ['swap_pre'] A default table prefix that should be swapped with the dbprefix
| ['encrypt'] Whether or not to use an encrypted connection.
|
| 'mysql' (deprecated), 'sqlsrv' and 'pdo/sqlsrv' drivers accept TRUE/FALSE
| 'mysqli' and 'pdo/mysql' drivers accept an array with the following options:
|
| 'ssl_key' - Path to the private key file
| 'ssl_cert' - Path to the public key certificate file
| 'ssl_ca' - Path to the certificate authority file
| 'ssl_capath' - Path to a directory containing trusted CA certificates in PEM format
| 'ssl_cipher' - List of *allowed* ciphers to be used for the encryption, separated by colons (':')
| 'ssl_verify' - TRUE/FALSE; Whether verify the server certificate or not
|
| ['compress'] Whether or not to use client compression (MySQL only)
| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
| - good for ensuring strict SQL while developing
| ['ssl_options'] Used to set various SSL options that can be used when making SSL connections.
| ['failover'] array - A array with 0 or more data for connections if the main should fail.
| ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries.
| NOTE: Disabling this will also effectively disable both
| $this->db->last_query() and profiling of DB queries.
| When you run a query, with this setting set to TRUE (default),
| CodeIgniter will store the SQL statement for debugging purposes.
| However, this may cause high memory usage, especially if you run
| a lot of SQL queries ... disable this to avoid that problem.
|
| The $active_group variable lets you choose which connection group to
| make active. By default there is only one group (the 'default' group).
|
| The $query_builder variables lets you determine whether or not to load
| the query builder class.
*/
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'dna',
'password' => 'wSFH4T47VAHpSpfS',
'database' => 'dna',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
+13
View File
@@ -0,0 +1,13 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| 中通快递配置 https://zop.zto.com/consoleBoard/home
|--------------------------------------------------------------------------
*/
$config['zto'] = [
'id'=>'kfpttestCode',
'key'=>'kfpttestkey==',
'host'=>'http://58.40.16.122:8080/'
//'host'=>'http://58.40.16.120:9001/'
];
+24
View File
@@ -0,0 +1,24 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$_doctypes = array(
'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'xhtml-basic11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
'mathml1' => '<!DOCTYPE math SYSTEM "http://www.w3.org/Math/DTD/mathml1/mathml.dtd">',
'mathml2' => '<!DOCTYPE math PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">',
'svg10' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">',
'svg11' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',
'svg11-basic' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Basic//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd">',
'svg11-tiny' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">',
'xhtml-math-svg-xh' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-math-svg-sh' => '<!DOCTYPE svg:svg PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-rdfa-1' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">',
'xhtml-rdfa-2' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.1//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd">'
);
+103
View File
@@ -0,0 +1,103 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| Foreign Characters
| -------------------------------------------------------------------
| This file contains an array of foreign characters for transliteration
| conversion used by the Text helper
|
*/
$foreign_characters = array(
'/ä|æ|ǽ/' => 'ae',
'/ö|œ/' => 'oe',
'/ü/' => 'ue',
'/Ä/' => 'Ae',
'/Ü/' => 'Ue',
'/Ö/' => 'Oe',
'/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ|Α|Ά|Ả|Ạ|Ầ|Ẫ|Ẩ|Ậ|Ằ|Ắ|Ẵ|Ẳ|Ặ|А/' => 'A',
'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª|α|ά|ả|ạ|ầ|ấ|ẫ|ẩ|ậ|ằ|ắ|ẵ|ẳ|ặ|а/' => 'a',
'/Б/' => 'B',
'/б/' => 'b',
'/Ç|Ć|Ĉ|Ċ|Č/' => 'C',
'/ç|ć|ĉ|ċ|č/' => 'c',
'/Д/' => 'D',
'/д/' => 'd',
'/Ð|Ď|Đ|Δ/' => 'Dj',
'/ð|ď|đ|δ/' => 'dj',
'/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě|Ε|Έ|Ẽ|Ẻ|Ẹ|Ề|Ế|Ễ|Ể|Ệ|Е|Э/' => 'E',
'/è|é|ê|ë|ē|ĕ|ė|ę|ě|έ|ε|ẽ|ẻ|ẹ|ề|ế|ễ|ể|ệ|е|э/' => 'e',
'/Ф/' => 'F',
'/ф/' => 'f',
'/Ĝ|Ğ|Ġ|Ģ|Γ|Г|Ґ/' => 'G',
'/ĝ|ğ|ġ|ģ|γ|г|ґ/' => 'g',
'/Ĥ|Ħ/' => 'H',
'/ĥ|ħ/' => 'h',
'/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ|Η|Ή|Ί|Ι|Ϊ|Ỉ|Ị|И|Ы/' => 'I',
'/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı|η|ή|ί|ι|ϊ|ỉ|ị|и|ы|ї/' => 'i',
'/Ĵ/' => 'J',
'/ĵ/' => 'j',
'/Ķ|Κ|К/' => 'K',
'/ķ|κ|к/' => 'k',
'/Ĺ|Ļ|Ľ|Ŀ|Ł|Λ|Л/' => 'L',
'/ĺ|ļ|ľ|ŀ|ł|λ|л/' => 'l',
'/М/' => 'M',
'/м/' => 'm',
'/Ñ|Ń|Ņ|Ň|Ν|Н/' => 'N',
'/ñ|ń|ņ|ň|ʼn|ν|н/' => 'n',
'/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ|Ο|Ό|Ω|Ώ|Ỏ|Ọ|Ồ|Ố|Ỗ|Ổ|Ộ|Ờ|Ớ|Ỡ|Ở|Ợ|О/' => 'O',
'/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º|ο|ό|ω|ώ|ỏ|ọ|ồ|ố|ỗ|ổ|ộ|ờ|ớ|ỡ|ở|ợ|о/' => 'o',
'/П/' => 'P',
'/п/' => 'p',
'/Ŕ|Ŗ|Ř|Ρ|Р/' => 'R',
'/ŕ|ŗ|ř|ρ|р/' => 'r',
'/Ś|Ŝ|Ş|Ș|Š|Σ|С/' => 'S',
'/ś|ŝ|ş|ș|š|ſ|σ|ς|с/' => 's',
'/Ț|Ţ|Ť|Ŧ|τ|Т/' => 'T',
'/ț|ţ|ť|ŧ|т/' => 't',
'/Þ|þ/' => 'th',
'/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ|Ũ|Ủ|Ụ|Ừ|Ứ|Ữ|Ử|Ự|У/' => 'U',
'/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ|υ|ύ|ϋ|ủ|ụ|ừ|ứ|ữ|ử|ự|у/' => 'u',
'/Ƴ|Ɏ|Ỵ|Ẏ|Ӳ|Ӯ|Ў|Ý|Ÿ|Ŷ|Υ|Ύ|Ϋ|Ỳ|Ỹ|Ỷ|Ỵ|Й/' => 'Y',
'/ẙ|ʏ|ƴ|ɏ|ỵ|ẏ|ӳ|ӯ|ў|ý|ÿ|ŷ|ỳ|ỹ|ỷ|ỵ|й/' => 'y',
'/В/' => 'V',
'/в/' => 'v',
'/Ŵ/' => 'W',
'/ŵ/' => 'w',
'/Ź|Ż|Ž|Ζ|З/' => 'Z',
'/ź|ż|ž|ζ|з/' => 'z',
'/Æ|Ǽ/' => 'AE',
'/ß/' => 'ss',
'/IJ/' => 'IJ',
'/ij/' => 'ij',
'/Œ/' => 'OE',
'/ƒ/' => 'f',
'/ξ/' => 'ks',
'/π/' => 'p',
'/β/' => 'v',
'/μ/' => 'm',
'/ψ/' => 'ps',
'/Ё/' => 'Yo',
'/ё/' => 'yo',
'/Є/' => 'Ye',
'/є/' => 'ye',
'/Ї/' => 'Yi',
'/Ж/' => 'Zh',
'/ж/' => 'zh',
'/Х/' => 'Kh',
'/х/' => 'kh',
'/Ц/' => 'Ts',
'/ц/' => 'ts',
'/Ч/' => 'Ch',
'/ч/' => 'ch',
'/Ш/' => 'Sh',
'/ш/' => 'sh',
'/Щ/' => 'Shch',
'/щ/' => 'shch',
'/Ъ|ъ|Ь|ь/' => '',
'/Ю/' => 'Yu',
'/ю/' => 'yu',
'/Я/' => 'Ya',
'/я/' => 'ya'
);
+20
View File
@@ -0,0 +1,20 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files. Please see the user guide for info:
|
| https://codeigniter.com/user_guide/general/hooks.html
|
*/
$hook['post_controller_constructor'][] = array(
'class' => 'ManageAuth', //类名
'function' => 'auth', //执行的方法
'filename' => 'ManageAuth.php', //文件名
'filepath' => 'hooks' //文件路径,默认是application/hooks
);
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+19
View File
@@ -0,0 +1,19 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Memcached settings
| -------------------------------------------------------------------------
| Your Memcached servers can be specified below.
|
| See: https://codeigniter.com/user_guide/libraries/caching.html#memcached
|
*/
$config = array(
'default' => array(
'hostname' => '127.0.0.1',
'port' => '11211',
'weight' => '1',
),
);
+84
View File
@@ -0,0 +1,84 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Enable/Disable Migrations
|--------------------------------------------------------------------------
|
| Migrations are disabled by default for security reasons.
| You should enable migrations whenever you intend to do a schema migration
| and disable it back when you're done.
|
*/
$config['migration_enabled'] = FALSE;
/*
|--------------------------------------------------------------------------
| Migration Type
|--------------------------------------------------------------------------
|
| Migration file names may be based on a sequential identifier or on
| a timestamp. Options are:
|
| 'sequential' = Sequential migration naming (001_add_blog.php)
| 'timestamp' = Timestamp migration naming (20121031104401_add_blog.php)
| Use timestamp format YYYYMMDDHHIISS.
|
| Note: If this configuration value is missing the Migration library
| defaults to 'sequential' for backward compatibility with CI2.
|
*/
$config['migration_type'] = 'timestamp';
/*
|--------------------------------------------------------------------------
| Migrations table
|--------------------------------------------------------------------------
|
| This is the name of the table that will store the current migrations state.
| When migrations runs it will store in a database table which migration
| level the system is at. It then compares the migration level in this
| table to the $config['migration_version'] if they are not the same it
| will migrate up. This must be set.
|
*/
$config['migration_table'] = 'migrations';
/*
|--------------------------------------------------------------------------
| Auto Migrate To Latest
|--------------------------------------------------------------------------
|
| If this is set to TRUE when you load the migrations class and have
| $config['migration_enabled'] set to TRUE the system will auto migrate
| to your latest migration (whatever $config['migration_version'] is
| set to). This way you do not have to call migrations anywhere else
| in your code to have the latest migration.
|
*/
$config['migration_auto_latest'] = FALSE;
/*
|--------------------------------------------------------------------------
| Migrations version
|--------------------------------------------------------------------------
|
| This is used to set migration version that the file system should be on.
| If you run $this->migration->current() this is the version that schema will
| be upgraded / downgraded to.
|
*/
$config['migration_version'] = 0;
/*
|--------------------------------------------------------------------------
| Migrations Path
|--------------------------------------------------------------------------
|
| Path to your migrations folder.
| Typically, it will be within your application path.
| Also, writing permission is required within the migrations path.
|
*/
$config['migration_path'] = APPPATH.'migrations/';
+184
View File
@@ -0,0 +1,184 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| MIME TYPES
| -------------------------------------------------------------------
| This file contains an array of mime types. It is used by the
| Upload class to help identify allowed file types.
|
*/
return array(
'hqx' => array('application/mac-binhex40', 'application/mac-binhex', 'application/x-binhex40', 'application/x-mac-binhex40'),
'cpt' => 'application/mac-compactpro',
'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain'),
'bin' => array('application/macbinary', 'application/mac-binary', 'application/octet-stream', 'application/x-binary', 'application/x-macbinary'),
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => array('application/octet-stream', 'application/x-msdownload'),
'class' => 'application/octet-stream',
'psd' => array('application/x-photoshop', 'image/vnd.adobe.photoshop'),
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => array('application/pdf', 'application/force-download', 'application/x-download', 'binary/octet-stream'),
'ai' => array('application/pdf', 'application/postscript'),
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => array('application/vnd.ms-excel', 'application/msexcel', 'application/x-msexcel', 'application/x-ms-excel', 'application/x-excel', 'application/x-dos_ms_excel', 'application/xls', 'application/x-xls', 'application/excel', 'application/download', 'application/vnd.ms-office', 'application/msword'),
'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint', 'application/vnd.ms-office', 'application/msword'),
'pptx' => array('application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/x-zip', 'application/zip'),
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'gzip' => 'application/x-gzip',
'php' => array('application/x-httpd-php', 'application/php', 'application/x-php', 'text/php', 'text/x-php', 'application/x-httpd-php-source'),
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => array('application/x-javascript', 'text/plain'),
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => array('application/x-tar', 'application/x-gzip-compressed'),
'z' => 'application/x-compress',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed', 'application/s-compressed', 'multipart/x-zip'),
'rar' => array('application/x-rar', 'application/rar', 'application/x-rar-compressed'),
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'),
'aif' => array('audio/x-aiff', 'audio/aiff'),
'aiff' => array('audio/x-aiff', 'audio/aiff'),
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => array('audio/x-wav', 'audio/wave', 'audio/wav'),
'bmp' => array('image/bmp', 'image/x-bmp', 'image/x-bitmap', 'image/x-xbitmap', 'image/x-win-bitmap', 'image/x-windows-bmp', 'image/ms-bmp', 'image/x-ms-bmp', 'application/bmp', 'application/x-bmp', 'application/x-win-bitmap'),
'gif' => 'image/gif',
'jpeg' => array('image/jpeg', 'image/pjpeg'),
'jpg' => array('image/jpeg', 'image/pjpeg'),
'jpe' => array('image/jpeg', 'image/pjpeg'),
'jp2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'j2k' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'jpf' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'jpg2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'jpx' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'jpm' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'mj2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'mjp2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'png' => array('image/png', 'image/x-png'),
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'css' => array('text/css', 'text/plain'),
'html' => array('text/html', 'text/plain'),
'htm' => array('text/html', 'text/plain'),
'shtml' => array('text/html', 'text/plain'),
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => array('text/plain', 'text/x-log'),
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => array('application/xml', 'text/xml', 'text/plain'),
'xsl' => array('application/xml', 'text/xsl', 'text/xml'),
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => array('video/x-msvideo', 'video/msvideo', 'video/avi', 'application/x-troff-msvideo'),
'movie' => 'video/x-sgi-movie',
'doc' => array('application/msword', 'application/vnd.ms-office'),
'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword', 'application/x-zip'),
'dot' => array('application/msword', 'application/vnd.ms-office'),
'dotx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword'),
'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/vnd.ms-excel', 'application/msword', 'application/x-zip'),
'word' => array('application/msword', 'application/octet-stream'),
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => array('application/json', 'text/json'),
'pem' => array('application/x-x509-user-cert', 'application/x-pem-file', 'application/octet-stream'),
'p10' => array('application/x-pkcs10', 'application/pkcs10'),
'p12' => 'application/x-pkcs12',
'p7a' => 'application/x-pkcs7-signature',
'p7c' => array('application/pkcs7-mime', 'application/x-pkcs7-mime'),
'p7m' => array('application/pkcs7-mime', 'application/x-pkcs7-mime'),
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'crt' => array('application/x-x509-ca-cert', 'application/x-x509-user-cert', 'application/pkix-cert'),
'crl' => array('application/pkix-crl', 'application/pkcs-crl'),
'der' => 'application/x-x509-ca-cert',
'kdb' => 'application/octet-stream',
'pgp' => 'application/pgp',
'gpg' => 'application/gpg-keys',
'sst' => 'application/octet-stream',
'csr' => 'application/octet-stream',
'rsa' => 'application/x-pkcs7',
'cer' => array('application/pkix-cert', 'application/x-x509-ca-cert'),
'3g2' => 'video/3gpp2',
'3gp' => array('video/3gp', 'video/3gpp'),
'mp4' => 'video/mp4',
'm4a' => 'audio/x-m4a',
'f4v' => array('video/mp4', 'video/x-f4v'),
'flv' => 'video/x-flv',
'webm' => 'video/webm',
'aac' => 'audio/x-acc',
'm4u' => 'application/vnd.mpegurl',
'm3u' => 'text/plain',
'xspf' => 'application/xspf+xml',
'vlc' => 'application/videolan',
'wmv' => array('video/x-ms-wmv', 'video/x-ms-asf'),
'au' => 'audio/x-au',
'ac3' => 'audio/ac3',
'flac' => 'audio/x-flac',
'ogg' => array('audio/ogg', 'video/ogg', 'application/ogg'),
'kmz' => array('application/vnd.google-earth.kmz', 'application/zip', 'application/x-zip'),
'kml' => array('application/vnd.google-earth.kml+xml', 'application/xml', 'text/xml'),
'ics' => 'text/calendar',
'ical' => 'text/calendar',
'zsh' => 'text/x-scriptzsh',
'7z' => array('application/x-7z-compressed', 'application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'),
'7zip' => array('application/x-7z-compressed', 'application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'),
'cdr' => array('application/cdr', 'application/coreldraw', 'application/x-cdr', 'application/x-coreldraw', 'image/cdr', 'image/x-cdr', 'zz-application/zz-winassoc-cdr'),
'wma' => array('audio/x-ms-wma', 'video/x-ms-asf'),
'jar' => array('application/java-archive', 'application/x-java-application', 'application/x-jar', 'application/x-compressed'),
'svg' => array('image/svg+xml', 'application/xml', 'text/xml'),
'vcf' => 'text/x-vcard',
'srt' => array('text/srt', 'text/plain'),
'vtt' => array('text/vtt', 'text/plain'),
'ico' => array('image/x-icon', 'image/x-ico', 'image/vnd.microsoft.icon'),
'odc' => 'application/vnd.oasis.opendocument.chart',
'otc' => 'application/vnd.oasis.opendocument.chart-template',
'odf' => 'application/vnd.oasis.opendocument.formula',
'otf' => 'application/vnd.oasis.opendocument.formula-template',
'odg' => 'application/vnd.oasis.opendocument.graphics',
'otg' => 'application/vnd.oasis.opendocument.graphics-template',
'odi' => 'application/vnd.oasis.opendocument.image',
'oti' => 'application/vnd.oasis.opendocument.image-template',
'odp' => 'application/vnd.oasis.opendocument.presentation',
'otp' => 'application/vnd.oasis.opendocument.presentation-template',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
'odt' => 'application/vnd.oasis.opendocument.text',
'odm' => 'application/vnd.oasis.opendocument.text-master',
'ott' => 'application/vnd.oasis.opendocument.text-template',
'oth' => 'application/vnd.oasis.opendocument.text-web'
);
+14
View File
@@ -0,0 +1,14 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Profiler Sections
| -------------------------------------------------------------------------
| This file lets you determine whether or not various sections of Profiler
| data are displayed when the Profiler is enabled.
| Please see the user guide for info:
|
| https://codeigniter.com/user_guide/general/profiling.html
|
*/
+6
View File
@@ -0,0 +1,6 @@
<?php
$config['host'] = 'localhost';
$config['password'] = NULL;
$config['port'] = 6379;
$config['timeout'] = 0;
+647
View File
@@ -0,0 +1,647 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| HTTP protocol
|--------------------------------------------------------------------------
|
| Set to force the use of HTTPS for REST API calls
|
*/
$config['force_https'] = false;
/*
|--------------------------------------------------------------------------
| REST Output Format
|--------------------------------------------------------------------------
|
| The default format of the response
|
| 'array': Array data structure
| 'csv': Comma separated file
| 'json': Uses json_encode(). Note: If a GET query string
| called 'callback' is passed, then jsonp will be returned
| 'html' HTML using the table library in CodeIgniter
| 'php': Uses var_export()
| 'serialized': Uses serialize()
| 'xml': Uses simplexml_load_string()
|
*/
$config['rest_default_format'] = 'json';
/*
|--------------------------------------------------------------------------
| REST Supported Output Formats
|--------------------------------------------------------------------------
|
| The following setting contains a list of the supported/allowed formats.
| You may remove those formats that you don't want to use.
| If the default format $config['rest_default_format'] is missing within
| $config['rest_supported_formats'], it will be added silently during
| REST_Controller initialization.
|
*/
$config['rest_supported_formats'] = [
'json',
'array',
'csv',
'html',
'jsonp',
'php',
'serialized',
'xml',
];
/*
|--------------------------------------------------------------------------
| REST Status Field Name
|--------------------------------------------------------------------------
|
| The field name for the status inside the response
|
*/
$config['rest_status_field_name'] = 'status';
/*
|--------------------------------------------------------------------------
| REST Message Field Name
|--------------------------------------------------------------------------
|
| The field name for the message inside the response
|
*/
$config['rest_message_field_name'] = 'error';
/*
|--------------------------------------------------------------------------
| Enable Emulate Request
|--------------------------------------------------------------------------
|
| Should we enable emulation of the request (e.g. used in Mootools request)
|
*/
$config['enable_emulate_request'] = true;
/*
|--------------------------------------------------------------------------
| REST Realm
|--------------------------------------------------------------------------
|
| Name of the password protected REST API displayed on login dialogs
|
| e.g: My Secret REST API
|
*/
$config['rest_realm'] = 'REST API';
/*
|--------------------------------------------------------------------------
| REST Login
|--------------------------------------------------------------------------
|
| Set to specify the REST API requires to be logged in
|
| FALSE No login required
| 'basic' Unsecured login
| 'digest' More secured login
| 'session' Check for a PHP session variable. See 'auth_source' to set the
| authorization key
|
*/
$config['rest_auth'] = false;
/*
|--------------------------------------------------------------------------
| REST Login Source
|--------------------------------------------------------------------------
|
| Is login required and if so, the user store to use
|
| '' Use config based users or wildcard testing
| 'ldap' Use LDAP authentication
| 'library' Use a authentication library
|
| Note: If 'rest_auth' is set to 'session' then change 'auth_source' to the name of the session variable
|
*/
$config['auth_source'] = 'ldap';
/*
|--------------------------------------------------------------------------
| Allow Authentication and API Keys
|--------------------------------------------------------------------------
|
| Where you wish to have Basic, Digest or Session login, but also want to use API Keys (for limiting
| requests etc), set to TRUE;
|
*/
$config['allow_auth_and_keys'] = true;
$config['strict_api_and_auth'] = true; // force the use of both api and auth before a valid api request is made
/*
|--------------------------------------------------------------------------
| REST Login Class and Function
|--------------------------------------------------------------------------
|
| If library authentication is used define the class and function name
|
| The function should accept two parameters: class->function($username, $password)
| In other cases override the function _perform_library_auth in your controller
|
| For digest authentication the library function should return already a stored
| md5(username:restrealm:password) for that username
|
| e.g: md5('admin:REST API:1234') = '1e957ebc35631ab22d5bd6526bd14ea2'
|
*/
$config['auth_library_class'] = '';
$config['auth_library_function'] = '';
/*
|--------------------------------------------------------------------------
| Override auth types for specific class/method
|--------------------------------------------------------------------------
|
| Set specific authentication types for methods within a class (controller)
|
| Set as many config entries as needed. Any methods not set will use the default 'rest_auth' config value.
|
| e.g:
|
| $config['auth_override_class_method']['deals']['view'] = 'none';
| $config['auth_override_class_method']['deals']['insert'] = 'digest';
| $config['auth_override_class_method']['accounts']['user'] = 'basic';
| $config['auth_override_class_method']['dashboard']['*'] = 'none|digest|basic';
|
| Here 'deals', 'accounts' and 'dashboard' are controller names, 'view', 'insert' and 'user' are methods within. An asterisk may also be used to specify an authentication method for an entire classes methods. Ex: $config['auth_override_class_method']['dashboard']['*'] = 'basic'; (NOTE: leave off the '_get' or '_post' from the end of the method name)
| Acceptable values are; 'none', 'digest' and 'basic'.
|
*/
// $config['auth_override_class_method']['deals']['view'] = 'none';
// $config['auth_override_class_method']['deals']['insert'] = 'digest';
// $config['auth_override_class_method']['accounts']['user'] = 'basic';
// $config['auth_override_class_method']['dashboard']['*'] = 'basic';
// ---Uncomment list line for the wildard unit test
// $config['auth_override_class_method']['wildcard_test_cases']['*'] = 'basic';
/*
|--------------------------------------------------------------------------
| Override auth types for specific 'class/method/HTTP method'
|--------------------------------------------------------------------------
|
| example:
|
| $config['auth_override_class_method_http']['deals']['view']['get'] = 'none';
| $config['auth_override_class_method_http']['deals']['insert']['post'] = 'none';
| $config['auth_override_class_method_http']['deals']['*']['options'] = 'none';
*/
// ---Uncomment list line for the wildard unit test
// $config['auth_override_class_method_http']['wildcard_test_cases']['*']['options'] = 'basic';
// Class User verifycode get auth Ϊ none *ΪСд user*
// ֤ͼƬ <img src ֱget, ׼ header, ˲ʹ x-api-key header
// this.VerificationImg = 'http://www.cirest.com:8889/api/v3/sys/user/verifycode?verify=' + this.verify
$config['auth_override_class_method_http']['user']['verifycode']['get'] = 'none';
/*
|--------------------------------------------------------------------------
| REST Login Usernames
|--------------------------------------------------------------------------
|
| Array of usernames and passwords for login, if ldap is configured this is ignored
|
*/
$config['rest_valid_logins'] = ['admin' => '1234'];
/*
|--------------------------------------------------------------------------
| Global IP White-listing
|--------------------------------------------------------------------------
|
| Limit connections to your REST server to White-listed IP addresses
|
| Usage:
| 1. Set to TRUE and select an auth option for extreme security (client's IP
| address must be in white-list and they must also log in)
| 2. Set to TRUE with auth set to FALSE to allow White-listed IPs access with no login
| 3. Set to FALSE but set 'auth_override_class_method' to 'white-list' to
| restrict certain methods to IPs in your white-list
|
*/
$config['rest_ip_whitelist_enabled'] = false;
/*
|--------------------------------------------------------------------------
| REST Handle Exceptions
|--------------------------------------------------------------------------
|
| Handle exceptions caused by the controller
|
*/
$config['rest_handle_exceptions'] = true;
/*
|--------------------------------------------------------------------------
| REST IP White-list
|--------------------------------------------------------------------------
|
| Limit connections to your REST server with a comma separated
| list of IP addresses
|
| e.g: '123.456.789.0, 987.654.32.1'
|
| 127.0.0.1 and 0.0.0.0 are allowed by default
|
*/
$config['rest_ip_whitelist'] = '';
/*
|--------------------------------------------------------------------------
| Global IP Blacklisting
|--------------------------------------------------------------------------
|
| Prevent connections to the REST server from blacklisted IP addresses
|
| Usage:
| 1. Set to TRUE and add any IP address to 'rest_ip_blacklist'
|
*/
$config['rest_ip_blacklist_enabled'] = false;
/*
|--------------------------------------------------------------------------
| REST IP Blacklist
|--------------------------------------------------------------------------
|
| Prevent connections from the following IP addresses
|
| e.g: '123.456.789.0, 987.654.32.1'
|
*/
$config['rest_ip_blacklist'] = '';
/*
|--------------------------------------------------------------------------
| REST Database Group
|--------------------------------------------------------------------------
|
| Connect to a database group for keys, logging, etc. It will only connect
| if you have any of these features enabled
|
*/
$config['rest_database_group'] = 'default';
/*
|--------------------------------------------------------------------------
| REST API Keys Table Name
|--------------------------------------------------------------------------
|
| The table name in your database that stores API keys
|
*/
$config['rest_keys_table'] = 'keys';
/*
|--------------------------------------------------------------------------
| REST Enable Keys
|--------------------------------------------------------------------------
|
| When set to TRUE, the REST API will look for a column name called 'key'.
| If no key is provided, the request will result in an error. To override the
| column name see 'rest_key_column'
|
| Default table schema:
| CREATE TABLE `keys` (
| `id` INT(11) NOT NULL AUTO_INCREMENT,
| `user_id` INT(11) NOT NULL,
| `key` VARCHAR(40) NOT NULL,
| `level` INT(2) NOT NULL,
| `ignore_limits` TINYINT(1) NOT NULL DEFAULT '0',
| `is_private_key` TINYINT(1) NOT NULL DEFAULT '0',
| `ip_addresses` TEXT NULL DEFAULT NULL,
| `date_created` INT(11) NOT NULL,
| PRIMARY KEY (`id`)
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
*/
$config['rest_enable_keys'] = false;
/*
|--------------------------------------------------------------------------
| REST Table Key Column Name
|--------------------------------------------------------------------------
|
| If not using the default table schema in 'rest_enable_keys', specify the
| column name to match e.g. my_key
|
*/
$config['rest_key_column'] = 'key';
/*
|--------------------------------------------------------------------------
| REST API Limits method
|--------------------------------------------------------------------------
|
| Specify the method used to limit the API calls
|
| Available methods are :
| $config['rest_limits_method'] = 'IP_ADDRESS'; // Put a limit per ip address
| $config['rest_limits_method'] = 'API_KEY'; // Put a limit per api key
| $config['rest_limits_method'] = 'METHOD_NAME'; // Put a limit on method calls
| $config['rest_limits_method'] = 'ROUTED_URL'; // Put a limit on the routed URL
|
*/
$config['rest_limits_method'] = 'ROUTED_URL';
/*
|--------------------------------------------------------------------------
| REST Key Length
|--------------------------------------------------------------------------
|
| Length of the created keys. Check your default database schema on the
| maximum length allowed
|
| Note: The maximum length is 40
|
*/
$config['rest_key_length'] = 40;
/*
|--------------------------------------------------------------------------
| REST API Key Variable
|--------------------------------------------------------------------------
|
| Custom header to specify the API key
| Note: Custom headers with the X- prefix are deprecated as of
| 2012/06/12. See RFC 6648 specification for more details
|
*/
$config['rest_key_name'] = 'X-API-KEY';
/*
|--------------------------------------------------------------------------
| REST Enable Logging
|--------------------------------------------------------------------------
|
| When set to TRUE, the REST API will log actions based on the column names 'key', 'date',
| 'time' and 'ip_address'. This is a general rule that can be overridden in the
| $this->method array for each controller
|
| Default table schema:
| CREATE TABLE `logs` (
| `id` INT(11) NOT NULL AUTO_INCREMENT,
| `uri` VARCHAR(255) NOT NULL,
| `method` VARCHAR(6) NOT NULL,
| `params` TEXT DEFAULT NULL,
| `api_key` VARCHAR(40) NOT NULL,
| `ip_address` VARCHAR(45) NOT NULL,
| `time` INT(11) NOT NULL,
| `rtime` FLOAT DEFAULT NULL,
| `authorized` VARCHAR(1) NOT NULL,
| `response_code` smallint(3) DEFAULT '0',
| PRIMARY KEY (`id`)
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
*/
$config['rest_enable_logging'] = false;
/*
|--------------------------------------------------------------------------
| REST API Logs Table Name
|--------------------------------------------------------------------------
|
| If not using the default table schema in 'rest_enable_logging', specify the
| table name to match e.g. my_logs
|
*/
$config['rest_logs_table'] = 'logs';
/*
|--------------------------------------------------------------------------
| REST Method Access Control
|--------------------------------------------------------------------------
| When set to TRUE, the REST API will check the access table to see if
| the API key can access that controller. 'rest_enable_keys' must be enabled
| to use this
|
| Default table schema:
| CREATE TABLE `access` (
| `id` INT(11) unsigned NOT NULL AUTO_INCREMENT,
| `key` VARCHAR(40) NOT NULL DEFAULT '',
| `all_access` TINYINT(1) NOT NULL DEFAULT '0',
| `controller` VARCHAR(50) NOT NULL DEFAULT '',
| `date_created` DATETIME DEFAULT NULL,
| `date_modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
| PRIMARY KEY (`id`)
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
*/
$config['rest_enable_access'] = false;
/*
|--------------------------------------------------------------------------
| REST API Access Table Name
|--------------------------------------------------------------------------
|
| If not using the default table schema in 'rest_enable_access', specify the
| table name to match e.g. my_access
|
*/
$config['rest_access_table'] = 'access';
/*
|--------------------------------------------------------------------------
| REST API Param Log Format
|--------------------------------------------------------------------------
|
| When set to TRUE, the REST API log parameters will be stored in the database as JSON
| Set to FALSE to log as serialized PHP
|
*/
$config['rest_logs_json_params'] = false;
/*
|--------------------------------------------------------------------------
| REST Enable Limits
|--------------------------------------------------------------------------
|
| When set to TRUE, the REST API will count the number of uses of each method
| by an API key each hour. This is a general rule that can be overridden in the
| $this->method array in each controller
|
| Default table schema:
| CREATE TABLE `limits` (
| `id` INT(11) NOT NULL AUTO_INCREMENT,
| `uri` VARCHAR(255) NOT NULL,
| `count` INT(10) NOT NULL,
| `hour_started` INT(11) NOT NULL,
| `api_key` VARCHAR(40) NOT NULL,
| PRIMARY KEY (`id`)
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
| To specify the limits within the controller's __construct() method, add per-method
| limits with:
|
| $this->methods['METHOD_NAME']['limit'] = [NUM_REQUESTS_PER_HOUR];
|
| See application/controllers/api/example.php for examples
*/
$config['rest_enable_limits'] = false;
/*
|--------------------------------------------------------------------------
| REST API Limits Table Name
|--------------------------------------------------------------------------
|
| If not using the default table schema in 'rest_enable_limits', specify the
| table name to match e.g. my_limits
|
*/
$config['rest_limits_table'] = 'limits';
/*
|--------------------------------------------------------------------------
| REST Ignore HTTP Accept
|--------------------------------------------------------------------------
|
| Set to TRUE to ignore the HTTP Accept and speed up each request a little.
| Only do this if you are using the $this->rest_format or /format/xml in URLs
|
*/
$config['rest_ignore_http_accept'] = false;
/*
|--------------------------------------------------------------------------
| REST AJAX Only
|--------------------------------------------------------------------------
|
| Set to TRUE to allow AJAX requests only. Set to FALSE to accept HTTP requests
|
| Note: If set to TRUE and the request is not AJAX, a 505 response with the
| error message 'Only AJAX requests are accepted.' will be returned.
|
| Hint: This is good for production environments
|
*/
$config['rest_ajax_only'] = false;
/*
|--------------------------------------------------------------------------
| REST Language File
|--------------------------------------------------------------------------
|
| Language file to load from the language directory
|
*/
$config['rest_language'] = 'simplified-chinese';
/*
|--------------------------------------------------------------------------
| CORS Check
|--------------------------------------------------------------------------
|
| Set to TRUE to enable Cross-Origin Resource Sharing (CORS). Useful if you
| are hosting your API on a different domain from the application that
| will access it through a browser
|
*/
//$config['check_cors'] = false;
$config['check_cors'] = true;
/*
|--------------------------------------------------------------------------
| CORS Allowable Headers
|--------------------------------------------------------------------------
|
| If using CORS checks, set the allowable headers here
|
*/
$config['allowed_cors_headers'] = [
'Origin',
'X-Requested-With',
'Content-Type',
'Accept',
'Access-Control-Request-Method',
'X-API-KEY',
'X-Token',
'cache-control'
];
/*
|--------------------------------------------------------------------------
| CORS Allowable Methods
|--------------------------------------------------------------------------
|
| If using CORS checks, you can set the methods you want to be allowed
|
*/
$config['allowed_cors_methods'] = [
'GET',
'POST',
'OPTIONS',
'PUT',
'PATCH',
'DELETE',
];
/*
|--------------------------------------------------------------------------
| CORS Allow Any Domain
|--------------------------------------------------------------------------
|
| Set to TRUE to enable Cross-Origin Resource Sharing (CORS) from any
| source domain
|
*/
//$config['allow_any_cors_domain'] = false;
$config['allow_any_cors_domain'] = false;
/*
|--------------------------------------------------------------------------
| CORS Allowable Domains
|--------------------------------------------------------------------------
|
| Used if $config['check_cors'] is set to TRUE and $config['allow_any_cors_domain']
| is set to FALSE. Set all the allowable domains within the array
|
| e.g. $config['allowed_origins'] = ['http://www.example.com', 'https://spa.example.com']
|
*/
$config['allowed_cors_origins'] = [
'user'=>'https://user.uahpet.com',
'dna'=>'https://dna.uahpet.com',
'report'=>'https://report.uahpet.com',
'user_dev'=>'http://192.168.0.100:8080',
'dna_dev'=>'http://localhost:9527',
'report_dev'=>'http://192.168.0.107:8080',
'report_dev_2'=>'http://192.168.0.105:8080',
'report_dev_3'=>'http://192.168.88.101:8080',
'report_dev_4'=>'http://192.168.0.104:8080',
'report_dev_5'=>'http://192.168.0.109:8080',
];
/*
|--------------------------------------------------------------------------
| CORS Forced Headers
|--------------------------------------------------------------------------
|
| If using CORS checks, always include the headers and values specified here
| in the OPTIONS client preflight.
| Example:
| $config['forced_cors_headers'] = [
| 'Access-Control-Allow-Credentials' => 'true'
| ];
|
| Added because of how Sencha Ext JS framework requires the header
| Access-Control-Allow-Credentials to be set to true to allow the use of
| credentials in the REST Proxy.
| See documentation here:
| http://docs.sencha.com/extjs/6.5.2/classic/Ext.data.proxy.Rest.html#cfg-withCredentials
|
*/
$config['forced_cors_headers'] = [];
+71
View File
@@ -0,0 +1,71 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| https://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
| $route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
//// http://localhost/restful/trunk/index.php/api/books_articles/index/2/22
///*
//| -------------------------------------------------------------------------
//| Sample REST API Routes
//| -------------------------------------------------------------------------
//*/
// 重新定义路由规则了 可选 根据控制器中获取的参数 将不规则的路由 重新定义成规则的路由
//$route['api/example/users/(:num)'] = 'api/example/users/id/$1'; // Example 4 , api/example/users/3 转换成 api/example/users/id/3 形式
//$route['api/example/users/(:num)(\.)([a-zA-Z0-9_-]+)(.*)'] = 'api/example/users/id/$1/format/$3$4'; // Example 8
// qiaokun test restful api
//$route['api/([a-z0-9]+)/(\d+)'] = "api/$1/index/$2";
//$route['api/([a-z0-9]+)/(\d+)/([a-z0-9]+)'] = "api/$1_$3/index/$2";
//$route['api/([a-z0-9]+)/(\d+)/([a-z0-9]+)/(\d+)'] = "api/$1_$3/index/$2/$4";
//$route['api/([a-z0-9]+)/(\d+)'] = "api/$1/index/$2";
+64
View File
@@ -0,0 +1,64 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| SMILEYS
| -------------------------------------------------------------------
| This file contains an array of smileys for use with the emoticon helper.
| Individual images can be used to replace multiple smileys. For example:
| :-) and :) use the same image replacement.
|
| Please see user guide for more info:
| https://codeigniter.com/user_guide/helpers/smiley_helper.html
|
*/
$smileys = array(
// smiley image name width height alt
':-)' => array('grin.gif', '19', '19', 'grin'),
':lol:' => array('lol.gif', '19', '19', 'LOL'),
':cheese:' => array('cheese.gif', '19', '19', 'cheese'),
':)' => array('smile.gif', '19', '19', 'smile'),
';-)' => array('wink.gif', '19', '19', 'wink'),
';)' => array('wink.gif', '19', '19', 'wink'),
':smirk:' => array('smirk.gif', '19', '19', 'smirk'),
':roll:' => array('rolleyes.gif', '19', '19', 'rolleyes'),
':-S' => array('confused.gif', '19', '19', 'confused'),
':wow:' => array('surprise.gif', '19', '19', 'surprised'),
':bug:' => array('bigsurprise.gif', '19', '19', 'big surprise'),
':-P' => array('tongue_laugh.gif', '19', '19', 'tongue laugh'),
'%-P' => array('tongue_rolleye.gif', '19', '19', 'tongue rolleye'),
';-P' => array('tongue_wink.gif', '19', '19', 'tongue wink'),
':P' => array('raspberry.gif', '19', '19', 'raspberry'),
':blank:' => array('blank.gif', '19', '19', 'blank stare'),
':long:' => array('longface.gif', '19', '19', 'long face'),
':ohh:' => array('ohh.gif', '19', '19', 'ohh'),
':grrr:' => array('grrr.gif', '19', '19', 'grrr'),
':gulp:' => array('gulp.gif', '19', '19', 'gulp'),
'8-/' => array('ohoh.gif', '19', '19', 'oh oh'),
':down:' => array('downer.gif', '19', '19', 'downer'),
':red:' => array('embarrassed.gif', '19', '19', 'red face'),
':sick:' => array('sick.gif', '19', '19', 'sick'),
':shut:' => array('shuteye.gif', '19', '19', 'shut eye'),
':-/' => array('hmm.gif', '19', '19', 'hmmm'),
'>:(' => array('mad.gif', '19', '19', 'mad'),
':mad:' => array('mad.gif', '19', '19', 'mad'),
'>:-(' => array('angry.gif', '19', '19', 'angry'),
':angry:' => array('angry.gif', '19', '19', 'angry'),
':zip:' => array('zip.gif', '19', '19', 'zipper'),
':kiss:' => array('kiss.gif', '19', '19', 'kiss'),
':ahhh:' => array('shock.gif', '19', '19', 'shock'),
':coolsmile:' => array('shade_smile.gif', '19', '19', 'cool smile'),
':coolsmirk:' => array('shade_smirk.gif', '19', '19', 'cool smirk'),
':coolgrin:' => array('shade_grin.gif', '19', '19', 'cool grin'),
':coolhmm:' => array('shade_hmm.gif', '19', '19', 'cool hmm'),
':coolmad:' => array('shade_mad.gif', '19', '19', 'cool mad'),
':coolcheese:' => array('shade_cheese.gif', '19', '19', 'cool cheese'),
':vampire:' => array('vampire.gif', '19', '19', 'vampire'),
':snake:' => array('snake.gif', '19', '19', 'snake'),
':exclaim:' => array('exclaim.gif', '19', '19', 'exclaim'),
':question:' => array('question.gif', '19', '19', 'question')
);
+215
View File
@@ -0,0 +1,215 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| USER AGENT TYPES
| -------------------------------------------------------------------
| This file contains four arrays of user agent data. It is used by the
| User Agent Class to help identify browser, platform, robot, and
| mobile device data. The array keys are used to identify the device
| and the array values are used to set the actual name of the item.
*/
$platforms = array(
'windows nt 10.0' => 'Windows 10',
'windows nt 6.3' => 'Windows 8.1',
'windows nt 6.2' => 'Windows 8',
'windows nt 6.1' => 'Windows 7',
'windows nt 6.0' => 'Windows Vista',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.1' => 'Windows XP',
'windows nt 5.0' => 'Windows 2000',
'windows nt 4.0' => 'Windows NT 4.0',
'winnt4.0' => 'Windows NT 4.0',
'winnt 4.0' => 'Windows NT',
'winnt' => 'Windows NT',
'windows 98' => 'Windows 98',
'win98' => 'Windows 98',
'windows 95' => 'Windows 95',
'win95' => 'Windows 95',
'windows phone' => 'Windows Phone',
'windows' => 'Unknown Windows OS',
'android' => 'Android',
'blackberry' => 'BlackBerry',
'iphone' => 'iOS',
'ipad' => 'iOS',
'ipod' => 'iOS',
'os x' => 'Mac OS X',
'ppc mac' => 'Power PC Mac',
'freebsd' => 'FreeBSD',
'ppc' => 'Macintosh',
'linux' => 'Linux',
'debian' => 'Debian',
'sunos' => 'Sun Solaris',
'beos' => 'BeOS',
'apachebench' => 'ApacheBench',
'aix' => 'AIX',
'irix' => 'Irix',
'osf' => 'DEC OSF',
'hp-ux' => 'HP-UX',
'netbsd' => 'NetBSD',
'bsdi' => 'BSDi',
'openbsd' => 'OpenBSD',
'gnu' => 'GNU/Linux',
'unix' => 'Unknown Unix OS',
'symbian' => 'Symbian OS'
);
// The order of this array should NOT be changed. Many browsers return
// multiple browser types so we want to identify the sub-type first.
$browsers = array(
'OPR' => 'Opera',
'Flock' => 'Flock',
'Edge' => 'Edge',
'Chrome' => 'Chrome',
// Opera 10+ always reports Opera/9.80 and appends Version/<real version> to the user agent string
'Opera.*?Version' => 'Opera',
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => 'Internet Explorer',
'Trident.* rv' => 'Internet Explorer',
'Shiira' => 'Shiira',
'Firefox' => 'Firefox',
'Chimera' => 'Chimera',
'Phoenix' => 'Phoenix',
'Firebird' => 'Firebird',
'Camino' => 'Camino',
'Netscape' => 'Netscape',
'OmniWeb' => 'OmniWeb',
'Safari' => 'Safari',
'Mozilla' => 'Mozilla',
'Konqueror' => 'Konqueror',
'icab' => 'iCab',
'Lynx' => 'Lynx',
'Links' => 'Links',
'hotjava' => 'HotJava',
'amaya' => 'Amaya',
'IBrowse' => 'IBrowse',
'Maxthon' => 'Maxthon',
'Ubuntu' => 'Ubuntu Web Browser'
);
$mobiles = array(
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
// 'opera mini' => 'Opera Mini',
// 'operamini' => 'Opera Mini',
// 'elaine' => 'Palm',
'palmsource' => 'Palm',
// 'digital paths' => 'Palm',
// 'avantgo' => 'Avantgo',
// 'xiino' => 'Xiino',
'palmscape' => 'Palmscape',
// 'nokia' => 'Nokia',
// 'ericsson' => 'Ericsson',
// 'blackberry' => 'BlackBerry',
// 'motorola' => 'Motorola'
// Phones and Manufacturers
'motorola' => 'Motorola',
'nokia' => 'Nokia',
'nexus' => 'Nexus',
'palm' => 'Palm',
'iphone' => 'Apple iPhone',
'ipad' => 'iPad',
'ipod' => 'Apple iPod Touch',
'sony' => 'Sony Ericsson',
'ericsson' => 'Sony Ericsson',
'blackberry' => 'BlackBerry',
'cocoon' => 'O2 Cocoon',
'blazer' => 'Treo',
'lg' => 'LG',
'amoi' => 'Amoi',
'xda' => 'XDA',
'mda' => 'MDA',
'vario' => 'Vario',
'htc' => 'HTC',
'samsung' => 'Samsung',
'sharp' => 'Sharp',
'sie-' => 'Siemens',
'alcatel' => 'Alcatel',
'benq' => 'BenQ',
'ipaq' => 'HP iPaq',
'mot-' => 'Motorola',
'playstation portable' => 'PlayStation Portable',
'playstation 3' => 'PlayStation 3',
'playstation vita' => 'PlayStation Vita',
'hiptop' => 'Danger Hiptop',
'nec-' => 'NEC',
'panasonic' => 'Panasonic',
'philips' => 'Philips',
'sagem' => 'Sagem',
'sanyo' => 'Sanyo',
'spv' => 'SPV',
'zte' => 'ZTE',
'sendo' => 'Sendo',
'nintendo dsi' => 'Nintendo DSi',
'nintendo ds' => 'Nintendo DS',
'nintendo 3ds' => 'Nintendo 3DS',
'wii' => 'Nintendo Wii',
'open web' => 'Open Web',
'openweb' => 'OpenWeb',
// Operating Systems
'android' => 'Android',
'symbian' => 'Symbian',
'SymbianOS' => 'SymbianOS',
'elaine' => 'Palm',
'series60' => 'Symbian S60',
'windows ce' => 'Windows CE',
// Browsers
'obigo' => 'Obigo',
'netfront' => 'Netfront Browser',
'openwave' => 'Openwave Browser',
'mobilexplorer' => 'Mobile Explorer',
'operamini' => 'Opera Mini',
'opera mini' => 'Opera Mini',
'opera mobi' => 'Opera Mobile',
'fennec' => 'Firefox Mobile',
// Other
'digital paths' => 'Digital Paths',
'avantgo' => 'AvantGo',
'xiino' => 'Xiino',
'novarra' => 'Novarra Transcoder',
'vodafone' => 'Vodafone',
'docomo' => 'NTT DoCoMo',
'o2' => 'O2',
// Fallback
'mobile' => 'Generic Mobile',
'wireless' => 'Generic Mobile',
'j2me' => 'Generic Mobile',
'midp' => 'Generic Mobile',
'cldc' => 'Generic Mobile',
'up.link' => 'Generic Mobile',
'up.browser' => 'Generic Mobile',
'smartphone' => 'Generic Mobile',
'cellphone' => 'Generic Mobile'
);
// There are hundreds of bots but these are the most common.
$robots = array(
'googlebot' => 'Googlebot',
'msnbot' => 'MSNBot',
'baiduspider' => 'Baiduspider',
'bingbot' => 'Bing',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'ask jeeves' => 'Ask Jeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos',
'yandex' => 'YandexBot',
'mediapartners-google' => 'MediaPartners Google',
'CRAZYWEBCRAWLER' => 'Crazy Webcrawler',
'adsbot-google' => 'AdsBot Google',
'feedfetcher-google' => 'Feedfetcher Google',
'curious george' => 'Curious George',
'ia_archiver' => 'Alexa Crawler',
'MJ12bot' => 'Majestic-12',
'Uptimebot' => 'Uptimebot'
);
+303
View File
@@ -0,0 +1,303 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 证书
* @author luoxuancai 2019/5/7
*/
class Cert extends CI_Controller {
const SESSION_KEY = 'device_id_cert';
public function __construct()
{
parent::__construct();
$this->load->model('wx_token');
}
/**
* 验证查看权限
* 用户/手机号主人/超管可以看
**/
protected function _check_auth($device_id){
//未登录验证
if(in_array($device_id,$_SESSION[self::SESSION_KEY])){
return true;
}
//超级管理员可以查看任意证书
$isLoggedIn = $this->session->userdata ( 'isAdminLoggedIn' );
if (isset ( $isLoggedIn ) || $isLoggedIn == TRUE) {
return true;
}
//已登录查看自己的验证码
if(!empty($_SESSION['users_id'])){
$this->load->model('model_UsersInfo');
//检查信息是否能对应
$row = $this->model_UsersInfo->get(
$device_id,
'device_id'
);
if(!empty($row) && $row['users_id'] == $_SESSION['users_id']){
return true;
}
}
return false;
}
protected function _set_auth($device_id){
//未登录验证
$_SESSION[self::SESSION_KEY][] = $device_id;
}
// 验证短信验证码是否有效
public function send_sms_code(){
$this->load->model('sms_code');
$this->sms_code->test();
$mobile = $_POST['mobile'];
$data = [
'ret' => 1,
'msg' => ''
];
if(empty($mobile)){
$data['msg'] = '信息不完整';
}
$this->load->model('sms_code');
if($this->sms_code->send(
$mobile,
rand(0,9)
)){
$data['msg'] = '验证码错误或已过期,请重新获取';
}
}
// 验证短信验证码是否有效
public function check_sms_code(){
$mobile = $_POST['mobile'];
$device_id = $_POST['device_id'];
$code = $_POST['code'];
$data = [
'ret' => 1,
'msg' => ''
];
if(empty($mobile) or empty($device_id) or empty($code)){
$data['msg'] = '信息不完整';
}
//检查设备号对应情况,没有填手机号则报错
$this->load->model('Model_UsersInfo');
//检查信息是否能对应
$row = $this->model_UsersInfo->get(
$mobile,
'users_tel'
);
if(empty($row) or $row['device_id']!==$device_id){
$data['msg'] = '手机号或序列号错误';
}
//检查验证码
$this->load->model('sms_code');
if($this->sms_code->check(
$mobile,
$code
)){
$data['msg'] = '验证码错误或已过期,请重新获取';
}
echo json_encode($data,JSON_UNESCAPED_UNICODE);
}
/**
* 激活查询
*/
public function query()
{
$mobile = isset($_REQUEST['mobile']) ? $_REQUEST['mobile'] : 0;
$device_id = isset($_REQUEST['device_id']) ? $_REQUEST['device_id'] : 0;
$data = [
'info' => [],
'warning' => ''
];
if($mobile and $device_id){
//检查信息是否能对应
$row = $this->model_UsersInfo->get(
$mobile,
'users_tel'
);
if(empty($row) or $row['device_id']!==$device_id){
$data['warning'] = '手机号或序列号错误';
}else{
$data['info'] = $row;
}
}
$data['type'] = 'info';
$this->load->view('cert/index', $data);
}
/**
* 证书查询
*/
public function index()
{
$this->load->model('model_UsersInfo');
$device_id = isset($_REQUEST['device_id']) ? $_REQUEST['device_id'] : 0;
$data = [
'info' => [],
'warning' => ''
];
if($device_id){
//检查信息是否能对应
$row = $this->model_UsersInfo->get(
$device_id,
'device_id'
);
if(empty($row)){
$data['warning'] = '序列号错误';
}else{
header('Location:/cert/id/'.trim($device_id));
$data['info'] = $row;
}
}
$data['type'] = 'cert';
$this->load->view('cert/index', $data);
}
/**
* 激活信息
*/
public function info($id)
{
if(empty($id)){
return $this->notify();
}
$this->load->model('Model_UsersInfo');
$this->load->model('report_model');
//报告文件
$file = $this->report_model->report_file_path(trim($id));
$reportJson = [];
if(file_exists($file)){
$a=filemtime($file);
$data['time'] = date("Y.m.d",$a);
//return $this->notify();
$reportJson = file_get_contents($file);
$reportJson = json_decode($reportJson,true);
}
//补充图片,物种
$info = $this->Model_UsersInfo->get_by_device_id($id);
if(!$info){
return $this->notify();
}
$data = array(
'owner'=>''
);
$data['device_id'] = $id;
//$data['name'] = $reportJson['header']['宠物名'];
//$data['wolf'] = isset($reportJson['进阶项目研究']['body']['狼性']['body'])?$reportJson['进阶项目研究']['body']['狼性']['body']:'未知';
if(!empty($reportJson)){
$data['mixed'] = isset($reportJson['血统分析']['body']['品系纯度'])?$reportJson['血统分析']['body']['品系纯度']:[];
}
//主人信息
$data['owner'] = $info['users_name'];
$data['name'] = $info['pet_name'];
$data['time'] = date("Y.m.d",$info['createtime']);
//预置血统信息优先
$data['mixed'] = ['未知'=>''];
if(!empty($info['lineage'])){
$data['mixed'] = [];
$lineage = explode(';',$info['lineage']);
foreach ($lineage as $val) {
$val = explode(':',$val);
if(count($val)<2){
continue;
}
$data['mixed'][$val[0]] = $val[1];
}
}
$this->load->view('user/includes/header', NULL);
$this->load->view('user/includes/nav', NULL);
$this->load->view('cert/id', $data);
$this->load->view('user/includes/footer', NULL);
}
/**
* 证书
*/
public function id($id)
{
if(empty($id)){
return $this->notify();
}
$this->load->model('Model_UsersInfo');
$this->load->model('report_model');
//报告文件
$file = $this->report_model->report_file_path(trim($id));
$reportJson = [];
if(file_exists($file)){
$a=filemtime($file);
$data['time'] = date("Y.m.d",$a);
//return $this->notify();
$reportJson = file_get_contents($file);
$reportJson = json_decode($reportJson,true);
}
//补充图片,物种
$info = $this->Model_UsersInfo->get_by_device_id($id);
if(!$info){
return $this->notify();
}
$data = array(
'owner'=>''
);
$data['device_id'] = $id;
//$data['name'] = $reportJson['header']['宠物名'];
//$data['wolf'] = isset($reportJson['进阶项目研究']['body']['狼性']['body'])?$reportJson['进阶项目研究']['body']['狼性']['body']:'未知';
if(!empty($reportJson)){
$data['mixed'] = isset($reportJson['血统分析']['body']['品系纯度'])?$reportJson['血统分析']['body']['品系纯度']:[];
}
//主人信息
$data['owner'] = $info['users_name'];
$data['name'] = $info['pet_name'];
$data['time'] = date("Y.m.d",$info['createtime']);
//预置血统信息优先
$data['mixed'] = ['未知'=>''];
if(!empty($info['lineage'])){
$data['mixed'] = [];
$lineage = explode(';',$info['lineage']);
foreach ($lineage as $val) {
$val = explode(':',$val);
if(count($val)<2){
continue;
}
$data['mixed'][$val[0]] = $val[1];
}
}
$data['test_date'] = $info['test_date'];
$data['birthday'] = $info['pet_birthday'];
$this->load->view('user/includes/header', NULL);
$this->load->view('user/includes/nav', NULL);
$this->load->view('cert/id', $data);
$this->load->view('user/includes/footer', NULL);
}
protected function notify(){
$this->load->view('user/includes/header', NULL);
$this->load->view('user/includes/nav', NULL);
$this->load->view('cert/notify', []);
$this->load->view('user/includes/footer', NULL);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Rest_server extends CI_Controller {
public function index()
{
$this->load->helper('url');
$this->load->view('rest_server');
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use EasyWeChat\Foundation\Application as OfficialAccount;
/**
* DNA检测系统微信授权入口首页
* @author luoxuancai
*/
class Test extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->model('customer_model');
}
// 中通快递查询
public function zto()
{
$this->load->model('zto_model');
//$ret_search = $this->zto_model->commonOrderSearchbycode('200310051678942109','29');
//$ret_search = $this->zto_model->commonOrderSearchbycode('200311000100544107','27');
//$ret_search = $this->zto_model->commonOrderSearchbycode('200311000276939109','49');
//print_r($ret_search);
/*
if($ship_order){
$track = $this->zto_model->traceInterfaceNewTraces($ship_order['order_code']);
}*/
$track = $this->zto_model->traceInterfaceNewTraces(73127201209703);
print_r($track);
}
// 中通
public function zto_query()
{
$this->load->model('zto_model');
$this->zto_model->commonOrderSearchbycode('200210000005196104','1');
}
// 测试顺丰
public function sf()
{
$this->load->model('sf_express_model');
$data = [
'trade_id'=>'2020041903',
'province'=>'上海市',
'city'=>'上海市',
'district'=>'嘉定区',
'name'=>'测试',
'tel'=>'15815725225',
'address'=>'黄浦江晓东楼房',
];
$ret = $this->sf_express_model->shipSample($data);
print_r($ret);die;
//$this->sf_express_model->test();
}
// 测试顺丰
public function sf2()
{
$this->load->model('sf_express_model');
$data = [
'user_id'=>'1',
'trade_id'=>'2020041903',
'province'=>'上海市',
'city'=>'上海市',
'district'=>'嘉定区',
'name'=>'测试',
'tel'=>'15815725225',
'address'=>'黄浦江晓东楼房',
];
$this->sf_express_model->test($data);
}
}
+143
View File
@@ -0,0 +1,143 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use EasyWeChat\Foundation\Application as OfficialAccount;
/**
* DNA检测系统微信授权入口首页
* @author luoxuancai
*/
class Weixin extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->model('customer_model');
}
protected function getApp(){
$conf = $this->config->item('weixin_uah');
$config = [
'app_id' => $conf['AppId'],
'secret' => $conf['AppSecert'],
'token' => $conf['Token'],
'aes_key' => $conf['EncodingAESKey'],
'response_type' => 'array',
];
return new OfficialAccount($config);
}
// 发起授权页
public function index()
{
$to_url = $this->input->get('url');
if(empty($to_url)){
die('Url is empty.');
}
//支持静默授权
$scope = !empty($this->input->get('is_base'))?'snsapi_base':'snsapi_userinfo';
//如已登录,则不跳转
if(!empty($this->session->{Customer_model::SESSION_KEY})){
Header("HTTP/1.1 303 See Other");
Header("Location: $to_url");
die;
}
//未登录,则跳转授权,处理会员数据之后再进行一次跳转
$callback_url = base_url().strtolower(__CLASS__).'/callback';
$callback_url.='?url='.urlencode($to_url);
$app = $this->getApp();
$response = $app->oauth->scopes([$scope])->redirect($callback_url);
$response->send();
}
//授权回调页
public function callback()
{
$to_url = $this->input->get('url');
$app = $this->getApp();
try{
$user = $app->oauth->user();
}catch (Exception $e){
die('Error:'.$e->getMessage());
}
if(!$user){
die('User info empty.');
}
if($user->original['scope'] == 'snsapi_base') {
$this->session->{Customer_model::SESSION_KEY_WX_OPEN_ID} = $user->original['openid'];
}else{
$ret = $this->customer_model->weixin_users($user->original);
if(!$ret){
die('Database connect failed.');
}
$this->session->{Customer_model::SESSION_KEY} = $ret;
}
Header("HTTP/1.1 303 See Other");
Header("Location: $to_url");
}
// 直接设置session user id,在微信外登录
public function test()
{
$this->session->{Customer_model::SESSION_KEY} = 1;
die('dfdf');
//$this->session->{Customer_model::SESSION_KEY_WX_OPEN_ID} = 'ddd';
//echo $this->session->{Customer_model::SESSION_KEY_WX_OPEN_ID};die;
}
public function test2()
{
unset($this->session->{Customer_model::SESSION_KEY});
//$this->session->{Customer_model::SESSION_KEY} = 26;
// $this->session->{Customer_model::SESSION_KEY} = 'aadd';
// if(!empty($this->session->{Customer_model::SESSION_KEY})){
// die('222');
// }
}
public function test_get()
{
var_dump($this->session->{Customer_model::SESSION_KEY});
}
//判断是介入还是用户 只有第一次介入的时候才会返回echostr
public function check_sign(){
//这个echostr呢 只有说验证的时候才会echo 如果是验证过之后这个echostr是不存在的字段了
$echoStr = $_GET["echostr"];
if ($this->checkSignature()) {
echo $echoStr;
//如果你不知道是否验证成功 你可以先echo echostr 然后再写一个东西
exit;
}
}
//验证微信开发者模式接入是否成功
private function checkSignature(){
//signature 是微信传过来的 类似于签名的东西
$signature = $_GET["signature"];
//微信发过来的东西
$timestamp = $_GET["timestamp"];
//微信传过来的值 什么用我不知道...
$nonce = $_GET["nonce"];
//定义你在微信公众号开发者模式里面定义的token
$token = $this->Token;
//三个变量 按照字典排序 形成一个数组
$tmpArr = array(
$token,
$timestamp,
$nonce
);
// use SORT_STRING rule
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
//哈希加密 在laravel里面是Hash::
$tmpStr = sha1($tmpStr);
//按照微信的套路 给你一个signature没用是不可能的 这里就用得上了
if ($tmpStr == $signature) {
return true; //一定要返回 不要echo 负责微信拿不到返回值导致不通过
} else {
return false;
}
}// checkSignature end
}
+25
View File
@@ -0,0 +1,25 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('welcome_message');
}
}
+330
View File
@@ -0,0 +1,330 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use \Firebase\JWT\JWT; //导入JWT
require 'vendor/php-sdk-7.2.8/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use chriskacerguis\RestServer\RestController;
/**
* This is an example of a few basic user interaction methods you could use
* all done with a hardcoded array
*
* @package CodeIgniter
* @subpackage Rest Server
* @category Controller
* @author Phil Sturgeon, Chris Kacerguis
* @license MIT
* @link https://github.com/chriskacerguis/codeigniter-restserver
*/
class Example extends RestController {
function __construct()
{
// Construct the parent class
parent::__construct();
// Configure limits on our controller methods
// Ensure you have created the 'limits' table and enabled 'limits' within application/config/rest.php
$this->methods['users_get']['limit'] = 500; // 500 requests per hour per user/key
$this->methods['users_post']['limit'] = 100; // 100 requests per hour per user/key
$this->methods['users_delete']['limit'] = 50; // 50 requests per hour per user/key
}
public function users_get()
{
// var_dump($this->input->server('REQUEST_METHOD'));
// var_dump($this->get('id')); // 参数带id
// var_dump($this->get('blah')); // http://www.cirest.com:8889/api/example/users/id/2/di/3 可以传多个参数
//
// //通过query获取 url 传参 测试失败?
// var_dump($this->query('id'));
// var_dump($this->query('blah'));
// var_dump($this->query());
// Users from a data store e.g. database
$users = [
['id' => 1, 'name' => 'John', 'email' => 'john@example.com', 'fact' => 'Loves coding'],
['id' => 2, 'name' => 'Jim', 'email' => 'jim@example.com', 'fact' => 'Developed on CodeIgniter'],
['id' => 3, 'name' => 'Jane', 'email' => 'jane@example.com', 'fact' => 'Lives in the USA', ['hobbies' => ['guitar', 'cycling']]],
];
$id = $this->get('id');
// If the id parameter doesn't exist return all the users
if ($id === NULL)
{
// Check if the users data store contains users (in case the database result returns NULL)
if ($users)
{
// Set the response and exit
$this->response($users, RestController::HTTP_OK); // OK (200) being the HTTP response code
}
else
{
// Set the response and exit
$this->response([
'status' => FALSE,
'message' => 'No users were found'
], RestController::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
}
}
// Find and return a single record for a particular user.
$id = (int) $id;
// Validate the id.
if ($id <= 0)
{
// Invalid id, set the response and exit.
$this->response(NULL, RestController::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// Get the user from the array, using the id as key for retrieval.
// Usually a model is to be used for this.
$user = NULL;
if (!empty($users))
{
foreach ($users as $key => $value)
{
if (isset($value['id']) && $value['id'] === $id)
{
$user = $value;
}
}
}
if (!empty($user))
{
$this->set_response($user, RestController::HTTP_OK); // OK (200) being the HTTP response code
}
else
{
$this->set_response([
'status' => FALSE,
'message' => 'User could not be found'
], RestController::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
}
}
public function users_post()
{
// $this->some_model->update_user( ... );
$message = [
'id' => 100, // Automatically generated by the model
'name' => $this->post('name'),
'email' => $this->post('email'),
'message' => 'Added a resource'
];
$this->set_response($message, RestController::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
public function users_delete()
{
// $this->>delete获取不到参数
// 可以使用 url 传参数方式获取 使用 $this->get('id')来接收
// DELETE http://www.cirest.com:8889/api/example/users/2 使用中路由重写了 成/users/id/2
// DELETE http://www.cirest.com:8889/api/example/users/id/2
var_dump($this->get('id')); // 参数带id
var_dump($this->get('blah')); // http://www.cirest.com:8889/api/example/users/id/2/blah/3 可以传多个参数
$id = (int) $this->get('id');
var_dump($id);
// Validate the id.
if ($id <= 0)
{
// Set the response and exit
$this->response(NULL, RestController::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// $this->some_model->delete_something($id);
$message = [
'id' => $id,
'message' => 'Deleted the resource'
];
$this->set_response($message, RestController::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code
}
// 签发Token
public function issue_get()
{
$key = '344'; //key
$time = time(); //当前时间
$token = [
'iss' => 'http://www.helloweba.net', //签发者 可选
'aud' => 'http://www.helloweba.net', //接收该JWT的一方,可选
'iat' => $time, //签发时间
'nbf' => $time, //(Not Before):某个时间点后才能访问,比如设置time+30,表示当前时间30秒后才能使用
'exp' => $time + 7200, //过期时间,这里设置2个小时
'data' => [ //自定义信息,不要定义敏感信息
'userid' => 1,
'username' => '李小龙'
]
];
$jsonList = [
'access_token' => JWT::encode($token, $key),
];
$this->set_response($jsonList, RestController::HTTP_CREATED);
}
public function verification_post()
{
$key = '344'; //key要和签发的时候一样
$jwt = $this->post('access_token'); //签发的Token
try {
JWT::$leeway = 60;//当前时间减去60,把时间留点余地
$decoded = JWT::decode($jwt, $key, ['HS256']); //HS256方式,这里要和签发的时候对应
$arr = (array)$decoded;
print_r($arr);
} catch (\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
echo $e->getMessage();
} catch (\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
echo $e->getMessage();
} catch (\Firebase\JWT\ExpiredException $e) { // token过期
echo $e->getMessage();
} catch (Exception $e) { //其他错误
echo $e->getMessage();
}
//Firebase定义了多个 throw new,我们可以捕获多个catch来定义问题,catch加入自己的业务,比如token过期可以用当前Token刷新一个新Token
}
// 七牛 上传图片测试
public function qiniu_get()
{
$cfg = [
'access' => 'K5w2Fe4XowpU6kuklgLlAhGkXWt111WVssI1R0ff',
'secret' => 'i9QhgiUvdO5AgpPnQkPXO6n9wA9jILLeaskqP0Iz',
'bucket' => 'pocoyo_bucket',
'domain' => 'http://pub8vjaao.bkt.clouddn.com'
];
$auth = new Auth($cfg['access'], $cfg['secret']);
// 创建一个过期时间为1小时的临时上传令牌
$token = $auth->uploadToken($cfg['bucket'], null, 3600);
// 中文名需要转换编码?
$filePath = iconv('UTF-8', 'GBK', APPPATH . 'controllers\api\QQ图片20160922141622.png');
$uploadMgr = new UploadManager();
list($ret, $err) = $uploadMgr->putFile($token, null, $filePath);
if($err !== null) {
$this->err = $err;
var_dump($err);
} else {
echo $cfg['domain'] . '/' . $ret['key'];
}
}
// Chevereto 图床免费版本地址:https://github.com/Chevereto/Chevereto-Free
// https://chevereto.com/docs/api-v1
// 上传图片测试
public function chevereto_post()
{
// 1. 上传本地文件时应使用 $fields post base64_encode方法
// Always use POST when uploading local files. Url encoding may alter the base64 source
// due to encoded characters or just by URL request length limit due to GET request.
// base64编码 会导致过长 url request
// var_dump($_FILES); 参考 uploadimg 可以做一些前置校验处理 // 前置判断 if (empty($_FILES) === false)
$key = '5486424e4dfb6b87453dd4bb25c0dcb0';
$url = 'http://172.17.1.110/chevereto/api/1/upload';
// What do we send to chevereto api?
$fields = array(
'key' => urlencode($key),
// The image encoded in base64
'source' => base64_encode(file_get_contents($_FILES["file"]['tmp_name'])),
// format: txt / json txt 只返回图片地址或错误信息 eg.Duplicated upload 较为简洁
'format' => urlencode('json')
);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, sizeof($fields));
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 240);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: '));
//execute post
$result = curl_exec($ch);
//释放curl句柄
curl_close($ch);
echo $result;
//close connection
// 2. 上传远程图片地址可使用 _get source=urlencode{source} 方法即可
// $key = '6a55c7f9fa13813c2da613dc7b5b920b';
// // 设定远程图片地址
// $source = 'https://img3.doubanio.com/view/group_topic/large/public/p67032015.jpg';
// // format: txt / json txt 只返回图片地址或错误信息 eg.Duplicated upload 较为简洁
// $url = 'http://172.17.1.110:8888/api/1/upload/?key={key}&source={source}&format=txt';
// $url = str_replace(array('{key}','{source}'),array($key,urlencode($source)),$url);
//
// //初始化
// $ch = curl_init();
// //设置选项,包括URL
// curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_HEADER, 0);
// //执行并获取HTML文档内容
// $output = curl_exec($ch);
// //释放curl句柄
// curl_close($ch);
// echo $output;
// 失败
// {
// "status_txt": "Bad Request",
// "error": {
// "context": "Exception",
// "code": 102,
// "message": "Duplicated upload"
// },
// "status_code": 400
// }
// 成功
// {
// "status_txt": "OK",
// "image": {
// "image": {
// "size": "89163",
// "url": "http://172.17.1.110:8888/images/2019/07/09/p67032015.jpg",
// "extension": "jpg",
// "mime": "image/jpeg",
// "name": "p67032015",
// "filename": "p67032015.jpg"
// },
// },
// "success": {
// "code": 200,
// "message": "image uploaded"
// },
// "status_code": 200
// }
}
}
+256
View File
@@ -0,0 +1,256 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
/**
* Keys Controller
* This is a basic Key Management REST controller to make and delete keys
*
* @package CodeIgniter
* @subpackage Rest Server
* @category Controller
* @author Phil Sturgeon, Chris Kacerguis
* @license MIT
* @link https://github.com/chriskacerguis/codeigniter-restserver
*/
class Key extends RestController
{
protected $methods = [
'index_put' => ['level' => 10, 'limit' => 10],
'index_delete' => ['level' => 10],
'level_post' => ['level' => 10],
'regenerate_post' => ['level' => 10],
];
/**
* Insert a key into the database
*
* @access public
* @return void
*/
public function index_put()
{
// Build a new key
$key = $this->_generate_key();
// If no key level provided, provide a generic key
$level = $this->put('level') ? $this->put('level') : 1;
$ignore_limits = ctype_digit($this->put('ignore_limits')) ? (int)$this->put('ignore_limits') : 1;
// Insert the new key
if ($this->_insert_key($key, ['level' => $level, 'ignore_limits' => $ignore_limits])) {
$this->response([
'status' => TRUE,
'key' => $key
], RestController::HTTP_CREATED); // CREATED (201) being the HTTP response code
} else {
$this->response([
'status' => FALSE,
'message' => 'Could not save the key'
], RestController::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
/**
* Remove a key from the database to stop it working
*
* @access public
* @return void
*/
public function index_delete($key)
{
// $this->>delete获取不到参数
// 可以使用 url 传参数方式获取
// DELETE http://www.cirest.com:8889/api/key/8ww0sgk0sogs0ocg4gsw0gwsosk8wwcwoks044ws
// $key = $this->delete('key');
// $key='oocwo8cs88g4c8w8c08ow00ss844cc4osko0s0ks';
// Does this key exist?
if (!$this->_key_exists($key)) {
// It doesn't appear the key exists
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], RestController::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// Destroy it
$this->_delete_key($key);
// Respond that the key was destroyed
$this->response([
'status' => TRUE,
'message' => 'API key was deleted'
], RestController::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code
}
/**
* Change the level
*
* @access public
* @return void
*/
public function level_post()
{
$key = $this->post('key');
$new_level = $this->post('level');
// Does this key exist?
if (!$this->_key_exists($key)) {
// It doesn't appear the key exists
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], RestController::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// Update the key level
if ($this->_update_key($key, ['level' => $new_level])) {
$this->response([
'status' => TRUE,
'message' => 'API key was updated'
], RestController::HTTP_OK); // OK (200) being the HTTP response code
} else {
$this->response([
'status' => FALSE,
'message' => 'Could not update the key level'
], RestController::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
/**
* Suspend a key
* 挂起api key 则key 的level 设置为0
* @access public
* @return void
*/
public function suspend_post()
{
$key = $this->post('key');
// Does this key exist?
if (!$this->_key_exists($key)) {
// It doesn't appear the key exists
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], RestController::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// Update the key level
if ($this->_update_key($key, ['level' => 0])) {
$this->response([
'status' => TRUE,
'message' => 'Key was suspended'
], RestController::HTTP_OK); // OK (200) being the HTTP response code
} else {
$this->response([
'status' => FALSE,
'message' => 'Could not suspend the user'
], RestController::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
/**
* Regenerate a key
* 将 key level 设置为0 (禁用),数据库里生成一条新的key记录并且延用原来level,ignore_limits
* @access public
* @return void
*/
public function regenerate_post()
{
$old_key = $this->post('key');
$key_details = $this->_get_key($old_key);
// Does this key exist?
if (!$key_details) {
// It doesn't appear the key exists
$this->response([
'status' => FALSE,
'message' => 'Invalid API key'
], RestController::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
}
// Build a new key
$new_key = $this->_generate_key();
// Insert the new key
if ($this->_insert_key($new_key, ['level' => $key_details->level, 'ignore_limits' => $key_details->ignore_limits])) {
// Suspend old key
$this->_update_key($old_key, ['level' => 0]);
$this->response([
'status' => TRUE,
'key' => $new_key
], RestController::HTTP_CREATED); // CREATED (201) being the HTTP response code
} else {
$this->response([
'status' => FALSE,
'message' => 'Could not save the key'
], RestController::HTTP_INTERNAL_SERVER_ERROR); // INTERNAL_SERVER_ERROR (500) being the HTTP response code
}
}
/* Helper Methods */
private function _generate_key()
{
do {
// Generate a random salt
$salt = base_convert(bin2hex($this->security->get_random_bytes(64)), 16, 36);
// If an error occurred, then fall back to the previous method
if ($salt === FALSE) {
$salt = hash('sha256', time() . mt_rand());
}
$new_key = substr($salt, 0, config_item('rest_key_length'));
} while ($this->_key_exists($new_key));
return $new_key;
}
/* Private Data Methods */
private function _get_key($key)
{
return $this->rest->db
->where(config_item('rest_key_column'), $key)
->get(config_item('rest_keys_table'))
->row();
}
private function _key_exists($key)
{
return $this->rest->db
->where(config_item('rest_key_column'), $key)
->count_all_results(config_item('rest_keys_table')) > 0;
}
private function _insert_key($key, $data)
{
$data[config_item('rest_key_column')] = $key;
$data['date_created'] = function_exists('now') ? now() : time();
return $this->rest->db
->set($data)
->insert(config_item('rest_keys_table'));
}
private function _update_key($key, $data)
{
return $this->rest->db
->where(config_item('rest_key_column'), $key)
->update(config_item('rest_keys_table'), $data);
}
private function _delete_key($key)
{
return $this->rest->db
->where(config_item('rest_key_column'), $key)
->delete(config_item('rest_keys_table'));
}
}
+402
View File
@@ -0,0 +1,402 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* @author luoxuancai 2017/7/13
*/
class Index extends ApiController {
const TEST_SUFFIX = '-Test';
protected $_is_test = false;
public function __construct()
{
header('Access-Control-Allow-Credentials: true');
parent::__construct();
$this->load->model('sample_model');
$this->load->model('report_model');
}
public function index_get()
{
if(empty($_GET['id'])){
$this->setError('请求错误');
}
$id = trim($_GET['id']);
$id = $this->getDeviceId($id);
//报告文件
$ret = $this->report_model->get_result($id,$this->_is_test);
if(empty($ret)){
$this->setError('报告未生成');
die;
}
$this->setSuccess($ret);
}
//获取犬类疾病的列表,需要挂钩报告编号,以便显示锁定与解锁的疾病
protected function disease_list($need_category,$need_detail)
{
/*
* 从库中读取
$params = [];
//区分单基因/多基因
if(!empty($_GET['gene_type'])){
$params['gene_type'] = $_GET['gene_type'];
}
$this->load->model('disease_model');
$list = $this->disease_model->listing($params, 0,50000,'base.*');
*/
/*
* 从素材分类
$material = $this->report_model->get_material();
$info = [];
$list = array_merge($material['犬类单基因疾病'],$material['犬类复杂疾病']);
//类别描述删除多余字符
$searchStrOne = explode('|','类遗传疾病|类疾病|系统遗传病|遗传病|遗传疾病|疾病');
$searchStrTwo = explode('|','类|系统类|系统');
foreach ($list as $key=>$val) {
if(empty($val['所属类别'])){
$name = '其他';
}else{
//删除多余的描述
$name = str_replace($searchStrOne,'',$val['所属类别']);
$name = str_replace($searchStrTwo,'',$name);
}
$info[$name][] = [
'name'=>$key,
'lock'=>$lock && !in_array($key,$lockDisease)
];
}
*/
if(empty($_GET['id'])){
$this->setError('请求错误');
}
$id = trim($_GET['id']);
$id = $this->getDeviceId($id);
//样品及套餐信息
$this->load->model('sample_model');
$this->load->model('package_model');
$sample = $this->sample_model->get($id,'device_id');
if(empty($sample)){
$this->setError('样品不存在');
die;
}
//报告文件
$json = $this->report_model->get_report_json($id,$sample['pet_species']);
//套餐设置成1,上线后删除
//$sample['package_id'] = 1;
$package = $this->package_model->get($sample['package_id']);
if(!$package){
return [];
}
$gene_type = !empty($_GET['gene_type'])?$_GET['gene_type']:0;
return $this->report_model->get_disease_list($gene_type,$sample,$json,$package,$need_category,$need_detail);
}
//疾病列表
public function disease_list_get(){
$ret = $this->disease_list(!empty($_GET['need_category']),false);
if(!empty($_GET['need_category'])){
//需要分类的疾病是单基因疾病,将解锁的放前面
foreach ($ret as $category_name => $list) {
$lock = [];
$unlock = [];
foreach ($list as $key=>$val) {
if($val['lock']){
$lock[] = $val;
}else{
$unlock[] = $val;
}
}
$ret[$category_name] = array_merge($unlock,$lock);
}
}
$this->setSuccess($ret);
}
//疾病列表
public function disease_get()
{
/*
$this->load->model('disease_model');
$row = $this->disease_model->get($_GET['disease_name'],'base.name');
*/
if(empty($_GET['disease_name'])){
$this->setError('请求错误');
}
$ret = [];
$material = $this->disease_list(false,true);
foreach ($material as $item) {
if($item['name'] == $_GET['disease_name']){
$ret = $item;
break;
}
}
//根据基因类型,做低风险描述调整,未检测出时没有描述
if(!$ret['risk']){
$ret['risk_desc'] = $ret['gene_type'] == 1?'未检测到致病突变':'低发病风险';
}
$this->setSuccess($ret);
}
//证书图片信息
public function cert_health_list_get()
{
//疾病描述
$this->load->model('Cat_disease_desc_model');
$disease = [];
$material = $this->disease_list(false,true);
foreach ($material as $item) {
$description = $this->Cat_disease_desc_model->breeding_single_detail($item['name']);
if(empty($description)){
continue;
}
//风险等级
$risk_tag = 'N/N';
if($item['risk']){
$risk_tag = $item['risk_level'] == 1?'N/F':'F/F';
}
$disease[] = [
//疾病名称
'name'=>$item['name'],
//疾病N/N
'risk_tag'=>$risk_tag,
//结果说明
'risk_desc'=>$description['检测结果'][$risk_tag],
//检测手段
'method'=>$description['检测手段'],
//基因型
'gene_type'=>$description['基因型'],
//N/N
'NN'=>$description['结果说明']['N/N'],
'NF'=>$description['结果说明']['N/F'],
'FF'=>$description['结果说明']['F/F'],
];
}
$this->success($disease);
}
//证书图片单张
public function cert_health_get()
{
if(empty($_GET['name'])){
$this->setError('请求错误');
}
$disease = [];
$material = $this->disease_list(false,true);
foreach ($material as $item) {
if($item['name'] == $_GET['name']){
$disease = $item;
break;
}
}
//根据基因类型,做低风险描述调整,未检测出时没有描述
if(!$disease['risk']){
$disease['risk_desc'] = $disease['gene_type'] == 1?'未检测到致病突变':'低发病风险';
}
//样本信息
$id = trim($_GET['id']);
$id = $this->getDeviceId($id);
//样品及套餐信息
$this->load->model('sample_model');
$this->load->model('package_model');
$sample = $this->sample_model->get($id,'device_id');
if(empty($sample)){
$this->setError('样品不存在');
die;
}
//疾病描述
$this->load->model('Cat_disease_desc_model');
$description = $this->Cat_disease_desc_model->breeding_single_detail($_GET['name']);
if(empty($description)){
die('empty');
}
//证书文件如果有就直接输出
$this->load->library('uploads');
$id = strtoupper($id);
$upload_path = $this->uploads->get_upload_path();
$cert_img_path = $upload_path.Uploads::DIR_PER_CERT_IMG.DIRECTORY_SEPARATOR.$id.DIRECTORY_SEPARATOR;
$cert_file_name = $cert_img_path.$_GET['name'].'.jpg';
if(file_exists($cert_file_name)){
//声明需要创建的图层的图片格式
header("Content-Type:image/jpg");
echo file_get_contents($cert_file_name);
die();
}
//风险等级
$risk_tag = 'N/N';
if($disease['risk']){
$risk_tag = $disease['risk_level'] == 1?'N/F':'F/F';
}
//图片
header("Content-type: image/png");
$file = APPPATH."uahpet/cert_template/health.png";//图片跟路径
$font = APPPATH."uahpet/font/SourceHanSansCN-Regular.otf";
$font_bold = APPPATH."uahpet/font/SourceHanSansCN-Bold.otf";
$img = imagecreatefrompng($file);
$blue = imagecolorallocate($img, 17, 182, 179);
$black = imagecolorallocate($img, 62, 62, 62);
//名字
$sting = $sample['pet_name'];
imagettftext($img, 15, 0, 288, 705, $black, $font, $sting);
//养育人
$sting = $sample['name'];
imagettftext($img, 15, 0, 600, 705, $black, $font, $sting);
//测试日期
$sting = date('Y-m-d',$sample['create_time']);
imagettftext($img, 15, 0, 970, 705, $black, $font, $sting);
//疾病名称
$sting = $_GET['name'];
imagettftext($img, 27, 0, 186, 965, $blue, $font_bold, $sting);
//疾病N/N
$sting = $risk_tag;
imagettftext($img, 27, 0, 638, 965, $blue, $font_bold, $sting);
//结果说明
$sting = $description['检测结果'][$risk_tag] ;
imagettftext($img, 15, 0, 736, 960, $black, $font, $sting);
/* 证书左侧段落 */
//检测手段
$sting = '检测手段:'.$description['检测手段'];
imagettftext($img, 13, 0, 188, 1030, $black, $font, $sting);
//检测手段解释
$sting = '基 因 型:';
imagettftext($img, 13, 0, 188, 1061, $black, $font, $sting);
//检测手段解释
$sting_arr = explode("\n",$description['基因型']);
//右侧,处理换行
foreach ($sting_arr as $key=>$val) {
imagettftext($img, 13, 0, 188+85, 1061+$key*25, $black, $font, $val);
}
/* 证书右侧段落 */
//N/N
$sting = 'N/N'.$description['结果说明']['N/N'];
imagettftext($img, 13, 0, 644, 1030, $black, $font, $sting);
//N/F
//标题
$sting_arr = $this->cutImgString($description['结果说明']['N/F'],26);
$sting = 'N/F';
imagettftext($img, 13, 0, 644, 1061, $black, $font, $sting);
//右侧,处理换行
foreach ($sting_arr as $key=>$val) {
imagettftext($img, 13, 0, 644+45, 1061+$key*25, $black, $font, $val);
}
//F/F
$sting = 'F/F'.$description['结果说明']['F/F'];
imagettftext($img, 13, 0, 644, 1093+(count($sting_arr)-1)*16, $black, $font, $sting);
imagejpeg($img,$cert_file_name,75);
imagedestroy($img);
echo file_get_contents($cert_file_name);
exit;
}
public function cert_health_down_post()
{
//接口禁用
die('');
$data = $this->json_input();
if(empty($data) || empty($data['id'])){
$this->setError('请求错误');
}
//样本序列号
$device_id = trim($data['id']);
$device_id = $this->getDeviceId($device_id);
//接收血统证书,血统证书很难在服务器端生成
$base64_cert_lineage = trim($data['cert_lineage']);
$this->load->library('uploads');
$this->load->library('MakeZip');
//报告id
$device_id = strtoupper($device_id);
//图片
$pet_img = $this->uploads->save_cert_img_base64(
$base64_cert_lineage,
$device_id,
'健康证书'
);
if(!$pet_img){
$this->error('健康证书输出失败');
}
//压缩
$path = (Uploads::DIR).DIRECTORY_SEPARATOR;
$sourceDir = $path.(Uploads::DIR_PER_CERT_IMG).DIRECTORY_SEPARATOR.$device_id.DIRECTORY_SEPARATOR;
$targetFile = $path.(Uploads::DIR_PER_CERT_ZIP).DIRECTORY_SEPARATOR.uniqid().'.zip';
$res = $this->makezip->zip(FCPATH.$sourceDir,FCPATH.$targetFile);
if(!$res){
throw new Exception('压缩失败');
}
$this->success(['file'=>base_url().$targetFile]);
exit;
}
private function setError($err,$code = 0){
echo json_encode(['code'=>$code,'msg'=>$err]);
die;
}
private function setSuccess($data){
echo json_encode(['code'=>1,'msg'=>'','data'=>$data]);
die;
}
protected function getDeviceId($deviceID){
//是否预置了测试参数
$this->_is_test = substr($deviceID,-strlen(self::TEST_SUFFIX)) == self::TEST_SUFFIX;
if($this->_is_test){
return substr($deviceID,0,-strlen(self::TEST_SUFFIX));
}
return $deviceID;
}
//字数太长要折行,统计折行的行数
protected function cutImgString($str,$len){
if(mb_strlen($str)<$len){
return [$str];
}
$str_len = mb_strlen($str);
$count = ceil($str_len/$len);
$result = [];
for($x = 0; $x <= $count; $x++){
$result[] =mb_substr($str,$len*$x,$len);
}
return $result;
}
}
+739
View File
@@ -0,0 +1,739 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use EasyWeChat\Foundation\Application as OfficialAccount;
class Active extends ApiController
{
function __construct()
{
header('Access-Control-Allow-Credentials: true');
parent::__construct();
//跨域
$this->load->library('session');
$this->load->model('series_number_model');
$this->load->model('package_model');
$this->load->model('sample_model');
$this->load->model('customer_model');
$this->checkUser();
}
public function ticket_get()
{
$conf = $this->config->item('weixin_uah');
$config = [
'app_id' => $conf['AppId'],
'secret' => $conf['AppSecert'],
'token' => $conf['Token'],
'aes_key' => $conf['EncodingAESKey'],
'response_type' => 'array',
];
$app = new OfficialAccount($config);
$url = $this->input->get('url');
if(!empty($url)){
$app->js->setUrl($url);
}else
if(!empty($_SERVER['HTTP_REFERER'])){
$app->js->setUrl($_SERVER['HTTP_REFERER']);
}
$config = $app->js->config(array('updateAppMessageShareData', 'updateTimelineShareData', 'scanQRCode'), $debug = false, $beta = false, $json = true);
$this->success(['config'=>json_decode($config)]);
}
public function check_number_post()
{
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[3]|max_length[20]'
),
);
$data = $this->json_validation($config);
$series = $this->series_number_model->get($data['device_id'],'device_id');
if(!$series){
$this->error('请联系【店铺】在线客服绑定序列号');
}
$sample = $this->sample_model->get($series['id'],'series_id');
if($sample){
$this->error('序列号已使用');
}
$package = $this->package_model->get($series['package_ori']);
if(!$package){
$this->error('序列号不可用,套餐信息不存在');
}
$content = empty($package['content'])?[]:json_decode($package['content'],true);
//获取所有疾病的名称
if(!empty($content)){
$disease_ids = [];
foreach ($content as $item) {
$disease_ids = array_merge($disease_ids,$item['disease_id']);
}
$this->load->model('disease_model');
$disease_list = $this->disease_model->get($disease_ids,'base.id',true);
$disease_map = [];
foreach ($disease_list as $val) {
$disease_map[$val['id']] = $val;
}
//疾病详情存到信息中
foreach ($content as $key=>$val) {
$val['disease_list'] = [];
foreach ($val['disease_id'] as $v) {
if(!isset($disease_map[$v])){
continue;
}
$val['disease_list'][] = $disease_map[$v];
}
$content[$key] = $val;
}
}
$package['content'] = $content;
$this->success(['package'=>$package]);
}
//新建样本
public function create_post()
{
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[4]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
'min_length' => '%s长度不足:%s.',
'max_length' => '%s长度不能超过:%s.',
),
),
array(
'field' => 'name',
'label' => '用户姓名',
'rules' => 'trim|required|min_length[1]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'tel',
'label' => '手机',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_name',
'label' => '宠物名称',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_sex',
'label' => '宠物性别',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_birthday',
'label' => '宠物生日',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:芯片号
array(
'field' => 'chip_number',
'label' => '芯片号',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:是否种猫
array(
'field' => 'is_breeding',
'label' => '是否种猫',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:血统认证机构
array(
'field' => 'lineage_cert_body',
'label' => '血统认证机构',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
)
);
$data = $this->json_validation($config);
$series = $this->series_number_model->get($data['device_id'],'device_id');
if(!$series){
$this->error('序列号不存在');
}
$sample = $this->sample_model->get($series['id'],'series_id');
if($sample){
$this->error('序列号已使用');
}
$package = $this->package_model->get($series['package_ori']);
if(!$package){
$this->error('套餐不存在');
}
//过滤字段
$fields = array_column($config,'field');
$entity = [];
foreach ($data as $key=>$val) {
if(in_array($key,$fields)){
$entity[$key] = $val;
}
}
unset($entity['device_id']);
//套餐是否要求选择疾病
$package['content'] = empty($package['content'])?[]:json_decode($package['content'],true);
//选择的疾病处理
if(!empty($package['content'])){
if(!isset($data['package_custom'])){
$this->error('请选择套餐选项');
}
//选择的选项是否允许选择
if(!isset($package['content'][$data['package_custom']])){
$this->error('您选择的套餐选项已失效');
}
$package_custom = $package['content'][$data['package_custom']];
//获取疾病的名称,保存起来,以免id变化
$this->load->model('disease_model');
$tmp = $this->disease_model->get($package_custom['disease_id'],'base.id',true);
$entity['package_custom'] = json_encode([
'id'=>$data['package_custom'],
'name'=>$package_custom['name'],
'disease_id'=>$package_custom['disease_id'],
'disease_name'=>array_column($tmp,'name')
],JSON_UNESCAPED_UNICODE);
}else{
$entity['package_custom'] = '';
}
//用户id
$entity['user_id'] = $this->_user_id;
//从device_id读取序列号ID
$entity['series_id'] = $series['id'];
//套餐
$entity['package_id'] = $series['package_ori'];
//套餐的猫狗写进样品,防止套餐变更造成影响
$entity['pet_species'] = $package['species'];
//头像处理
if(!empty($data['file']['content'])){
$imgBase64 = $data['file']['content'];
if(!empty($data['file']['ext'])){
//对于java接口,需要兼容前端的格式
$imgBase64 = 'data:image/'.trim($data['file']['ext']).';base64,'.$imgBase64;
}
$this->load->library('uploads');
//存原图
$pet_img = $this->uploads->save_pet_img_base64(
$imgBase64,
$data['device_id']
);
if($pet_img){
$entity['pet_img'] = $pet_img;
}
}
//绝育情况,如果没有传入则按“否”处理
if(empty($entity['is_sterilized'])){
$entity['is_sterilized'] = 0;
}
//处理宠物性别与绝育情况合并的情况(非繁育用户)
switch ($entity['pet_sex']){
case 1:
$entity['pet_sex'] = 1;
break;
case 2:
$entity['pet_sex'] = 2;
break;
case 3:
$entity['pet_sex'] = 1;
$entity['is_sterilized'] = 1;
break;
case 4:
$entity['pet_sex'] = 2;
$entity['is_sterilized'] = 1;
break;
default:
$entity['pet_sex'] = 1;
}
//步骤置为初始步骤
$entity['step'] = Sample_model::STEP_BIND;
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
$conf = $this->config->item('allowed_cors_origins');
try{
//如果没关注,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_ACTIVE,
base_url().'weixin/?url='.urlencode($conf['user'].'/ship'),
[
'first'=>'激活成功,如您还没选择回寄,请点击回寄',
'keyword1'=>$data['device_id'],
'keyword2'=>$package['name'],
'remark'=>'',
]
);
}catch (Exception $e){
}
//如果证书有多个,用逗号组合
if(is_array($entity['lineage_cert_body'])){
$entity['lineage_cert_body'] = implode(',',$entity['lineage_cert_body']);
}
$ret = $this->sample_model->add($entity);
/*
//保存一条样品流程处理信息
$this->load->model('sample_processing_model');
$this->sample_processing_model->add([
'sample_id'=>$ret,
'step'=>$entity['step']
]);
//保存一条样品套餐升级信息
$this->load->model('sample_upgrade_model');
$this->sample_upgrade_model->add([
'sample_id'=>$ret,
'package_id'=>$entity['package_id'],
'package_custom'=>$entity['package_custom']
]);
*/
if($ret){
//激活了繁育套餐的客户,用户信息修改
//if(!empty($package['is_breed'])){}
$this->success();
}else{
$this->error('提交失败');
}
}
//获取需回寄的样品
public function ship_get()
{
$ret = $this->sample_model->get($this->_user_id,'user_id',true);
//只展示需回寄样品
$un_ship = [];
foreach ($ret as $key=>$item) {
if($item['step'] < Sample_model::STEP_SENT){
$un_ship[] = $ret[$key];
}
}
$first = [];
//取第一个样品的信息
if(!empty($un_ship)){
$first = $un_ship[0];
}elseif(!empty($ret)){
$first = $ret[0];
}
$this->success(['sample'=>$un_ship,'info'=>$first]);
}
//样品回寄
public function ship_post()
{
$config = array(
array(
'field' => 'device_id[]',
'label' => '样品',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'name',
'label' => '姓名',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'tel',
'label' => '手机号',
'rules' => 'required'
),
array(
'field' => 'address',
'label' => '地址',
'rules' => 'required'
),
array(
'field' => 'province',
'label' => '省',
'rules' => 'required'
),
array(
'field' => 'city',
'label' => '市',
'rules' => 'required'
),
array(
'field' => 'district',
'label' => '区',
'rules' => 'required'
)
);
$receiver_address = array(
'cat' => array(
'd_province' => '广东省',
'd_city' => '深圳市',
'd_county' => '大鹏新区',
'd_company' => '有哈科技',
'd_contact' => '有哈收样组(侯佩彤)',
'd_tel' => '13723470168',
'd_address' => '大鹏街道鹏飞路7号中国农科院中国农业科学院深圳农业基因组研究所',
),
'dog' => array(
'd_province' => '广东省',
'd_city' => '深圳市',
'd_county' => '大鹏新区',
'd_company' => '有哈科技',
'd_contact' => '有哈收样组(侯佩彤)',
'd_tel' => '13723470168',
'd_address' => '大鹏街道鹏飞路7号中国农科院中国农业科学院深圳农业基因组研究所',
)
);
$data = $this->json_validation($config);
$sample_ids = [];
$dog_cat = [false, false];
$samples = array(
'cat' => [],
'cat_device_ids' =>[],
'dog' => [],
'dog_device_ids' =>[],
);
foreach ($data['device_id'] as $device_id) {
$sample = $this->sample_model->get($device_id,'device_id');
if($sample['user_id'] != $this->_user_id){
$this->error('该样品不在您名下');
}
if ($sample['pet_species'] == 1){
$dog_cat[0] = true;
$samples['dog'][] = $sample['id'];
$samples['dog_device_ids'][] = $device_id;
}else if ($sample['pet_species'] == 2){
$dog_cat[1] = true;
$samples['cat'][] = $sample['id'];
$samples['cat_device_ids'][] = $device_id;
}
$sample_ids[] = $sample['id'];
}
//创建订单
$data['user_id'] = $this->_user_id;
$this->load->model('sf_express_model');
if ($dog_cat[0] && $dog_cat[1]){
// $this->error("ship -> dog: $dog_cat[0], cat: $dog_cat[1]");
$data['d_province'] = $receiver_address['dog']['d_province'];
$data['d_city'] = $receiver_address['dog']['d_city'];
$data['d_county'] = $receiver_address['dog']['d_county'];
$data['d_company'] = $receiver_address['dog']['d_company'];
$data['d_contact'] = $receiver_address['dog']['d_contact'];
$data['d_tel'] = $receiver_address['dog']['d_tel'];
$data['d_address'] = $receiver_address['dog']['d_address'];
$data['trade_id'] = $samples['dog'][0];
$ret = $this->sf_express_model->shipSample($data);
//$ret = [true];
error_log("shipSample dog: $ret[0] $ret[1]");
if($ret[0]){
//快递id写到样品中
$this->sample_model->update(['ship_order_id'=>$ret[1],'step'=>Sample_model::STEP_SENT],'id in ('.implode(',',$samples['dog']).')');
try{
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
//如果没关系,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_SENT,
null,
[
'first'=>'尊敬的用户:我们已为您分配了快递员,请保持手机畅通,快递员会尽快与您联系。',
'keyword1'=>implode(',',$samples['dog_device_ids']),
//'keyword2'=>'上门取货后获取',
'keyword2'=>$ret[1],
'keyword3'=>'预估两小时内',
//'remark'=>'物流信息只能在中通官网查看,请保管好回寄单号方便日后物流查询。',
'remark'=>'我们已为您呼叫了顺丰速运,请耐心等待。物流信息可在“顺丰速运”公众号查看。',
]
);
}catch (Exception $e){
}
}else{
if (strpos($ret[1], '您的预约超出今日营业时间') !== false){
$this->error('快递营业时间:8-18点,现已超出今日营业时间,请于明日8点后进行预约取件。');
}else{
$this->error('快递未能使用,请添加微信号“uap_pet”咨询客服,错误信息:'.$ret[1]);
}
}
sleep(1);
$data['d_province'] = $receiver_address['cat']['d_province'];
$data['d_city'] = $receiver_address['cat']['d_city'];
$data['d_county'] = $receiver_address['cat']['d_county'];
$data['d_company'] = $receiver_address['cat']['d_company'];
$data['d_contact'] = $receiver_address['cat']['d_contact'];
$data['d_tel'] = $receiver_address['cat']['d_tel'];
$data['d_address'] = $receiver_address['cat']['d_address'];
$data['trade_id'] = $samples['cat'][0];
$ret = $this->sf_express_model->shipSample($data);
//$ret = [true];
error_log("shipSample cat: $ret[0] $ret[1]");
if($ret[0]){
//快递id写到样品中
$this->sample_model->update(['ship_order_id'=>$ret[1],'step'=>Sample_model::STEP_SENT],'id in ('.implode(',',$samples['dog']).')');
try{
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
//如果没关系,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_SENT,
null,
[
'first'=>'尊敬的用户:我们已为您分配了快递员,请保持手机畅通,快递员会尽快与您联系。',
'keyword1'=>implode(',',$samples['cat_device_ids']),
//'keyword2'=>'上门取货后获取',
'keyword2'=>$ret[1],
'keyword3'=>'预估两小时内',
//'remark'=>'物流信息只能在中通官网查看,请保管好回寄单号方便日后物流查询。',
'remark'=>'我们已为您呼叫了顺丰速运,请耐心等待。物流信息可在“顺丰速运”公众号查看。',
]
);
}catch (Exception $e){
}
$this->success();
}else{
if (strpos($ret[1], '您的预约超出今日营业时间') !== false){
$this->error('快递营业时间:8-18点,现已超出今日营业时间,请于明日8点后进行预约取件。');
}else{
$this->error('快递未能使用,请添加微信号“uap_pet”咨询客服,错误信息:'.$ret[1]);
}
}
}else if ($dog_cat[1] || $dog_cat[0]){
$data['trade_id'] = $data['device_id'][0];
if ($dog_cat[0]){
$data['d_province'] = $receiver_address['dog']['d_province'];
$data['d_city'] = $receiver_address['dog']['d_city'];
$data['d_county'] = $receiver_address['dog']['d_county'];
$data['d_company'] = $receiver_address['dog']['d_company'];
$data['d_contact'] = $receiver_address['dog']['d_contact'];
$data['d_tel'] = $receiver_address['dog']['d_tel'];
$data['d_address'] = $receiver_address['dog']['d_address'];
}else{
$data['d_province'] = $receiver_address['cat']['d_province'];
$data['d_city'] = $receiver_address['cat']['d_city'];
$data['d_county'] = $receiver_address['cat']['d_county'];
$data['d_company'] = $receiver_address['cat']['d_company'];
$data['d_contact'] = $receiver_address['cat']['d_contact'];
$data['d_tel'] = $receiver_address['cat']['d_tel'];
$data['d_address'] = $receiver_address['cat']['d_address'];
}
$ret = $this->sf_express_model->shipSample($data);
//$ret = [true];
if($ret[0]){
//快递id写到样品中
$this->sample_model->update(['ship_order_id'=>$ret[1],'step'=>Sample_model::STEP_SENT],'id in ('.implode(',',$sample_ids).')');
try{
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
//如果没关系,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_SENT,
null,
[
'first'=>'尊敬的用户:我们已为您分配了快递员,请保持手机畅通,快递员会尽快与您联系。',
'keyword1'=>implode(',',$data['device_id']),
//'keyword2'=>'上门取货后获取',
'keyword2'=>$ret[1],
'keyword3'=>'预估两小时内',
//'remark'=>'物流信息只能在中通官网查看,请保管好回寄单号方便日后物流查询。',
'remark'=>'我们已为您呼叫了顺丰速运,请耐心等待。物流信息可在“顺丰速运”公众号查看。',
]
);
}catch (Exception $e){
}
$this->success();
}else{
if (strpos($ret[1], '您的预约超出今日营业时间') !== false){
$this->error('快递营业时间:8-18点,现已超出今日营业时间,请于明日8点后进行预约取件。');
}else{
$this->error('快递未能使用,请添加微信号“uap_pet”咨询客服,错误信息:'.$ret[1]);
}
}
}
/*
if($data['name'] == '有哈'){
$this->load->model('sf_express_model');
$ret = $this->sf_express_model->shipSample($data);
}else{
$this->load->model('zto_model');
$ret = $this->zto_model->shipSample($data);
}*/
}
//进度查询:样品列表
public function list_get()
{
$ret = $this->sample_model->get($this->_user_id,'user_id',true);
$list = [];
if($ret)foreach ($ret as $item) {
//废弃的样品不呈现
if($item['step'] == Sample_model::STEP_DISCARD){
continue;
}
$item['step_fail'] = $item['step'] == Sample_model::STEP_UNQUALIFIED;
$list[] = $item;
}
$this->success($list);
}
//进度查询:样品进度详情
public function detail_get()
{
$config = array(
array(
'field' => 'id',
'label' => '样品ID',
'rules' => 'trim|required|min_length[4]|max_length[20]'
)
);
$this->load->library('form_validation');
$data = $this->input->get();
$this->form_validation->set_data($data);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() === FALSE)
{
$this->error('参数错误',$this->form_validation->error_array());
}
$sample = $this->sample_model->get(trim($data['id']),'device_id');
if($sample['user_id'] != $this->_user_id){
$this->error('您没有权限查看该样品');
}
if($sample['step'] == Sample_model::STEP_DISCARD){
$this->error('该样品已作废');
}
//获取摘要版的进度
$steps = $this->sample_model->step_summary;
//当前进度
$sample['step_desc'] = $steps[$sample['step']];
//成功与失败状态不能同时存在
$sample['step_fail'] = $sample['step'] == Sample_model::STEP_UNQUALIFIED;
if($sample['step_fail']){
//隐藏成功项目
unset($steps[Sample_model::STEP_DNA_EXTRACTED]);
}else{
//隐藏失败项目
unset($steps[Sample_model::STEP_UNQUALIFIED]);
}
//删除重复的进度
$steps = array_keys(array_flip($steps));
//当前在哪一个步骤
$sample['step_active'] = array_search($sample['step_desc'],$steps);
$sample['step_active_fail'] = $sample['step_fail'] ? $sample['step_active'] : -1;
//状态描述改成小描述
$sample['step_desc'] = $this->sample_model->step[$sample['step']];
//获取物流信息
$track = [];
$this->load->model('zto_model');
$ship_order = false;
//$ship_order = $this->zto_model->get(trim($sample['id']),'sample_id');
if($ship_order){
$track = $this->zto_model->traceInterfaceNewTraces($ship_order['order_code']);
}
$this->success([
'sample'=>$sample,
'ship_order'=>$ship_order,
//步骤需要提醒
'error_step'=>Sample_model::STEP_UNQUALIFIED,
'track'=>$track,
'steps'=>$steps,
]);
}
//升级样品:获取可升级的套餐
public function upgrade_post()
{
$config = array(
array(
'field' => 'id',
'label' => '样品ID',
'rules' => 'trim|required|min_length[4]|max_length[20]'
)
);
$data = $this->json_validation($config);
$sample = $this->sample_model->get(trim($data['id']),'device_id');
/*
if($sample['user_id'] != $this->_user_id){
$this->error('您没有权限查看该样品');
}*/
//查询可升级套餐,即同物种的更高价格的套餐
$packages = $this->package_model->get(trim($sample['pet_species']),'species',true);
$cur_package = null;
$up_packages = [];
foreach ($packages as $package) {
if($package['id'] == $sample['package_id']){
$cur_package = $package;
}else{
//只输出特定信息给用户前端
$up_packages[] = [
'id'=>$package['id'],
'name'=>$package['name'],
'description'=>$package['description'],
'price'=>$package['price']
];
}
}
if(is_null($cur_package)){
$this->error('样品原套餐信息丢失,暂不可升级');
}
//过滤比当前套餐价格低的套餐
foreach ($up_packages as $key=> $package) {
if($package['price'] <= $cur_package['price']){
unset($up_packages[$key]);
continue;
}
//输出升级差价
$up_packages[$key]['balance'] = round($package['price'] - $cur_package['price'],2);
}
if(empty($up_packages)){
$this->success();
}
//按照价格从低到高排序
array_multisort(array_column($up_packages,'price'),SORT_DESC,$up_packages);
$this->success(['packages'=>$up_packages]);
}
public function test_get(){
$this->load->library('uploads');
echo $this->uploads->get_upload_path();
}
}
+590
View File
@@ -0,0 +1,590 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use EasyWeChat\Foundation\Application as OfficialAccount;
class Active extends ApiController
{
function __construct()
{
header('Access-Control-Allow-Credentials: true');
parent::__construct();
//跨域
$this->load->library('session');
$this->load->model('series_number_model');
$this->load->model('package_model');
$this->load->model('sample_model');
$this->load->model('customer_model');
$this->checkUser();
}
public function ticket_get()
{
$conf = $this->config->item('weixin_uah');
$config = [
'app_id' => $conf['AppId'],
'secret' => $conf['AppSecert'],
'token' => $conf['Token'],
'aes_key' => $conf['EncodingAESKey'],
'response_type' => 'array',
];
$app = new OfficialAccount($config);
$url = $this->input->get('url');
if(!empty($url)){
$app->js->setUrl($url);
}else
if(!empty($_SERVER['HTTP_REFERER'])){
$app->js->setUrl($_SERVER['HTTP_REFERER']);
}
$config = $app->js->config(array('updateAppMessageShareData', 'updateTimelineShareData', 'scanQRCode'), $debug = false, $beta = false, $json = true);
$this->success(['config'=>json_decode($config)]);
}
public function check_number_post()
{
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[3]|max_length[20]'
),
);
$data = $this->json_validation($config);
$series = $this->series_number_model->get($data['device_id'],'device_id');
if(!$series){
$this->error('序列号不存在');
}
$sample = $this->sample_model->get($series['id'],'series_id');
if($sample){
$this->error('序列号已使用');
}
$package = $this->package_model->get($series['package_ori']);
if(!$package){
$this->error('序列号不可用,套餐信息不存在');
}
$content = empty($package['content'])?[]:json_decode($package['content'],true);
//获取所有疾病的名称
if(!empty($content)){
$disease_ids = [];
foreach ($content as $item) {
$disease_ids = array_merge($disease_ids,$item['disease_id']);
}
$this->load->model('disease_model');
$disease_list = $this->disease_model->get($disease_ids,'base.id',true);
$disease_map = [];
foreach ($disease_list as $val) {
$disease_map[$val['id']] = $val;
}
//疾病详情存到信息中
foreach ($content as $key=>$val) {
$val['disease_list'] = [];
foreach ($val['disease_id'] as $v) {
if(!isset($disease_map[$v])){
continue;
}
$val['disease_list'][] = $disease_map[$v];
}
$content[$key] = $val;
}
}
$package['content'] = $content;
$this->success(['package'=>$package]);
}
//新建样本
public function create_post()
{
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[4]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
'min_length' => '%s长度不足:%s.',
'max_length' => '%s长度不能超过:%s.',
),
),
array(
'field' => 'name',
'label' => '用户姓名',
'rules' => 'trim|required|min_length[1]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'tel',
'label' => '手机',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_name',
'label' => '宠物名称',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_sex',
'label' => '宠物性别',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_birthday',
'label' => '宠物生日',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:芯片号
array(
'field' => 'chip_number',
'label' => '芯片号',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:是否种猫
array(
'field' => 'is_breeding',
'label' => '是否种猫',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:血统认证机构
array(
'field' => 'lineage_cert_body',
'label' => '血统认证机构',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
)
);
$data = $this->json_validation($config);
$series = $this->series_number_model->get($data['device_id'],'device_id');
if(!$series){
$this->error('序列号不存在');
}
$sample = $this->sample_model->get($series['id'],'series_id');
if($sample){
$this->error('序列号已使用');
}
$package = $this->package_model->get($series['package_ori']);
if(!$package){
$this->error('套餐不存在');
}
//过滤字段
$fields = array_column($config,'field');
$entity = [];
foreach ($data as $key=>$val) {
if(in_array($key,$fields)){
$entity[$key] = $val;
}
}
unset($entity['device_id']);
//套餐是否要求选择疾病
$package['content'] = empty($package['content'])?[]:json_decode($package['content'],true);
//选择的疾病处理
if(!empty($package['content'])){
if(!isset($data['package_custom'])){
$this->error('请选择套餐选项');
}
//选择的选项是否允许选择
if(!isset($package['content'][$data['package_custom']])){
$this->error('您选择的套餐选项已失效');
}
$package_custom = $package['content'][$data['package_custom']];
//获取疾病的名称,保存起来,以免id变化
$this->load->model('disease_model');
$tmp = $this->disease_model->get($package_custom['disease_id'],'base.id',true);
$entity['package_custom'] = json_encode([
'id'=>$data['package_custom'],
'name'=>$package_custom['name'],
'disease_id'=>$package_custom['disease_id'],
'disease_name'=>array_column($tmp,'name')
],JSON_UNESCAPED_UNICODE);
}else{
$entity['package_custom'] = '';
}
//用户id
$entity['user_id'] = $this->_user_id;
//从device_id读取序列号ID
$entity['series_id'] = $series['id'];
//套餐
$entity['package_id'] = $series['package_ori'];
//套餐的猫狗写进样品,防止套餐变更造成影响
$entity['pet_species'] = $package['species'];
//头像处理
if(!empty($data['file']['content'])){
$imgBase64 = $data['file']['content'];
if(!empty($data['file']['ext'])){
//对于java接口,需要兼容前端的格式
$imgBase64 = 'data:image/'.trim($data['file']['ext']).';base64,'.$imgBase64;
}
$this->load->library('uploads');
//存原图
$pet_img = $this->uploads->save_pet_img_base64(
$imgBase64,
$data['device_id']
);
if($pet_img){
$entity['pet_img'] = $pet_img;
}
}
//绝育情况,如果没有传入则按“否”处理
if(empty($entity['is_sterilized'])){
$entity['is_sterilized'] = 0;
}
//处理宠物性别与绝育情况合并的情况(非繁育用户)
switch ($entity['pet_sex']){
case 1:
$entity['pet_sex'] = 1;
break;
case 2:
$entity['pet_sex'] = 2;
break;
case 3:
$entity['pet_sex'] = 1;
$entity['is_sterilized'] = 1;
break;
case 4:
$entity['pet_sex'] = 2;
$entity['is_sterilized'] = 1;
break;
default:
$entity['pet_sex'] = 1;
}
//步骤置为初始步骤
$entity['step'] = Sample_model::STEP_BIND;
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
$conf = $this->config->item('allowed_cors_origins');
try{
//如果没关注,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_ACTIVE,
base_url().'weixin/?url='.urlencode($conf['user'].'/ship'),
[
'first'=>'激活成功,如您还没选择回寄,请点击回寄',
'keyword1'=>$data['device_id'],
'keyword2'=>$package['name'],
'remark'=>'',
]
);
}catch (Exception $e){
}
//如果证书有多个,用逗号组合
if(is_array($entity['lineage_cert_body'])){
$entity['lineage_cert_body'] = implode(',',$entity['lineage_cert_body']);
}
$ret = $this->sample_model->add($entity);
/*
//保存一条样品流程处理信息
$this->load->model('sample_processing_model');
$this->sample_processing_model->add([
'sample_id'=>$ret,
'step'=>$entity['step']
]);
//保存一条样品套餐升级信息
$this->load->model('sample_upgrade_model');
$this->sample_upgrade_model->add([
'sample_id'=>$ret,
'package_id'=>$entity['package_id'],
'package_custom'=>$entity['package_custom']
]);
*/
if($ret){
//激活了繁育套餐的客户,用户信息修改
//if(!empty($package['is_breed'])){}
$this->success();
}else{
$this->error('提交失败');
}
}
//获取需回寄的样品
public function ship_get()
{
$ret = $this->sample_model->get($this->_user_id,'user_id',true);
//只展示需回寄样品
$un_ship = [];
foreach ($ret as $key=>$item) {
if($item['step'] < Sample_model::STEP_SENT){
$un_ship[] = $ret[$key];
}
}
$first = [];
//取第一个样品的信息
if(!empty($un_ship)){
$first = $un_ship[0];
}elseif(!empty($ret)){
$first = $ret[0];
}
$this->success(['sample'=>$un_ship,'info'=>$first]);
}
//样品回寄
public function ship_post()
{
$config = array(
array(
'field' => 'device_id[]',
'label' => '样品',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'name',
'label' => '姓名',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'tel',
'label' => '手机号',
'rules' => 'required'
),
array(
'field' => 'address',
'label' => '地址',
'rules' => 'required'
),
array(
'field' => 'province',
'label' => '省',
'rules' => 'required'
),
array(
'field' => 'city',
'label' => '市',
'rules' => 'required'
),
array(
'field' => 'district',
'label' => '区',
'rules' => 'required'
)
);
$data = $this->json_validation($config);
$sample_ids = [];
foreach ($data['device_id'] as $device_id) {
$sample = $this->sample_model->get($device_id,'device_id');
if($sample['user_id'] != $this->_user_id){
$this->error('该样品不在您名下');
}
$sample_ids[] = $sample['id'];
}
//创建订单
$data['user_id'] = $this->_user_id;
$data['trade_id'] = $data['device_id'][0];
/*
if($data['name'] == '有哈'){
$this->load->model('sf_express_model');
$ret = $this->sf_express_model->shipSample($data);
}else{
$this->load->model('zto_model');
$ret = $this->zto_model->shipSample($data);
}*/
$this->load->model('sf_express_model');
$ret = $this->sf_express_model->shipSample($data);
//$ret = [true];
if($ret[0]){
//快递id写到样品中
$this->sample_model->update(['ship_order_id'=>$ret[1],'step'=>Sample_model::STEP_SENT],'id in ('.implode(',',$sample_ids).')');
try{
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
//如果没关系,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_SENT,
null,
[
'first'=>'尊敬的用户:我们已为您分配了快递员,请保持手机畅通,快递员会尽快与您联系。',
'keyword1'=>implode(',',$data['device_id']),
//'keyword2'=>'上门取货后获取',
'keyword2'=>$ret[1],
'keyword3'=>'预估两小时内',
//'remark'=>'物流信息只能在中通官网查看,请保管好回寄单号方便日后物流查询。',
'remark'=>'我们已为您呼叫了顺丰速运,请耐心等待。物流信息可在“顺丰速运”公众号查看。',
]
);
}catch (Exception $e){
}
$this->success();
}else{
$this->error('快递未能使用,请添加微信号“uap_pet”咨询客服,错误信息:'.$ret[1]);
}
}
//进度查询:样品列表
public function list_get()
{
$ret = $this->sample_model->get($this->_user_id,'user_id',true);
$list = [];
if($ret)foreach ($ret as $item) {
//废弃的样品不呈现
if($item['step'] == Sample_model::STEP_DISCARD){
continue;
}
$item['step_fail'] = $item['step'] == Sample_model::STEP_UNQUALIFIED;
$list[] = $item;
}
$this->success($list);
}
//进度查询:样品进度详情
public function detail_get()
{
$config = array(
array(
'field' => 'id',
'label' => '样品ID',
'rules' => 'trim|required|min_length[4]|max_length[20]'
)
);
$this->load->library('form_validation');
$data = $this->input->get();
$this->form_validation->set_data($data);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() === FALSE)
{
$this->error('参数错误',$this->form_validation->error_array());
}
$sample = $this->sample_model->get(trim($data['id']),'device_id');
if($sample['user_id'] != $this->_user_id){
$this->error('您没有权限查看该样品');
}
if($sample['step'] == Sample_model::STEP_DISCARD){
$this->error('该样品已作废');
}
//获取摘要版的进度
$steps = $this->sample_model->step_summary;
//当前进度
$sample['step_desc'] = $steps[$sample['step']];
//成功与失败状态不能同时存在
$sample['step_fail'] = $sample['step'] == Sample_model::STEP_UNQUALIFIED;
if($sample['step_fail']){
//隐藏成功项目
unset($steps[Sample_model::STEP_DNA_EXTRACTED]);
}else{
//隐藏失败项目
unset($steps[Sample_model::STEP_UNQUALIFIED]);
}
//删除重复的进度
$steps = array_keys(array_flip($steps));
//当前在哪一个步骤
$sample['step_active'] = array_search($sample['step_desc'],$steps);
$sample['step_active_fail'] = $sample['step_fail'] ? $sample['step_active'] : -1;
//状态描述改成小描述
$sample['step_desc'] = $this->sample_model->step[$sample['step']];
//获取物流信息
$track = [];
$this->load->model('zto_model');
$ship_order = false;
//$ship_order = $this->zto_model->get(trim($sample['id']),'sample_id');
if($ship_order){
$track = $this->zto_model->traceInterfaceNewTraces($ship_order['order_code']);
}
$this->success([
'sample'=>$sample,
'ship_order'=>$ship_order,
//步骤需要提醒
'error_step'=>Sample_model::STEP_UNQUALIFIED,
'track'=>$track,
'steps'=>$steps,
]);
}
//升级样品:获取可升级的套餐
public function upgrade_post()
{
$config = array(
array(
'field' => 'id',
'label' => '样品ID',
'rules' => 'trim|required|min_length[4]|max_length[20]'
)
);
$data = $this->json_validation($config);
$sample = $this->sample_model->get(trim($data['id']),'device_id');
/*
if($sample['user_id'] != $this->_user_id){
$this->error('您没有权限查看该样品');
}*/
//查询可升级套餐,即同物种的更高价格的套餐
$packages = $this->package_model->get(trim($sample['pet_species']),'species',true);
$cur_package = null;
$up_packages = [];
foreach ($packages as $package) {
if($package['id'] == $sample['package_id']){
$cur_package = $package;
}else{
//只输出特定信息给用户前端
$up_packages[] = [
'id'=>$package['id'],
'name'=>$package['name'],
'description'=>$package['description'],
'price'=>$package['price']
];
}
}
if(is_null($cur_package)){
$this->error('样品原套餐信息丢失,暂不可升级');
}
//过滤比当前套餐价格低的套餐
foreach ($up_packages as $key=> $package) {
if($package['price'] <= $cur_package['price']){
unset($up_packages[$key]);
continue;
}
//输出升级差价
$up_packages[$key]['balance'] = round($package['price'] - $cur_package['price'],2);
}
if(empty($up_packages)){
$this->success();
}
//按照价格从低到高排序
array_multisort(array_column($up_packages,'price'),SORT_DESC,$up_packages);
$this->success(['packages'=>$up_packages]);
}
public function test_get(){
$this->load->library('uploads');
echo $this->uploads->get_upload_path();
}
}
+724
View File
@@ -0,0 +1,724 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use EasyWeChat\Foundation\Application as OfficialAccount;
class Active extends ApiController
{
function __construct()
{
header('Access-Control-Allow-Credentials: true');
parent::__construct();
//跨域
$this->load->library('session');
$this->load->model('series_number_model');
$this->load->model('package_model');
$this->load->model('sample_model');
$this->load->model('customer_model');
$this->checkUser();
}
public function ticket_get()
{
$conf = $this->config->item('weixin_uah');
$config = [
'app_id' => $conf['AppId'],
'secret' => $conf['AppSecert'],
'token' => $conf['Token'],
'aes_key' => $conf['EncodingAESKey'],
'response_type' => 'array',
];
$app = new OfficialAccount($config);
$url = $this->input->get('url');
if(!empty($url)){
$app->js->setUrl($url);
}else
if(!empty($_SERVER['HTTP_REFERER'])){
$app->js->setUrl($_SERVER['HTTP_REFERER']);
}
$config = $app->js->config(array('updateAppMessageShareData', 'updateTimelineShareData', 'scanQRCode'), $debug = false, $beta = false, $json = true);
$this->success(['config'=>json_decode($config)]);
}
public function check_number_post()
{
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[3]|max_length[20]'
),
);
$data = $this->json_validation($config);
$series = $this->series_number_model->get($data['device_id'],'device_id');
if(!$series){
$this->error('序列号不存在');
}
$sample = $this->sample_model->get($series['id'],'series_id');
if($sample){
$this->error('序列号已使用');
}
$package = $this->package_model->get($series['package_ori']);
if(!$package){
$this->error('序列号不可用,套餐信息不存在');
}
$content = empty($package['content'])?[]:json_decode($package['content'],true);
//获取所有疾病的名称
if(!empty($content)){
$disease_ids = [];
foreach ($content as $item) {
$disease_ids = array_merge($disease_ids,$item['disease_id']);
}
$this->load->model('disease_model');
$disease_list = $this->disease_model->get($disease_ids,'base.id',true);
$disease_map = [];
foreach ($disease_list as $val) {
$disease_map[$val['id']] = $val;
}
//疾病详情存到信息中
foreach ($content as $key=>$val) {
$val['disease_list'] = [];
foreach ($val['disease_id'] as $v) {
if(!isset($disease_map[$v])){
continue;
}
$val['disease_list'][] = $disease_map[$v];
}
$content[$key] = $val;
}
}
$package['content'] = $content;
$this->success(['package'=>$package]);
}
//新建样本
public function create_post()
{
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[4]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
'min_length' => '%s长度不足:%s.',
'max_length' => '%s长度不能超过:%s.',
),
),
array(
'field' => 'name',
'label' => '用户姓名',
'rules' => 'trim|required|min_length[1]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'tel',
'label' => '手机',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_name',
'label' => '宠物名称',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_sex',
'label' => '宠物性别',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_birthday',
'label' => '宠物生日',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:芯片号
array(
'field' => 'chip_number',
'label' => '芯片号',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:是否种猫
array(
'field' => 'is_breeding',
'label' => '是否种猫',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:血统认证机构
array(
'field' => 'lineage_cert_body',
'label' => '血统认证机构',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
)
);
$data = $this->json_validation($config);
$series = $this->series_number_model->get($data['device_id'],'device_id');
if(!$series){
$this->error('序列号不存在');
}
$sample = $this->sample_model->get($series['id'],'series_id');
if($sample){
$this->error('序列号已使用');
}
$package = $this->package_model->get($series['package_ori']);
if(!$package){
$this->error('套餐不存在');
}
//过滤字段
$fields = array_column($config,'field');
$entity = [];
foreach ($data as $key=>$val) {
if(in_array($key,$fields)){
$entity[$key] = $val;
}
}
unset($entity['device_id']);
//套餐是否要求选择疾病
$package['content'] = empty($package['content'])?[]:json_decode($package['content'],true);
//选择的疾病处理
if(!empty($package['content'])){
if(!isset($data['package_custom'])){
$this->error('请选择套餐选项');
}
//选择的选项是否允许选择
if(!isset($package['content'][$data['package_custom']])){
$this->error('您选择的套餐选项已失效');
}
$package_custom = $package['content'][$data['package_custom']];
//获取疾病的名称,保存起来,以免id变化
$this->load->model('disease_model');
$tmp = $this->disease_model->get($package_custom['disease_id'],'base.id',true);
$entity['package_custom'] = json_encode([
'id'=>$data['package_custom'],
'name'=>$package_custom['name'],
'disease_id'=>$package_custom['disease_id'],
'disease_name'=>array_column($tmp,'name')
],JSON_UNESCAPED_UNICODE);
}else{
$entity['package_custom'] = '';
}
//用户id
$entity['user_id'] = $this->_user_id;
//从device_id读取序列号ID
$entity['series_id'] = $series['id'];
//套餐
$entity['package_id'] = $series['package_ori'];
//套餐的猫狗写进样品,防止套餐变更造成影响
$entity['pet_species'] = $package['species'];
//头像处理
if(!empty($data['file']['content'])){
$imgBase64 = $data['file']['content'];
if(!empty($data['file']['ext'])){
//对于java接口,需要兼容前端的格式
$imgBase64 = 'data:image/'.trim($data['file']['ext']).';base64,'.$imgBase64;
}
$this->load->library('uploads');
//存原图
$pet_img = $this->uploads->save_pet_img_base64(
$imgBase64,
$data['device_id']
);
if($pet_img){
$entity['pet_img'] = $pet_img;
}
}
//绝育情况,如果没有传入则按“否”处理
if(empty($entity['is_sterilized'])){
$entity['is_sterilized'] = 0;
}
//处理宠物性别与绝育情况合并的情况(非繁育用户)
switch ($entity['pet_sex']){
case 1:
$entity['pet_sex'] = 1;
break;
case 2:
$entity['pet_sex'] = 2;
break;
case 3:
$entity['pet_sex'] = 1;
$entity['is_sterilized'] = 1;
break;
case 4:
$entity['pet_sex'] = 2;
$entity['is_sterilized'] = 1;
break;
default:
$entity['pet_sex'] = 1;
}
//步骤置为初始步骤
$entity['step'] = Sample_model::STEP_BIND;
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
$conf = $this->config->item('allowed_cors_origins');
try{
//如果没关注,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_ACTIVE,
base_url().'weixin/?url='.urlencode($conf['user'].'/ship'),
[
'first'=>'激活成功,如您还没选择回寄,请点击回寄',
'keyword1'=>$data['device_id'],
'keyword2'=>$package['name'],
'remark'=>'',
]
);
}catch (Exception $e){
}
//如果证书有多个,用逗号组合
if(is_array($entity['lineage_cert_body'])){
$entity['lineage_cert_body'] = implode(',',$entity['lineage_cert_body']);
}
$ret = $this->sample_model->add($entity);
/*
//保存一条样品流程处理信息
$this->load->model('sample_processing_model');
$this->sample_processing_model->add([
'sample_id'=>$ret,
'step'=>$entity['step']
]);
//保存一条样品套餐升级信息
$this->load->model('sample_upgrade_model');
$this->sample_upgrade_model->add([
'sample_id'=>$ret,
'package_id'=>$entity['package_id'],
'package_custom'=>$entity['package_custom']
]);
*/
if($ret){
//激活了繁育套餐的客户,用户信息修改
//if(!empty($package['is_breed'])){}
$this->success();
}else{
$this->error('提交失败');
}
}
//获取需回寄的样品
public function ship_get()
{
$ret = $this->sample_model->get($this->_user_id,'user_id',true);
//只展示需回寄样品
$un_ship = [];
foreach ($ret as $key=>$item) {
if($item['step'] < Sample_model::STEP_SENT){
$un_ship[] = $ret[$key];
}
}
$first = [];
//取第一个样品的信息
if(!empty($un_ship)){
$first = $un_ship[0];
}elseif(!empty($ret)){
$first = $ret[0];
}
$this->success(['sample'=>$un_ship,'info'=>$first]);
}
//样品回寄
public function ship_post()
{
$config = array(
array(
'field' => 'device_id[]',
'label' => '样品',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'name',
'label' => '姓名',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'tel',
'label' => '手机号',
'rules' => 'required'
),
array(
'field' => 'address',
'label' => '地址',
'rules' => 'required'
),
array(
'field' => 'province',
'label' => '省',
'rules' => 'required'
),
array(
'field' => 'city',
'label' => '市',
'rules' => 'required'
),
array(
'field' => 'district',
'label' => '区',
'rules' => 'required'
)
);
$receiver_address = array(
'cat' => array(
'd_province' => '广东省',
'd_city' => '深圳市',
'd_county' => '龙岗区',
'd_company' => '有哈科技',
'd_contact' => '有哈收样组(猫)王先生',
'd_tel' => '17596551135',
'd_address' => '大鹏新区布新路97号农科院基因组所A栋',
),
'dog' => array(
'd_province' => '江苏省',
'd_city' => '南京市',
'd_county' => '浦口区',
'd_company' => '有哈科技',
'd_contact' => '有哈收样组(犬)',
'd_tel' => '17751784617',
'd_address' => '行知路8号南京农创中心方舟实验室C栋南楼3层',
)
);
$data = $this->json_validation($config);
$sample_ids = [];
$dog_cat = [false, false];
$samples = array(
'cat' => [],
'cat_device_ids' =>[],
'dog' => [],
'dog_device_ids' =>[],
);
foreach ($data['device_id'] as $device_id) {
$sample = $this->sample_model->get($device_id,'device_id');
if($sample['user_id'] != $this->_user_id){
$this->error('该样品不在您名下');
}
if ($sample['pet_species'] == 1){
$dog_cat[0] = true;
$samples['dog'][] = $sample['id'];
$samples['dog_device_ids'][] = $device_id;
}else if ($sample['pet_species'] == 2){
$dog_cat[1] = true;
$samples['cat'][] = $sample['id'];
$samples['cat_device_ids'][] = $device_id;
}
$sample_ids[] = $sample['id'];
}
//创建订单
$data['user_id'] = $this->_user_id;
$this->load->model('sf_express_model');
if ($dog_cat[0] && $dog_cat[1]){
// $this->error("ship -> dog: $dog_cat[0], cat: $dog_cat[1]");
$data['d_province'] = $receiver_address['dog']['d_province'];
$data['d_city'] = $receiver_address['dog']['d_city'];
$data['d_county'] = $receiver_address['dog']['d_county'];
$data['d_company'] = $receiver_address['dog']['d_company'];
$data['d_contact'] = $receiver_address['dog']['d_contact'];
$data['d_tel'] = $receiver_address['dog']['d_tel'];
$data['d_address'] = $receiver_address['dog']['d_address'];
$data['trade_id'] = $samples['dog'][0];
$ret = $this->sf_express_model->shipSample($data);
//$ret = [true];
error_log("shipSample dog: $ret[0] $ret[1]");
if($ret[0]){
//快递id写到样品中
$this->sample_model->update(['ship_order_id'=>$ret[1],'step'=>Sample_model::STEP_SENT],'id in ('.implode(',',$samples['dog']).')');
try{
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
//如果没关系,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_SENT,
null,
[
'first'=>'尊敬的用户:我们已为您分配了快递员,请保持手机畅通,快递员会尽快与您联系。',
'keyword1'=>implode(',',$samples['dog_device_ids']),
//'keyword2'=>'上门取货后获取',
'keyword2'=>$ret[1],
'keyword3'=>'预估两小时内',
//'remark'=>'物流信息只能在中通官网查看,请保管好回寄单号方便日后物流查询。',
'remark'=>'我们已为您呼叫了顺丰速运,请耐心等待。物流信息可在“顺丰速运”公众号查看。',
]
);
}catch (Exception $e){
}
}else{
$this->error('快递未能使用,请添加微信号“uap_pet”咨询客服,错误信息:'.$ret[1]);
}
sleep(1);
$data['d_province'] = $receiver_address['cat']['d_province'];
$data['d_city'] = $receiver_address['cat']['d_city'];
$data['d_county'] = $receiver_address['cat']['d_county'];
$data['d_company'] = $receiver_address['cat']['d_company'];
$data['d_contact'] = $receiver_address['cat']['d_contact'];
$data['d_tel'] = $receiver_address['cat']['d_tel'];
$data['d_address'] = $receiver_address['cat']['d_address'];
$data['trade_id'] = $samples['cat'][0];
$ret = $this->sf_express_model->shipSample($data);
//$ret = [true];
error_log("shipSample cat: $ret[0] $ret[1]");
if($ret[0]){
//快递id写到样品中
$this->sample_model->update(['ship_order_id'=>$ret[1],'step'=>Sample_model::STEP_SENT],'id in ('.implode(',',$samples['dog']).')');
try{
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
//如果没关系,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_SENT,
null,
[
'first'=>'尊敬的用户:我们已为您分配了快递员,请保持手机畅通,快递员会尽快与您联系。',
'keyword1'=>implode(',',$samples['cat_device_ids']),
//'keyword2'=>'上门取货后获取',
'keyword2'=>$ret[1],
'keyword3'=>'预估两小时内',
//'remark'=>'物流信息只能在中通官网查看,请保管好回寄单号方便日后物流查询。',
'remark'=>'我们已为您呼叫了顺丰速运,请耐心等待。物流信息可在“顺丰速运”公众号查看。',
]
);
}catch (Exception $e){
}
$this->success();
}else{
$this->error('快递未能使用,请添加微信号“uap_pet”咨询客服,错误信息:'.$ret[1]);
}
}else if ($dog_cat[1] || $dog_cat[0]){
$data['trade_id'] = $data['device_id'][0];
if ($dog_cat[0]){
$data['d_province'] = $receiver_address['dog']['d_province'];
$data['d_city'] = $receiver_address['dog']['d_city'];
$data['d_county'] = $receiver_address['dog']['d_county'];
$data['d_company'] = $receiver_address['dog']['d_company'];
$data['d_contact'] = $receiver_address['dog']['d_contact'];
$data['d_tel'] = $receiver_address['dog']['d_tel'];
$data['d_address'] = $receiver_address['dog']['d_address'];
}else{
$data['d_province'] = $receiver_address['cat']['d_province'];
$data['d_city'] = $receiver_address['cat']['d_city'];
$data['d_county'] = $receiver_address['cat']['d_county'];
$data['d_company'] = $receiver_address['cat']['d_company'];
$data['d_contact'] = $receiver_address['cat']['d_contact'];
$data['d_tel'] = $receiver_address['cat']['d_tel'];
$data['d_address'] = $receiver_address['cat']['d_address'];
}
$ret = $this->sf_express_model->shipSample($data);
//$ret = [true];
if($ret[0]){
//快递id写到样品中
$this->sample_model->update(['ship_order_id'=>$ret[1],'step'=>Sample_model::STEP_SENT],'id in ('.implode(',',$sample_ids).')');
try{
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
//如果没关系,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_SENT,
null,
[
'first'=>'尊敬的用户:我们已为您分配了快递员,请保持手机畅通,快递员会尽快与您联系。',
'keyword1'=>implode(',',$data['device_id']),
//'keyword2'=>'上门取货后获取',
'keyword2'=>$ret[1],
'keyword3'=>'预估两小时内',
//'remark'=>'物流信息只能在中通官网查看,请保管好回寄单号方便日后物流查询。',
'remark'=>'我们已为您呼叫了顺丰速运,请耐心等待。物流信息可在“顺丰速运”公众号查看。',
]
);
}catch (Exception $e){
}
$this->success();
}else{
$this->error('快递未能使用,请添加微信号“uap_pet”咨询客服,错误信息:'.$ret[1]);
}
}
/*
if($data['name'] == '有哈'){
$this->load->model('sf_express_model');
$ret = $this->sf_express_model->shipSample($data);
}else{
$this->load->model('zto_model');
$ret = $this->zto_model->shipSample($data);
}*/
}
//进度查询:样品列表
public function list_get()
{
$ret = $this->sample_model->get($this->_user_id,'user_id',true);
$list = [];
if($ret)foreach ($ret as $item) {
//废弃的样品不呈现
if($item['step'] == Sample_model::STEP_DISCARD){
continue;
}
$item['step_fail'] = $item['step'] == Sample_model::STEP_UNQUALIFIED;
$list[] = $item;
}
$this->success($list);
}
//进度查询:样品进度详情
public function detail_get()
{
$config = array(
array(
'field' => 'id',
'label' => '样品ID',
'rules' => 'trim|required|min_length[4]|max_length[20]'
)
);
$this->load->library('form_validation');
$data = $this->input->get();
$this->form_validation->set_data($data);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() === FALSE)
{
$this->error('参数错误',$this->form_validation->error_array());
}
$sample = $this->sample_model->get(trim($data['id']),'device_id');
if($sample['user_id'] != $this->_user_id){
$this->error('您没有权限查看该样品');
}
if($sample['step'] == Sample_model::STEP_DISCARD){
$this->error('该样品已作废');
}
//获取摘要版的进度
$steps = $this->sample_model->step_summary;
//当前进度
$sample['step_desc'] = $steps[$sample['step']];
//成功与失败状态不能同时存在
$sample['step_fail'] = $sample['step'] == Sample_model::STEP_UNQUALIFIED;
if($sample['step_fail']){
//隐藏成功项目
unset($steps[Sample_model::STEP_DNA_EXTRACTED]);
}else{
//隐藏失败项目
unset($steps[Sample_model::STEP_UNQUALIFIED]);
}
//删除重复的进度
$steps = array_keys(array_flip($steps));
//当前在哪一个步骤
$sample['step_active'] = array_search($sample['step_desc'],$steps);
$sample['step_active_fail'] = $sample['step_fail'] ? $sample['step_active'] : -1;
//状态描述改成小描述
$sample['step_desc'] = $this->sample_model->step[$sample['step']];
//获取物流信息
$track = [];
$this->load->model('zto_model');
$ship_order = false;
//$ship_order = $this->zto_model->get(trim($sample['id']),'sample_id');
if($ship_order){
$track = $this->zto_model->traceInterfaceNewTraces($ship_order['order_code']);
}
$this->success([
'sample'=>$sample,
'ship_order'=>$ship_order,
//步骤需要提醒
'error_step'=>Sample_model::STEP_UNQUALIFIED,
'track'=>$track,
'steps'=>$steps,
]);
}
//升级样品:获取可升级的套餐
public function upgrade_post()
{
$config = array(
array(
'field' => 'id',
'label' => '样品ID',
'rules' => 'trim|required|min_length[4]|max_length[20]'
)
);
$data = $this->json_validation($config);
$sample = $this->sample_model->get(trim($data['id']),'device_id');
/*
if($sample['user_id'] != $this->_user_id){
$this->error('您没有权限查看该样品');
}*/
//查询可升级套餐,即同物种的更高价格的套餐
$packages = $this->package_model->get(trim($sample['pet_species']),'species',true);
$cur_package = null;
$up_packages = [];
foreach ($packages as $package) {
if($package['id'] == $sample['package_id']){
$cur_package = $package;
}else{
//只输出特定信息给用户前端
$up_packages[] = [
'id'=>$package['id'],
'name'=>$package['name'],
'description'=>$package['description'],
'price'=>$package['price']
];
}
}
if(is_null($cur_package)){
$this->error('样品原套餐信息丢失,暂不可升级');
}
//过滤比当前套餐价格低的套餐
foreach ($up_packages as $key=> $package) {
if($package['price'] <= $cur_package['price']){
unset($up_packages[$key]);
continue;
}
//输出升级差价
$up_packages[$key]['balance'] = round($package['price'] - $cur_package['price'],2);
}
if(empty($up_packages)){
$this->success();
}
//按照价格从低到高排序
array_multisort(array_column($up_packages,'price'),SORT_DESC,$up_packages);
$this->success(['packages'=>$up_packages]);
}
public function test_get(){
$this->load->library('uploads');
echo $this->uploads->get_upload_path();
}
}
+739
View File
@@ -0,0 +1,739 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use EasyWeChat\Foundation\Application as OfficialAccount;
class Active extends ApiController
{
function __construct()
{
header('Access-Control-Allow-Credentials: true');
parent::__construct();
//跨域
$this->load->library('session');
$this->load->model('series_number_model');
$this->load->model('package_model');
$this->load->model('sample_model');
$this->load->model('customer_model');
$this->checkUser();
}
public function ticket_get()
{
$conf = $this->config->item('weixin_uah');
$config = [
'app_id' => $conf['AppId'],
'secret' => $conf['AppSecert'],
'token' => $conf['Token'],
'aes_key' => $conf['EncodingAESKey'],
'response_type' => 'array',
];
$app = new OfficialAccount($config);
$url = $this->input->get('url');
if(!empty($url)){
$app->js->setUrl($url);
}else
if(!empty($_SERVER['HTTP_REFERER'])){
$app->js->setUrl($_SERVER['HTTP_REFERER']);
}
$config = $app->js->config(array('updateAppMessageShareData', 'updateTimelineShareData', 'scanQRCode'), $debug = false, $beta = false, $json = true);
$this->success(['config'=>json_decode($config)]);
}
public function check_number_post()
{
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[3]|max_length[20]'
),
);
$data = $this->json_validation($config);
$series = $this->series_number_model->get($data['device_id'],'device_id');
if(!$series){
$this->error('请联系【店铺】在线客服绑定序列号');
}
$sample = $this->sample_model->get($series['id'],'series_id');
if($sample){
$this->error('序列号已使用');
}
$package = $this->package_model->get($series['package_ori']);
if(!$package){
$this->error('序列号不可用,套餐信息不存在');
}
$content = empty($package['content'])?[]:json_decode($package['content'],true);
//获取所有疾病的名称
if(!empty($content)){
$disease_ids = [];
foreach ($content as $item) {
$disease_ids = array_merge($disease_ids,$item['disease_id']);
}
$this->load->model('disease_model');
$disease_list = $this->disease_model->get($disease_ids,'base.id',true);
$disease_map = [];
foreach ($disease_list as $val) {
$disease_map[$val['id']] = $val;
}
//疾病详情存到信息中
foreach ($content as $key=>$val) {
$val['disease_list'] = [];
foreach ($val['disease_id'] as $v) {
if(!isset($disease_map[$v])){
continue;
}
$val['disease_list'][] = $disease_map[$v];
}
$content[$key] = $val;
}
}
$package['content'] = $content;
$this->success(['package'=>$package]);
}
//新建样本
public function create_post()
{
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[4]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
'min_length' => '%s长度不足:%s.',
'max_length' => '%s长度不能超过:%s.',
),
),
array(
'field' => 'name',
'label' => '用户姓名',
'rules' => 'trim|required|min_length[1]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'tel',
'label' => '手机',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_name',
'label' => '宠物名称',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_sex',
'label' => '宠物性别',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'pet_birthday',
'label' => '宠物生日',
'rules' => 'required',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:芯片号
array(
'field' => 'chip_number',
'label' => '芯片号',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:是否种猫
array(
'field' => 'is_breeding',
'label' => '是否种猫',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
//繁育:血统认证机构
array(
'field' => 'lineage_cert_body',
'label' => '血统认证机构',
'rules' => 'trim',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
)
);
$data = $this->json_validation($config);
$series = $this->series_number_model->get($data['device_id'],'device_id');
if(!$series){
$this->error('序列号不存在');
}
$sample = $this->sample_model->get($series['id'],'series_id');
if($sample){
$this->error('序列号已使用');
}
$package = $this->package_model->get($series['package_ori']);
if(!$package){
$this->error('套餐不存在');
}
//过滤字段
$fields = array_column($config,'field');
$entity = [];
foreach ($data as $key=>$val) {
if(in_array($key,$fields)){
$entity[$key] = $val;
}
}
unset($entity['device_id']);
//套餐是否要求选择疾病
$package['content'] = empty($package['content'])?[]:json_decode($package['content'],true);
//选择的疾病处理
if(!empty($package['content'])){
if(!isset($data['package_custom'])){
$this->error('请选择套餐选项');
}
//选择的选项是否允许选择
if(!isset($package['content'][$data['package_custom']])){
$this->error('您选择的套餐选项已失效');
}
$package_custom = $package['content'][$data['package_custom']];
//获取疾病的名称,保存起来,以免id变化
$this->load->model('disease_model');
$tmp = $this->disease_model->get($package_custom['disease_id'],'base.id',true);
$entity['package_custom'] = json_encode([
'id'=>$data['package_custom'],
'name'=>$package_custom['name'],
'disease_id'=>$package_custom['disease_id'],
'disease_name'=>array_column($tmp,'name')
],JSON_UNESCAPED_UNICODE);
}else{
$entity['package_custom'] = '';
}
//用户id
$entity['user_id'] = $this->_user_id;
//从device_id读取序列号ID
$entity['series_id'] = $series['id'];
//套餐
$entity['package_id'] = $series['package_ori'];
//套餐的猫狗写进样品,防止套餐变更造成影响
$entity['pet_species'] = $package['species'];
//头像处理
if(!empty($data['file']['content'])){
$imgBase64 = $data['file']['content'];
if(!empty($data['file']['ext'])){
//对于java接口,需要兼容前端的格式
$imgBase64 = 'data:image/'.trim($data['file']['ext']).';base64,'.$imgBase64;
}
$this->load->library('uploads');
//存原图
$pet_img = $this->uploads->save_pet_img_base64(
$imgBase64,
$data['device_id']
);
if($pet_img){
$entity['pet_img'] = $pet_img;
}
}
//绝育情况,如果没有传入则按“否”处理
if(empty($entity['is_sterilized'])){
$entity['is_sterilized'] = 0;
}
//处理宠物性别与绝育情况合并的情况(非繁育用户)
switch ($entity['pet_sex']){
case 1:
$entity['pet_sex'] = 1;
break;
case 2:
$entity['pet_sex'] = 2;
break;
case 3:
$entity['pet_sex'] = 1;
$entity['is_sterilized'] = 1;
break;
case 4:
$entity['pet_sex'] = 2;
$entity['is_sterilized'] = 1;
break;
default:
$entity['pet_sex'] = 1;
}
//步骤置为初始步骤
$entity['step'] = Sample_model::STEP_BIND;
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
$conf = $this->config->item('allowed_cors_origins');
try{
//如果没关注,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_ACTIVE,
base_url().'weixin/?url='.urlencode($conf['user'].'/ship'),
[
'first'=>'激活成功,如您还没选择回寄,请点击回寄',
'keyword1'=>$data['device_id'],
'keyword2'=>$package['name'],
'remark'=>'',
]
);
}catch (Exception $e){
}
//如果证书有多个,用逗号组合
if(is_array($entity['lineage_cert_body'])){
$entity['lineage_cert_body'] = implode(',',$entity['lineage_cert_body']);
}
$ret = $this->sample_model->add($entity);
/*
//保存一条样品流程处理信息
$this->load->model('sample_processing_model');
$this->sample_processing_model->add([
'sample_id'=>$ret,
'step'=>$entity['step']
]);
//保存一条样品套餐升级信息
$this->load->model('sample_upgrade_model');
$this->sample_upgrade_model->add([
'sample_id'=>$ret,
'package_id'=>$entity['package_id'],
'package_custom'=>$entity['package_custom']
]);
*/
if($ret){
//激活了繁育套餐的客户,用户信息修改
//if(!empty($package['is_breed'])){}
$this->success();
}else{
$this->error('提交失败');
}
}
//获取需回寄的样品
public function ship_get()
{
$ret = $this->sample_model->get($this->_user_id,'user_id',true);
//只展示需回寄样品
$un_ship = [];
foreach ($ret as $key=>$item) {
if($item['step'] < Sample_model::STEP_SENT){
$un_ship[] = $ret[$key];
}
}
$first = [];
//取第一个样品的信息
if(!empty($un_ship)){
$first = $un_ship[0];
}elseif(!empty($ret)){
$first = $ret[0];
}
$this->success(['sample'=>$un_ship,'info'=>$first]);
}
//样品回寄
public function ship_post()
{
$config = array(
array(
'field' => 'device_id[]',
'label' => '样品',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'name',
'label' => '姓名',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
),
array(
'field' => 'tel',
'label' => '手机号',
'rules' => 'required'
),
array(
'field' => 'address',
'label' => '地址',
'rules' => 'required'
),
array(
'field' => 'province',
'label' => '省',
'rules' => 'required'
),
array(
'field' => 'city',
'label' => '市',
'rules' => 'required'
),
array(
'field' => 'district',
'label' => '区',
'rules' => 'required'
)
);
$receiver_address = array(
'cat' => array(
'd_province' => '江苏省',
'd_city' => '南京市',
'd_county' => '浦口区',
'd_company' => '有哈科技',
'd_contact' => '有哈收样组',
'd_tel' => '17751784617',
'd_address' => '行知路8号南京农创中心方舟实验室C栋南楼3层',
),
'dog' => array(
'd_province' => '江苏省',
'd_city' => '南京市',
'd_county' => '浦口区',
'd_company' => '有哈科技',
'd_contact' => '有哈收样组',
'd_tel' => '17751784617',
'd_address' => '行知路8号南京农创中心方舟实验室C栋南楼3层',
)
);
$data = $this->json_validation($config);
$sample_ids = [];
$dog_cat = [false, false];
$samples = array(
'cat' => [],
'cat_device_ids' =>[],
'dog' => [],
'dog_device_ids' =>[],
);
foreach ($data['device_id'] as $device_id) {
$sample = $this->sample_model->get($device_id,'device_id');
if($sample['user_id'] != $this->_user_id){
$this->error('该样品不在您名下');
}
if ($sample['pet_species'] == 1){
$dog_cat[0] = true;
$samples['dog'][] = $sample['id'];
$samples['dog_device_ids'][] = $device_id;
}else if ($sample['pet_species'] == 2){
$dog_cat[1] = true;
$samples['cat'][] = $sample['id'];
$samples['cat_device_ids'][] = $device_id;
}
$sample_ids[] = $sample['id'];
}
//创建订单
$data['user_id'] = $this->_user_id;
$this->load->model('sf_express_model');
if ($dog_cat[0] && $dog_cat[1]){
// $this->error("ship -> dog: $dog_cat[0], cat: $dog_cat[1]");
$data['d_province'] = $receiver_address['dog']['d_province'];
$data['d_city'] = $receiver_address['dog']['d_city'];
$data['d_county'] = $receiver_address['dog']['d_county'];
$data['d_company'] = $receiver_address['dog']['d_company'];
$data['d_contact'] = $receiver_address['dog']['d_contact'];
$data['d_tel'] = $receiver_address['dog']['d_tel'];
$data['d_address'] = $receiver_address['dog']['d_address'];
$data['trade_id'] = $samples['dog'][0];
$ret = $this->sf_express_model->shipSample($data);
//$ret = [true];
error_log("shipSample dog: $ret[0] $ret[1]");
if($ret[0]){
//快递id写到样品中
$this->sample_model->update(['ship_order_id'=>$ret[1],'step'=>Sample_model::STEP_SENT],'id in ('.implode(',',$samples['dog']).')');
try{
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
//如果没关系,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_SENT,
null,
[
'first'=>'尊敬的用户:我们已为您分配了快递员,请保持手机畅通,快递员会尽快与您联系。',
'keyword1'=>implode(',',$samples['dog_device_ids']),
//'keyword2'=>'上门取货后获取',
'keyword2'=>$ret[1],
'keyword3'=>'预估两小时内',
//'remark'=>'物流信息只能在中通官网查看,请保管好回寄单号方便日后物流查询。',
'remark'=>'我们已为您呼叫了顺丰速运,请耐心等待。物流信息可在“顺丰速运”公众号查看。',
]
);
}catch (Exception $e){
}
}else{
if (strpos($ret[1], '您的预约超出今日营业时间') !== false){
$this->error('快递营业时间:8-18点,现已超出今日营业时间,请于明日8点后进行预约取件。');
}else{
$this->error('快递未能使用,请添加微信号“uap_pet”咨询客服,错误信息:'.$ret[1]);
}
}
sleep(1);
$data['d_province'] = $receiver_address['cat']['d_province'];
$data['d_city'] = $receiver_address['cat']['d_city'];
$data['d_county'] = $receiver_address['cat']['d_county'];
$data['d_company'] = $receiver_address['cat']['d_company'];
$data['d_contact'] = $receiver_address['cat']['d_contact'];
$data['d_tel'] = $receiver_address['cat']['d_tel'];
$data['d_address'] = $receiver_address['cat']['d_address'];
$data['trade_id'] = $samples['cat'][0];
$ret = $this->sf_express_model->shipSample($data);
//$ret = [true];
error_log("shipSample cat: $ret[0] $ret[1]");
if($ret[0]){
//快递id写到样品中
$this->sample_model->update(['ship_order_id'=>$ret[1],'step'=>Sample_model::STEP_SENT],'id in ('.implode(',',$samples['dog']).')');
try{
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
//如果没关系,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_SENT,
null,
[
'first'=>'尊敬的用户:我们已为您分配了快递员,请保持手机畅通,快递员会尽快与您联系。',
'keyword1'=>implode(',',$samples['cat_device_ids']),
//'keyword2'=>'上门取货后获取',
'keyword2'=>$ret[1],
'keyword3'=>'预估两小时内',
//'remark'=>'物流信息只能在中通官网查看,请保管好回寄单号方便日后物流查询。',
'remark'=>'我们已为您呼叫了顺丰速运,请耐心等待。物流信息可在“顺丰速运”公众号查看。',
]
);
}catch (Exception $e){
}
$this->success();
}else{
if (strpos($ret[1], '您的预约超出今日营业时间') !== false){
$this->error('快递营业时间:8-18点,现已超出今日营业时间,请于明日8点后进行预约取件。');
}else{
$this->error('快递未能使用,请添加微信号“uap_pet”咨询客服,错误信息:'.$ret[1]);
}
}
}else if ($dog_cat[1] || $dog_cat[0]){
$data['trade_id'] = $data['device_id'][0];
if ($dog_cat[0]){
$data['d_province'] = $receiver_address['dog']['d_province'];
$data['d_city'] = $receiver_address['dog']['d_city'];
$data['d_county'] = $receiver_address['dog']['d_county'];
$data['d_company'] = $receiver_address['dog']['d_company'];
$data['d_contact'] = $receiver_address['dog']['d_contact'];
$data['d_tel'] = $receiver_address['dog']['d_tel'];
$data['d_address'] = $receiver_address['dog']['d_address'];
}else{
$data['d_province'] = $receiver_address['cat']['d_province'];
$data['d_city'] = $receiver_address['cat']['d_city'];
$data['d_county'] = $receiver_address['cat']['d_county'];
$data['d_company'] = $receiver_address['cat']['d_company'];
$data['d_contact'] = $receiver_address['cat']['d_contact'];
$data['d_tel'] = $receiver_address['cat']['d_tel'];
$data['d_address'] = $receiver_address['cat']['d_address'];
}
$ret = $this->sf_express_model->shipSample($data);
//$ret = [true];
if($ret[0]){
//快递id写到样品中
$this->sample_model->update(['ship_order_id'=>$ret[1],'step'=>Sample_model::STEP_SENT],'id in ('.implode(',',$sample_ids).')');
try{
//发送微信通知
$this->load->model('weixin_message_model');
$user = $this->customer_model->get($this->_user_id);
//如果没关系,会抛出错误,忽略
$this->weixin_message_model->send(
$user['openid'],
Weixin_message_model::TEMPLATE_SENT,
null,
[
'first'=>'尊敬的用户:我们已为您分配了快递员,请保持手机畅通,快递员会尽快与您联系。',
'keyword1'=>implode(',',$data['device_id']),
//'keyword2'=>'上门取货后获取',
'keyword2'=>$ret[1],
'keyword3'=>'预估两小时内',
//'remark'=>'物流信息只能在中通官网查看,请保管好回寄单号方便日后物流查询。',
'remark'=>'我们已为您呼叫了顺丰速运,请耐心等待。物流信息可在“顺丰速运”公众号查看。',
]
);
}catch (Exception $e){
}
$this->success();
}else{
if (strpos($ret[1], '您的预约超出今日营业时间') !== false){
$this->error('快递营业时间:8-18点,现已超出今日营业时间,请于明日8点后进行预约取件。');
}else{
$this->error('快递未能使用,请添加微信号“uap_pet”咨询客服,错误信息:'.$ret[1]);
}
}
}
/*
if($data['name'] == '有哈'){
$this->load->model('sf_express_model');
$ret = $this->sf_express_model->shipSample($data);
}else{
$this->load->model('zto_model');
$ret = $this->zto_model->shipSample($data);
}*/
}
//进度查询:样品列表
public function list_get()
{
$ret = $this->sample_model->get($this->_user_id,'user_id',true);
$list = [];
if($ret)foreach ($ret as $item) {
//废弃的样品不呈现
if($item['step'] == Sample_model::STEP_DISCARD){
continue;
}
$item['step_fail'] = $item['step'] == Sample_model::STEP_UNQUALIFIED;
$list[] = $item;
}
$this->success($list);
}
//进度查询:样品进度详情
public function detail_get()
{
$config = array(
array(
'field' => 'id',
'label' => '样品ID',
'rules' => 'trim|required|min_length[4]|max_length[20]'
)
);
$this->load->library('form_validation');
$data = $this->input->get();
$this->form_validation->set_data($data);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() === FALSE)
{
$this->error('参数错误',$this->form_validation->error_array());
}
$sample = $this->sample_model->get(trim($data['id']),'device_id');
if($sample['user_id'] != $this->_user_id){
$this->error('您没有权限查看该样品');
}
if($sample['step'] == Sample_model::STEP_DISCARD){
$this->error('该样品已作废');
}
//获取摘要版的进度
$steps = $this->sample_model->step_summary;
//当前进度
$sample['step_desc'] = $steps[$sample['step']];
//成功与失败状态不能同时存在
$sample['step_fail'] = $sample['step'] == Sample_model::STEP_UNQUALIFIED;
if($sample['step_fail']){
//隐藏成功项目
unset($steps[Sample_model::STEP_DNA_EXTRACTED]);
}else{
//隐藏失败项目
unset($steps[Sample_model::STEP_UNQUALIFIED]);
}
//删除重复的进度
$steps = array_keys(array_flip($steps));
//当前在哪一个步骤
$sample['step_active'] = array_search($sample['step_desc'],$steps);
$sample['step_active_fail'] = $sample['step_fail'] ? $sample['step_active'] : -1;
//状态描述改成小描述
$sample['step_desc'] = $this->sample_model->step[$sample['step']];
//获取物流信息
$track = [];
$this->load->model('zto_model');
$ship_order = false;
//$ship_order = $this->zto_model->get(trim($sample['id']),'sample_id');
if($ship_order){
$track = $this->zto_model->traceInterfaceNewTraces($ship_order['order_code']);
}
$this->success([
'sample'=>$sample,
'ship_order'=>$ship_order,
//步骤需要提醒
'error_step'=>Sample_model::STEP_UNQUALIFIED,
'track'=>$track,
'steps'=>$steps,
]);
}
//升级样品:获取可升级的套餐
public function upgrade_post()
{
$config = array(
array(
'field' => 'id',
'label' => '样品ID',
'rules' => 'trim|required|min_length[4]|max_length[20]'
)
);
$data = $this->json_validation($config);
$sample = $this->sample_model->get(trim($data['id']),'device_id');
/*
if($sample['user_id'] != $this->_user_id){
$this->error('您没有权限查看该样品');
}*/
//查询可升级套餐,即同物种的更高价格的套餐
$packages = $this->package_model->get(trim($sample['pet_species']),'species',true);
$cur_package = null;
$up_packages = [];
foreach ($packages as $package) {
if($package['id'] == $sample['package_id']){
$cur_package = $package;
}else{
//只输出特定信息给用户前端
$up_packages[] = [
'id'=>$package['id'],
'name'=>$package['name'],
'description'=>$package['description'],
'price'=>$package['price']
];
}
}
if(is_null($cur_package)){
$this->error('样品原套餐信息丢失,暂不可升级');
}
//过滤比当前套餐价格低的套餐
foreach ($up_packages as $key=> $package) {
if($package['price'] <= $cur_package['price']){
unset($up_packages[$key]);
continue;
}
//输出升级差价
$up_packages[$key]['balance'] = round($package['price'] - $cur_package['price'],2);
}
if(empty($up_packages)){
$this->success();
}
//按照价格从低到高排序
array_multisort(array_column($up_packages,'price'),SORT_DESC,$up_packages);
$this->success(['packages'=>$up_packages]);
}
public function test_get(){
$this->load->library('uploads');
echo $this->uploads->get_upload_path();
}
}
+229
View File
@@ -0,0 +1,229 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Breeding extends ApiController
{
function __construct()
{
header('Access-Control-Allow-Credentials: true');
parent::__construct();
//跨域
$this->load->library('session');
$this->load->model('customer_model');
//$this->session->{Customer_model::SESSION_KEY} = 1;
$this->checkUser();
}
//获取繁育人信息
public function info_get(){
$row = $this->customer_model->get($this->_user_id);
//统计数量
$this->load->model('sample_model');
$this->load->model('breeding_plan_model');
$row['total_sample'] = $this->sample_model->getUserTotal($this->_user_id);
$row['total_breeding_plan'] = $this->breeding_plan_model->getUserTotal($this->_user_id);
$this->success($row);
}
//获取种猫/犬
public function candidate_post(){
$this->load->model('sample_model');
$this->load->model('report_model');
$data = $this->json_input();
$ids = [];
if(!empty($data['tree']) && is_array($data['tree'])){
$ids = $this->_getTreeSampleIds($data['tree']);
}
$pet_sex = empty($data['pet_sex'])?0:(int)$data['pet_sex'];
$pet_species = empty($data['pet_species'])?0:(int)$data['pet_species'];
$list = $this->sample_model->getBreeding($this->_user_id,$ids,$pet_species,$pet_sex,100);
$ret = [];
foreach ($list as $val) {
$reportJson = $this->report_model->get_report_json($val['device_id'],$val['pet_species']);
$ret[] = $this->_getCandidateItem($val,$reportJson);
}
$this->success($ret);
}
//繁育计划保存
public function plan_save_post()
{
$data = $this->json_input();
if(empty($data['tree'])){
$this->error('参数不完整');
}
$tree = $data['tree'];
//保存孩子的样本id
$children_ids = [];
foreach ($tree['children'] as $item) {
if(!empty($item['id'])){
$children_ids[] = $item['id'];
}
}
//雌性
$female_id = !empty($tree['female']['self']['id'])?(int)$tree['female']['self']['id']:0;
$female_father_id = !empty($tree['female']['father']['id'])?(int)$tree['female']['father']['id']:0;
$female_mother_id = !empty($tree['female']['mother']['id'])?(int)$tree['female']['mother']['id']:0;
//雄性
$male_id = !empty($tree['male']['self']['id'])?(int)$tree['male']['self']['id']:0;
$male_father_id = !empty($tree['male']['father']['id'])?(int)$tree['male']['father']['id']:0;
$male_mother_id = !empty($tree['male']['mother']['id'])?(int)$tree['male']['mother']['id']:0;
if(empty($female_id) || empty($male_id)){
$this->error('关系不完整');
}
$this->load->model('breeding_plan_model');
$entity = [
'children_ids' => implode(',',$children_ids),
'user_id' => $this->_user_id,
'female_id' => $female_id,
'female_father_id' => $female_father_id,
'female_mother_id' => $female_mother_id,
'male_id' => $male_id,
'male_father_id' => $male_father_id,
'male_mother_id' => $male_mother_id,
];
if(empty($data['id'])){
$this->breeding_plan_model->add($entity);
}else{
$this->breeding_plan_model->update($entity,[
'id'=>$data['id']
]);
}
$this->success('保存成功');
}
//繁育计划列表
public function list_get()
{
$this->load->model('breeding_plan_model');
$ret = $this->breeding_plan_model->get($this->_user_id,'user_id',true);
$list = [];
if($ret){
//获取所有相关样品
$sample_ids = [];
foreach ($ret as $item) {
$sample_ids[] = $item['male_id'];
$sample_ids[] = $item['female_id'];
}
$this->load->model('sample_model');
//根据id获取样本信息
$samples = $this->sample_model->getByUserIds($sample_ids);
$sample_map = [];
foreach ($samples as $item) {
$this->sample_model->format($item);
$sample_map[$item['id']] = $item;
}
//格式化信息
foreach ($ret as $item) {
$male = [
'name'=>$sample_map[$item['male_id']]['pet_name'],
'pet_img'=>$sample_map[$item['male_id']]['pet_img'],
'device_id'=>$sample_map[$item['male_id']]['device_id'],
];
$female = [
'name'=>$sample_map[$item['female_id']]['pet_name'],
'pet_img'=>$sample_map[$item['female_id']]['pet_img'],
'device_id'=>$sample_map[$item['female_id']]['device_id'],
];
$tmp = [
'id'=>$item['id'],
'male'=>$male,
'female'=>$female,
];
$list[] = $tmp;
}
}
$this->success($list);
}
//繁育计划列表
public function detail_get()
{
$id = $this->input->get('id');
if(empty($id)){
$this->error('参数错误');
}
$this->load->model('breeding_plan_model');
$plan = $this->breeding_plan_model->get($id);
if(!$plan){
$this->error('计划不存在');
}
$tree = [
'male'=>[
'father'=>$this->_getNode($plan['male_father_id']),
'mother'=>$this->_getNode($plan['male_mother_id']),
'self'=>$this->_getNode($plan['male_id']),
],
'female'=>[
'father'=>$this->_getNode($plan['female_father_id']),
'mother'=>$this->_getNode($plan['female_mother_id']),
'self'=>$this->_getNode($plan['female_id']),
],
'children'=>[]
];
if(!empty($plan['children_ids'])){
$plan['children_ids'] = explode(',',$plan['children_ids']);
foreach ($plan['children_ids'] as $val) {
$tree['children'][] = $this->_getNode($val);
}
}
//如果没有children,补一个
if(empty($tree['children'])){
$tree['children'][] = [
'id'=>0,
'pet_name'=>'',
'pet_img'=>'',
];
}
$this->success($tree);
}
//繁育计划节点
protected function _getNode($sample_id)
{
$this->load->model('sample_model');
$sample = $this->sample_model->get($sample_id);
if(!$sample){
return [
'id'=>0
];
}
return $sample;
}
//繁育计划候选列表项目
protected function _getCandidateItem($sample,$reportJson)
{
$lineage = !empty($reportJson['血统分析']['body']['品系纯度'])?$reportJson['血统分析']['body']['品系纯度']:[];
$lineage = implode(',',array_keys($lineage));
$item = [
'id'=>$sample['id'],
'pet_name'=>$sample['pet_name'],
'pet_img'=>$sample['pet_img'],
'pet_sex'=>$sample['pet_sex'],
'lineage'=>$lineage,
];
return $item;
}
//繁育计划树的所有id
protected function _getTreeSampleIds($tree)
{
$ids = [];
foreach ($tree as $key=>$val) {
foreach ($val as $v) {
$ids[] = $v['id'];
}
}
return array_filter(array_unique($ids));
}
}
+87
View File
@@ -0,0 +1,87 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 创建用户
* Class Active
*/
class Sync extends ApiController
{
function __construct()
{
header('Access-Control-Allow-Credentials: true');
parent::__construct();
$this->load->model('series_number_model');
$this->load->model('package_model');
$this->load->model('sample_model');
$this->load->model('customer_model');
}
/**
* 服务端请求创建用户
* 绕过了前端授权
*/
public function user_post()
{
$ret = $this->serverSign();
if(!$ret){
$this->error('您的签名错误');
}
$config = array(
array(
'field' => 'openid',
'label' => 'OPENID',
'rules' => 'trim|required|min_length[3]|max_length[50]'
),
array(
'field' => 'unionid',
'label' => 'UNIONID',
'rules' => 'trim|required|min_length[3]|max_length[50]'
),
array(
'field' => 'nickname',
'label' => 'nickname',
'rules' => 'trim|required|min_length[1]|max_length[50]'
),
array(
'field' => 'sex',
'label' => 'sex',
'rules' => 'trim|min_length[1]|max_length[2]'
),
array(
'field' => 'language',
'label' => 'language',
'rules' => 'trim|min_length[1]|max_length[50]'
),
array(
'field' => 'city',
'label' => 'city',
'rules' => 'trim|min_length[1]|max_length[50]'
),
array(
'field' => 'province',
'label' => 'province',
'rules' => 'trim|min_length[0]|max_length[50]'
),
array(
'field' => 'country',
'label' => 'country',
'rules' => 'trim|min_length[0]|max_length[50]'
),
array(
'field' => 'headimgurl',
'label' => 'headimgurl',
'rules' => 'trim|required|min_length[3]|max_length[1000]'
),
);
$data = $this->json_validation($config);
$data['is_server'] = 1;
$ret = $this->customer_model->weixin_users($data);
if($ret){
$this->success('成功');
}else{
$this->error('创建失败');
}
}
}
+159
View File
@@ -0,0 +1,159 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use EasyWeChat\Foundation\Application as OfficialAccount;
use EasyWeChat\Payment\Order as WxPayOrder;
class Upgrade extends ApiController
{
function __construct()
{
header('Access-Control-Allow-Credentials: true');
parent::__construct();
}
protected function getApp(){
$conf = $this->config->item('weixin_uah');
$config = [
'app_id' => $conf['AppId'],
'secret' => $conf['AppSecert'],
'token' => $conf['Token'],
'aes_key' => $conf['EncodingAESKey'],
'response_type' => 'array',
'payment'=>[
// 必要配置
'app_id' => $conf['AppId'],
'mch_id' => $conf['mch_id'],
'key' => $conf['pay_api_key'], // API 密钥
// 如需使用敏感接口(如退款、发送红包等)需要配置
'cert_path' => $conf['pay_cert_path'], // 绝对路径
'key_path' => $conf['pay_key_path'], // 绝对路径
'notify_url' => '默认的订单回调地址', // 下单时单独设置来覆盖它
//'sandbox_mode' => (ENVIRONMENT !== 'production'), // 设置为 false 或注释则关闭沙箱模式
]
];
return new OfficialAccount($config);
}
//创建升级订单
public function order_post()
{
$config = array(
array(
'field' => 'id',
'label' => 'ID',
'rules' => 'trim|required|min_length[4]|max_length[20]'
),
array(
'field' => 'package_id',
'label' => 'ID',
'rules' => 'trim|required|min_length[1]|max_length[20]'
)
);
$data = $this->json_validation($config);
$this->load->model('sample_model');
$sample = $this->sample_model->get($data['id'],'device_id');
if(empty($sample)){
$this->error('样品不存在');
}
if($sample['package_id'] == $data['package_id']){
$this->error('升级信息不正确');
}
$this->load->model('package_model');
$to_package = $this->package_model->get($data['package_id'],'id');
$from_package = $this->package_model->get($sample['package_id'],'id');
if(empty($to_package) || empty($from_package)){
$this->error('套餐信息不存在');
}
$total = $to_package['price'] - $from_package['price'];
//生成订单
//同样订单升级方案只能创建一个订单
$order_id = null;
$this->load->model('sample_upgrade_order_model');
$order_list = $this->sample_upgrade_order_model->get($sample['id'],'base.sample_id',true);
foreach ($order_list as $value) {
if($value['package_before'] == $from_package['id'] &&
$value['package_after'] == $to_package['id']
){
if($value['paid_time'] > 0){
$this->error('您的订单已支付');
}
$order_id = $value['id'];
}
}
if(is_null($order_id)){
$order_id = $this->sample_upgrade_order_model->add([
'sample_id'=>$sample['id'],
'grand_total'=>$total,
'package_before'=>$from_package['id'],
'package_after'=>$to_package['id'],
'grand_total'=>$total,
]);
}
if(!$order_id){
$this->error('订单创建失败');
}
//获取用户的openid
$this->load->model('customer_model');
$customer = $this->customer_model->get($sample['user_id'],'id');
$attributes = [
'body' => '有哈检测套餐升级',
'out_trade_no' => 'testadsfdsffadsf',
//'total_fee' => (ENVIRONMENT !== 'production'?101:$total*100),//沙箱环境固定为1.01,正式环境固定为分
'total_fee' => $total*100,//单位:分
//'spbill_create_ip' => '', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
'notify_url' => base_url().'api/user/'.strtolower(__CLASS__).'/callback', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
'openid' => $customer['openid'],
];
$order = new WxPayOrder($attributes);
//print_r($attributes);die;
$app = $this->getApp();
$result = $app->payment->prepare($order);
if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
$prepayId = $result->prepay_id;
$json = $app->payment->configForPayment($prepayId,false); // 返回 json 字符串,如果想返回数组,传第二个参数
$this->success($json);
}
//print_r($result);die;
log_message('error', json_encode($data).''.json_encode($result));
$this->error('下单失败,请联系客服');
}
public function callback_get()
{
log_message('error',json_encode($_GET));
log_message('error',json_encode($_POST));
log_message('error',json_encode(file_get_contents('php://input')));
$app = $this->getApp();
$this->$app->payment->handleNotify(function($notify, $successful){
// 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
$this->load->model('sample_upgrade_order_model');
$order = $this->sample_upgrade_order_model->get($notify->out_trade_no);
if (!$order) { // 如果订单不存在
return 'Order not exist.'; // 告诉微信,我已经处理完了,订单没找到,别再通知我了
}
// 如果订单存在
// 检查订单是否已经更新过支付状态
if ($order['paid_time']) { // 假设订单字段“支付时间”不为空代表已经支付
return true; // 已经支付成功了就不再更新了
}
$data = [];
// 用户是否支付成功
if ($successful) {
// 不是已经支付状态则修改为已经支付状态
$data['paid_time'] = time(); // 更新支付时间为当前时间
$data['pay_status'] = 1;
} else { // 用户支付失败
$data['pay_status'] = 2;
}
$this->sample_upgrade_order_model->update($data,[
'id'=>$notify->out_trade_no
]);
return true; // 返回处理完成
});
}
}
+213
View File
@@ -0,0 +1,213 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use EasyWeChat\Foundation\Application as OfficialAccount;
use EasyWeChat\Payment\Order as WxPayOrder;
class Upgrade extends ApiController
{
function __construct()
{
header('Access-Control-Allow-Credentials: true');
parent::__construct();
$this->load->library('session');
}
protected function getApp(){
$conf = $this->config->item('weixin_uah');
$config = [
'app_id' => $conf['AppId'],
'secret' => $conf['AppSecert'],
'token' => $conf['Token'],
'aes_key' => $conf['EncodingAESKey'],
'response_type' => 'array',
'payment'=>[
// 必要配置
'app_id' => $conf['AppId'],
'mch_id' => $conf['mch_id'],
'key' => $conf['pay_api_key'], // API 密钥
// 如需使用敏感接口(如退款、发送红包等)需要配置
'cert_path' => $conf['pay_cert_path'], // 绝对路径
'key_path' => $conf['pay_key_path'], // 绝对路径
'notify_url' => '默认的订单回调地址', // 下单时单独设置来覆盖它
//'sandbox_mode' => (ENVIRONMENT !== 'production'), // 设置为 false 或注释则关闭沙箱模式
]
];
return new OfficialAccount($config);
}
//创建升级订单
public function order_post()
{
$config = array(
array(
'field' => 'id',
'label' => '样本编号',
'rules' => 'trim|required|min_length[4]|max_length[20]',
'errors' => array(
'required' => '请提供以下信息:%s.',
),
)
);
$data = $this->json_validation($config);
//样本信息
$this->load->model('sample_model');
$sample = $this->sample_model->get($data['id'],'device_id');
if(!$sample){
$this->error('样本不存在');
}
//序列号信息
$this->load->model('series_number_model');
$series = $this->series_number_model->get($data['id'],'device_id');
if(empty($series)){
$this->error('序列号信息不存在');
}
//如果样本中没有记录套餐,则根据序列号绑定的套餐做升级
$package_ori = !empty($sample['package_id'])?$sample['package_id']:$series['package_ori'];
//套餐信息
$this->load->model('package_model');
$from_package = $this->package_model->get($package_ori);
if(empty($from_package['package_up'])){
$this->error('您的套餐已经升级到最高套餐');
}
$to_package = $this->package_model->get($from_package['package_up']);
if(empty($to_package)){
$this->error('套餐信息不存在');
}
$total = round($to_package['price'] - $from_package['price'],2);
if($total <= 0){
$this->error('升级后套餐价格比当前套餐价格低');
}
//用户信息处理,获取用户的openid
$this->load->model('customer_model');
if(!empty($this->session->{Customer_model::SESSION_KEY})){
//如已登录,获取用户的open
$customer = $this->customer_model->get(
$this->session->{Customer_model::SESSION_KEY},
'id'
);
//用户可能会被删除
if($customer){
$open_id = $customer['openid'];
}
}
if(empty($open_id) && !empty($this->session->{Customer_model::SESSION_KEY_WX_OPEN_ID})){
$open_id = $this->session->{Customer_model::SESSION_KEY_WX_OPEN_ID};
}
if(empty($open_id)){
$this->success(['need_open_id'=>true]);
}
//生成订单,订单不能重复,每次都重新创建
$this->load->model('sample_upgrade_order_model');
/*
//同样订单升级方案只能创建一个订单
$order_id = null;
$order_list = $this->sample_upgrade_order_model->get($sample['id'],'base.sample_id',true);
foreach ($order_list as $value) {
if($value['package_before'] == $from_package['id'] &&
$value['package_after'] == $to_package['id']
){
if($value['paid_time'] > 0){
$this->error('您的订单已支付');
}
//如果金额不一致,需要做金额修改
if($total!=$value['grand_total']){
$this->sample_upgrade_order_model->update([
'grand_total'=>$total,
],[
'id'=>$value['id']
]);
}
$order_id = $value['id'];
break;
}
}
if(is_null($order_id)){
}*/
$order_id = $this->sample_upgrade_order_model->add([
'sample_id'=>$sample['id'],
'package_before'=>$from_package['id'],
'package_after'=>$to_package['id'],
'grand_total'=>$total,
]);
if(!$order_id){
$this->error('订单创建失败');
}
$attributes = [
'body' => '有哈检测套餐升级',
'out_trade_no' => $order_id,
//'total_fee' => (ENVIRONMENT !== 'production'?101:$total*100),//沙箱环境固定为1.01,正式环境固定为分
'total_fee' => round($total*100),//单位:分
//'spbill_create_ip' => '', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
'notify_url' => base_url().'api/user/'.strtolower(__CLASS__).'/callback', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
'openid' => $open_id,
];
//echo base_url().'api/user/'.strtolower(__CLASS__).'/callback';die;
$order = new WxPayOrder($attributes);
//print_r($attributes);die;
$app = $this->getApp();
$result = $app->payment->prepare($order);
if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
$prepayId = $result->prepay_id;
$json = $app->payment->configForPayment($prepayId,false); // 返回 json 字符串,如果想返回数组,传第二个参数
$this->success($json);
}
//print_r($result);die;
log_message('error', json_encode($data).''.json_encode($result));
$this->error('下单失败,请联系客服');
}
public function callback_post()
{
log_message('error',json_encode($_GET));
log_message('error',json_encode($_POST));
log_message('error',file_get_contents('php://input'));
$app = $this->getApp();
$app->payment->handleNotify(function($notify, $successful){
// 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
$this->load->model('sample_upgrade_order_model');
$order = $this->sample_upgrade_order_model->get($notify->out_trade_no);
if (!$order) { // 如果订单不存在
return 'Order not exist.'; // 告诉微信,我已经处理完了,订单没找到,别再通知我了
}
// 如果订单存在
// 检查订单是否已经更新过支付状态
if ($order['paid_time']) { // 假设订单字段“支付时间”不为空代表已经支付
return true; // 已经支付成功了就不再更新了
}
$data = [];
// 用户是否支付成功
if(!$successful){
$data['pay_status'] = 2;
$this->sample_upgrade_order_model->update($data,[
'id'=>$notify->out_trade_no
]);
return true;
}
$this->load->model('sample_model');
$this->sample_model->update([
'package_id'=>$order['package_after']
],[
'id'=>$order['sample_id']
]);
// 不是已经支付状态则修改为已经支付状态
$data['paid_time'] = time(); // 更新支付时间为当前时间
$data['pay_status'] = 1;
$this->sample_upgrade_order_model->update($data,[
'id'=>$notify->out_trade_no
]);
//样本更改套餐
return true; // 返回处理完成
});
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
use Restserver\Libraries\REST_Controller;
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
//To Solve File REST_Controller not found
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
class Table extends REST_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Api_model');
// $this->load->model('Record_model');
// $this->load->model('Dept_model', 'Dept');
// $this->config->load('config', true);
}
public function index()
{
$this->load->view('login_view');
}
public function testapi()
{
echo "test api ok...";
}
public function phpinfo()
{
phpinfo();
}
public function testdb()
{
$this->load->database();
$query = $this->db->query("show tables");
var_dump($query);
var_dump($query->result());
var_dump($query->row_array());
// 有结果表明数据库连接正常 reslut() 与 row_array 结果有时不太一样
// 一般加载到时model里面使用。
}
function list_get()
{
$items = [
["id" => 1,
"title" => "www",
"status" => "draft",
"author" => "qiaokun",
"display_time" => "",
"pageviews" => 300
],
["id" => 3,
"title" => "bbb",
"status" => "bbbb",
"author" => "乔锟",
"display_time" => "",
"pageviews" => 300
],
];
$message = [
"code" => 20000,
"data" => [
"items" => $items
]
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
function goods_get()
{
$items = array(
array('id' => 1, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 2, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 3, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 4, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 5, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 6, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 7, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 8, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 9, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 10, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 11, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 31, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 13, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 24, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 35, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 19, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 22, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 33, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
);
$message = [
"code" => 20000,
"data" => [
"items" => $items
]
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
+325
View File
@@ -0,0 +1,325 @@
<?php
use Restserver\Libraries\REST_Controller;
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
//To Solve File REST_Controller not found
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
//require APPPATH . 'libraries/kindeditor/php/JSON.php';
class Uploadimg extends REST_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Api_model');
}
public function testapi_get()
{
echo "test api ok...";
echo APPPATH . "\n";
echo SELF . "\n";
echo BASEPATH . "\n";
echo FCPATH . "\n";
echo SYSDIR . "\n";
var_dump($this->config->item('rest_language'));
var_dump($this->config->item('language'));
var_dump($this->config);
}
public function upload_post()
{
$uploadDir = FCPATH . 'uploads/';
$id = 'T' . $this->POST('identify');
$php_path = dirname(__FILE__) . '/';//dirname($_SERVER['DOCUMENT_ROOT']); dirname(__FILE__)
// $php_url = "";//dirname($_SERVER['HTTP_HOST']) . '/';//PHP_SELF
$php_url = $_SERVER['HTTP_HOST'] . '/'; //PHP_SELF
$save_path = $uploadDir;
//文件保存目录URL
$save_url = $php_url . 'uploads/';
// nginx服务器端修改绝对路径
//$save_url = "http://172.30.3.11/static/home/kindeditor/attached/";
// var_dump($save_path);
// var_dump($save_url);
// string(46) "D:\Q\code\vue\CodeIgniter-3.1.10\uploads\imgs\"
// string(28) "www.cirest.com:8889/uploads/"
//定义允许上传的文件扩展名
$ext_arr = array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
);
//最大文件大小 10M 默认是1M
$max_size = 10000000;
$save_path = realpath($save_path) . '/';
$save_path = str_replace('\\', '/', $save_path);
//PHP上传失败
if (!empty($_FILES['file']['error'])) {
switch ($_FILES['file']['error']) {
case '1':
$error = '超过php.ini允许的大小。';
break;
case '2':
$error = '超过表单允许的大小。';
break;
case '3':
$error = '图片只有部分被上传。';
break;
case '4':
$error = '请选择图片。';
break;
case '6':
$error = '找不到临时目录。';
break;
case '7':
$error = '写文件到硬盘出错。';
break;
case '8':
$error = 'File upload stopped by extension。';
break;
case '999':
default:
$error = '未知错误。';
}
$this->alert($error);
}
//有上传文件时
if (empty($_FILES) === false) {
//原文件名
$file_name = $_FILES['file']['name'];
//服务器上临时文件名
$tmp_name = $_FILES['file']['tmp_name'];
//文件大小
$file_size = $_FILES['file']['size'];
//检查文件名
if (!$file_name) {
$this->alert("请选择文件。");
}
//检查目录
if (@is_dir($save_path) === false) {
$this->alert("上传目录不存在。");
}
//检查目录写权限
if (@is_writable($save_path) === false) {
$this->alert("上传目录没有写权限。");
}
//检查是否已上传
if (@is_uploaded_file($tmp_name) === false) {
$this->alert("上传失败。");
}
//检查文件大小
if ($file_size > $max_size) {
$this->alert("上传文件大小超过限制(<10M)。");
}
//检查目录名
$dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
if (empty($ext_arr[$dir_name])) {
$this->alert("目录名不正确。");
}
//获得文件扩展名
$temp_arr = explode(".", $file_name);
$file_ext = array_pop($temp_arr);
$file_ext = trim($file_ext);
$file_ext = strtolower($file_ext);
//检查扩展名
if (!in_array($file_ext, $ext_arr[$dir_name])) {
$this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
}
/*
* 以 T+身份证号作为临时目录 , 以身份证作为正式目录
*/
$identify = empty($id) ? '' : trim($id);
if ($identify == '') {
echo "Invalid session identify.";
exit;
}
//创建文件夹
if ($dir_name !== '') {
$save_path .= $dir_name . "/" . $identify . "/";
$save_url .= $dir_name . "/" . $identify . "/";
if (!file_exists($save_path)) {
mkdir($save_path, 0777, true); // true 允许创建多级目录
}
}
$ymd = date("Ym");
$save_path .= $ymd . "/";
$save_url .= $ymd . "/";
if (!file_exists($save_path)) {
mkdir($save_path);
}
//新文件名
$new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
//移动文件
$file_path = $save_path . $new_file_name;
if (move_uploaded_file($tmp_name, $file_path) === false) {
$this->alert("上传文件失败。");
}
@chmod($file_path, 0644);
$file_url = $save_url . $new_file_name;
header('Content-type: text/html; charset=UTF-8');
// Insert file information in the database
// $insert = $db->query("INSERT INTO files (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
$link = "http://" . $file_url;
// http://www.cirest.com:8889/uploads/image/T410000000000000000/201902/20190228071354_96833.png
$message = [
"code" => 20000,
"error" => 0,
"message" => "上传成功",
"link" => $link,
"filepath" => preg_replace('/^http.*uploads/', '/uploads', $link)
];
echo json_encode($message);
// $this->set_response($message, REST_Controller::HTTP_OK);
// alert里面使用时 exit() 产生的是空,或字符串,使用原生的json_encode返回统一的字符串,在客户端在统一处理成对象
}
}
public function delimg_post()
{
$php_path = dirname(__FILE__) . '/';//dirname($_SERVER['DOCUMENT_ROOT']); dirname(__FILE__)
//文件保存目录路径
$save_path = $php_path . '../../../../';
$save_path = realpath($save_path) . '/';
$save_path = str_replace('\\', '/', $save_path);
// var_dump($save_path);
// "D:/Q/code/vue/CodeIgniter-3.1.10/"
$DelFileName = $this->POST('filename');
$DelFileType = $this->POST('isdir');
$FilePath = $save_path . $DelFileName;
// var_dump($FilePath);return;
if ($DelFileType == 'F') {
if (!is_file($FilePath)) {
$message = [
"code" => 20000,
"data" => "文件不存在 - " . $DelFileName,
"message" => "文件不存在 - " . $DelFileName
];
echo json_encode($message);
} else {
if (!unlink($FilePath)) {
$message = [
"code" => 20000,
"data" => "Error deleting " . $FilePath,
"message" => "Error deleting " . $FilePath
];
echo json_encode($message);
} else {
// 必须返回code 由于前端vue封装的 request 请求,返回数据对code进行判断
$message = [
"code" => 20000,
"data" => '服务器删除成功!',
"message" => '服务器删除成功!'
];
echo json_encode($message);
}
}
exit;
}
if ($DelFileType == 'D') {
if (!@rmdir($FilePath)) {
echo "文件夹 " . $FilePath . " 不为空,不能删除!";
} else {
echo "succeed";
}
exit;
}
}
private function alert($msg)
{
header('Content-type: text/html; charset=UTF-8');
$message = [
"code" => 20000,
"error" => 1,
"message" => $msg
];
echo json_encode($message);
exit();
// var_dump($message);
// $this->set_response($message, REST_Controller::HTTP_OK);
// die();
}
public function onsubmit_post()
{
$identify = $this->POST('identify');
$phone = $this->POST('phone');
$idinfo = $this->POST('idinfo');
$bankinfo = $this->POST('bankinfo');
// $data = [
// 'identify' => $identify,
// 'phone' => $phone,
// 'idinfo' => $idinfo,
// 'check' => '待审核'
// ];
// 写入数据库表 身份证号,手机号,证件照,文件路径等
$where = [
'identify' => $identify,
'phone' => $phone,
];
$data = [
'idinfo' => $idinfo,
'bankinfo' => $bankinfo,
'check' => '待审核'
];
$result = $this->Api_model->saveEdit('upload_tbl', $data, $where);
if ($result) {
$message = [
"code" => 20000,
"message" => '写入数据库表成功,请请待审核通知!',
"data" => array_merge($where, $data)
];
$this->set_response($message, REST_Controller::HTTP_OK);
} else {
$message = [
"code" => 20000,
"message" => '写入数据库表失败!',
"data" => array_merge($where, $data)
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
+559
View File
@@ -0,0 +1,559 @@
<?php
use Restserver\Libraries\REST_Controller;
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
//To Solve File REST_Controller not found
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
class User extends REST_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Api_model');
// $this->load->model('Record_model');
// $this->load->model('Dept_model', 'Dept');
// $this->config->load('config', true);
}
public function index_get()
{
$this->load->view('login_view');
}
public function testapi_get()
{
echo "test api ok...";
echo APPPATH . "\n";
echo SELF . "\n";
echo BASEPATH . "\n";
echo FCPATH . "\n";
echo SYSDIR . "\n";
var_dump($this->config->item('rest_language'));
var_dump($this->config->item('language'));
var_dump($this->config);
}
public function phpinfo_get()
{
phpinfo();
}
public function testdb_get()
{
$this->load->database();
$query = $this->db->query("show tables");
var_dump($query);
var_dump($query->result());
var_dump($query->row_array());
// 有结果表明数据库连接正常 reslut() 与 row_array 结果有时不太一样
// 一般加载到时model里面使用。
}
/* Helper Methods */
/**
* 生成 token
* @param
* @return string 40个字符
*/
private function _generate_token()
{
do {
// Generate a random salt
$salt = base_convert(bin2hex($this->security->get_random_bytes(64)), 16, 36);
// If an error occurred, then fall back to the previous method
if ($salt === FALSE) {
$salt = hash('sha256', time() . mt_rand());
}
$new_key = substr($salt, 0, config_item('rest_key_length'));
} while ($this->_token_exists($new_key));
return $new_key;
}
/* Private Data Methods */
private function _token_exists($token)
{
return $this->rest->db
->where('token', $token)
->count_all_results('auth') > 0;
}
private function _insert_token($token, $data)
{
$data['token'] = $token;
$data['date_created'] = function_exists('now') ? now() : time();
return $this->rest->db
->set($data)
->insert('auth');
}
private function _update_token($token, $data)
{
return $this->rest->db
->where('token', $token)
->update('auth', $data);
}
function login_post()
{
$username = $this->post('username'); // POST param
$password = $this->post('password'); // POST param
// var_dump($username);
// var_dump($password);
$input_account = $username;
$input_password = md5($password);
// $result = $this->Api_model->app_user_login_validate($input_account, $input_password);
// 用户名密码正确 生成token 返回
if (1) {
$token = $this->_generate_token();
// "token" => $token
$message = [
"code" => 20000,
"data" => [
"token" => "admin-token"
]
];
$this->set_response($message, REST_Controller::HTTP_OK);
} else {
$message = [
"code" => 60204,
"message" => 'Account and password are incorrect.'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
// 根据token拉取用户信息 get
function info_get()
{
// $result = $this->some_model();
$result['success'] = TRUE;
// 获取用户信息成功
if ($result['success']) {
$info = [
"roles" => ["editor"],
"introduction" => "I am a super administrator",
"avatar" => "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
"name" => "Super Admin",
"identify" => "410000000000000000",
"phone" => "13633838282"
];
$message = [
"code" => 20000,
"data" => $info,
"_SERVER" => $_SERVER,
"_GET" => $_GET
];
$this->set_response($message, REST_Controller::HTTP_OK);
} else {
$message = [
"code" => 50008,
"message" => 'Login failed, unable to get user details.'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
function logout_post()
{
$message = [
"code" => 20000,
"data" => 'success'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
function login()
{
$this->SET_HEADER; // 设置php CI 处理 CORS 自定义头部
if ($_SERVER["REQUEST_METHOD"] == 'POST') { // 只处理post请求,否则options请求 500错误
$json_params = file_get_contents('php://input');
$data = json_decode($json_params, true);
if (!empty($data)) {
if (!empty($data['username']) && !empty($data['password'])) {
$username = $data['username'];
$password = $data['password'];
$input_account = $username;
$input_password = md5($password);
// $results = $this->phpIonicLoginAuthValidateLogin($username, $password);
$result = $this->Api_model->app_user_login_validate($input_account, $input_password);
// $token=$_SERVER['x-auth-token'];
// 用户名密码正确 生成token 返回
$token = $this->createToken(10000);
$data = array(
"code" => 20000,
"data" => array(
"token" => "admin-token"
// "token" => $token
),
"params" => $json_params
);
echo json_encode($data);
// 用户名密码不正确
// return {
// code:
// 60204,
// message: 'Account and password are incorrect.'
// }
if ($result['success']) {
echo json_encode($this->saveLoginInfo($result['userinfo']));
} else {
// 校验失败,写入token
$this->output->set_status_header(300);
echo '{"success": false,"message": "用户名或密码错误","jump":"","user":"' . $username . '"}';
}
} else {
$results = array(
"result" => "Error - data incomplete!",
);
$jsonData = json_encode($results);
echo $jsonData;
}
} else { // no data post
$results = array(
"result" => "Error - no data!",
);
$jsonData = json_encode($results);
echo $jsonData;
}
}
}
// 根据token拉取用户信息 get
function info()
{
$this->SET_HEADER; // 设置php CI 处理 CORS 自定义头部
if ($_SERVER["REQUEST_METHOD"] == 'GET') { // 只处理post请求,否则options请求 500错误
$json_params = file_get_contents('php://input');
$data = json_decode($json_params, true);
// $token=$_SERVER['x-auth-token'];
// 获取用户信息成功
$info = array(
"roles" => array(
"admin"
),
"introduction" => "I am a super administrator",
"avatar" => "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
"name" => "Super Admin",
);
echo json_encode(
array(
"code" => 20000,
"data" => $info,
"_SERVER" => $_SERVER,
"_GET" => $_GET
)
);
// 获取用户信息失败
// return {
// code: 50008,
// message: 'Login failed, unable to get user details.'
// }
// echo json_encode(
// array(
// "code" => 50008,
// "message" => "Login failed, unable to get user details."
// )
// );
return;
if (!empty($data)) {
if (!empty($data['username']) && !empty($data['password'])) {
$username = $data['username'];
$password = $data['password'];
$input_account = $username;
$input_password = md5($password);
// $results = $this->phpIonicLoginAuthValidateLogin($username, $password);
$result = $this->Api_model->app_user_login_validate($input_account, $input_password);
if ($result['success']) {
echo json_encode($this->saveLoginInfo($result['userinfo']));
} else {
// 校验失败,写入token
$this->output->set_status_header(300);
echo '{"success": false,"message": "用户名或密码错误","jump":"","user":"' . $username . '"}';
}
} else {
$results = array(
"result" => "Error - data incomplete!",
);
$jsonData = json_encode($results);
echo $jsonData;
}
} else { // no data post
$results = array(
"result" => "Error - no data!",
);
$jsonData = json_encode($results);
echo $jsonData;
}
}
}
function logout()
{
$this->SET_HEADER; // 设置php CI 处理 CORS 自定义头部
if ($_SERVER["REQUEST_METHOD"] == 'POST') { // 只处理post请求,否则options请求 500错误
echo json_encode(array(
"code" => 20000,
"data" => 'sucess'
));
}
}
/*
* For 微信认证及全登录时保留登录日志信息
*/
function saveLoginInfo($userinfo)
{
$token = md5($userinfo["name"] . date('y-m-d H:i:s', time()));
$arr2 = array('token' => $token);
$userinfo["token"] = $token;
$this->Bas->saveAdd(
'auth',
array(
'token' => $token,
'expiredAt' => date('Y-m-d H:i:s', strtotime('+1 day')),
'onlineIp' => $this->input->ip_address(),
'userLoginInfo' => json_encode($userinfo),
'creatorId' => $userinfo["name"],
'createdAt' => date('Y-m-d H:i:s')
)
);
// 返回信息
$results = array(
"success" => true,
"message" => "APP登陆成功",
"user" => $userinfo,
'session' => $_SESSION,
);
$this->Bas->saveEdit('userinfo', array('LASTLOGIN' => date('y-m-d H:i:s', time()), 'LASTIP' => $this->input->ip_address()), array('USERNAME' => $userinfo["name"]));
return $results;
}
/**
* 执行CURL请求,并封装返回对象
*/
private function execCURL($ch)
{
$response = curl_exec($ch);
$error = curl_error($ch);
$result = array('header' => '',
'content' => '',
'curl_error' => '',
'http_code' => '',
'last_url' => '');
if ($error != "") {
$result['curl_error'] = $error;
return $result;
}
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$result['header'] = str_replace(array("\r\n", "\r", "\n"), "<br/>", substr($response, 0, $header_size));
$result['content'] = substr($response, $header_size);
$result['http_code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result['last_url'] = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$result["base_resp"] = array();
$result["base_resp"]["ret"] = $result['http_code'] == 200 ? 0 : $result['http_code'];
$result["base_resp"]["err_msg"] = $result['http_code'] == 200 ? "ok" : $result["curl_error"];
return $result;
}
/**
* GET 请求
* @param string $url
*/
private function http_get($url)
{
$oCurl = curl_init();
if (stripos($url, "https://") !== FALSE) {
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
}
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($oCurl, CURLOPT_VERBOSE, 1);
curl_setopt($oCurl, CURLOPT_HEADER, 1);
// $sContent = curl_exec($oCurl);
// $aStatus = curl_getinfo($oCurl);
$sContent = $this->execCURL($oCurl);
curl_close($oCurl);
return $sContent;
}
/**
* POST 请求
* @param string $url
* @param array $param
* @param boolean $post_file 是否文件上传
* @return string content
*/
private function http_post($url, $param, $post_file = false)
{
$oCurl = curl_init();
if (stripos($url, "https://") !== FALSE) {
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
}
if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
$is_curlFile = true;
} else {
$is_curlFile = false;
if (defined('CURLOPT_SAFE_UPLOAD')) {
curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
}
}
if ($post_file) {
if ($is_curlFile) {
foreach ($param as $key => $val) {
if (isset($val["tmp_name"])) {
$param[$key] = new \CURLFile(realpath($val["tmp_name"]), $val["type"], $val["name"]);
} else if (substr($val, 0, 1) == '@') {
$param[$key] = new \CURLFile(realpath(substr($val, 1)));
}
}
}
$strPOST = $param;
} else {
$strPOST = json_encode($param);
}
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($oCurl, CURLOPT_POST, true);
curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
curl_setopt($oCurl, CURLOPT_VERBOSE, 1);
curl_setopt($oCurl, CURLOPT_HEADER, 1);
// $sContent = curl_exec($oCurl);
// $aStatus = curl_getinfo($oCurl);
$sContent = $this->execCURL($oCurl);
curl_close($oCurl);
return $sContent;
}
function weixinAuth()
{
session_start();
if ($_SERVER["REQUEST_METHOD"] == 'OPTIONS') {
echo "options";
die();
}
// $corpId = "wwxxxxxxxx";
// $agentId = "100000";
// $appSecret = "fsdfsfsdf";
// $localAuthUrl = "http://dj.xxx.com:7000/hotcode/";
if (!array_key_exists("code", $_REQUEST)) {
$redirectUri = urlencode("http://yw.cttha.com/ksh/get-corp-weixin-code.html?redirect_uri=" . urlencode($localAuthUrl));
$authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $corpId . "&redirect_uri=" . $redirectUri . "&response_type=code&scope=snsapi_privateinfo&agentid=" . $agentId . "&state=STATE#wechat_redirect";
echo json_encode(array("success" => false, "authUrl" => $authUrl));
die();
}
$getCorpAccessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $corpId . "&corpsecret=" . $appSecret;
$accessToken = "";
if (false && $_SESSION["weixinAuth_accessToken"] && $_SESSION["weixinAuth_tokenTime"] && $_SESSION["weixinAuth_tokenExpires"] && time() - intval($_SESSION["weixinAuth_tokenTime"]) < intval($_SESSION["tokenExpires"])) {
$accessToken = $_SESSION["weixinAuth_accessToken"];
} else {
$tokenInfo = $this->http_get($getCorpAccessTokenUrl);
$tokenInfo = json_decode($tokenInfo["content"], true);
if ($tokenInfo["errcode"] == 0) {
$accessToken = $tokenInfo["access_token"];
$_SESSION["weixinAuth_accessToke"] = $accessToken;
$_SESSION["weixinAuth_tokenTime"] = time();
$_SESSION["weixinAuth_tokenExpires"] = $tokenInfo["expires_in"];
} else {
echo json_encode(array("success" => false, "msg" => $tokenInfo["errmsg"] ? $tokenInfo["errmsg"] : "企业认证失败!"));
die();
}
}
$getUserIdUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" . $accessToken . "&code=" . $_REQUEST["code"];
$ajaxUserIdInfo = $this->http_get($getUserIdUrl);
// var_dump($ajaxUserIdInfo);die();
$userIdInfo = json_decode($ajaxUserIdInfo["content"], true);
if ($userIdInfo["errcode"] == 0) {
if (array_key_exists("OpenId", $userIdInfo)) {
echo json_encode(array("success" => false, "msg" => "不是企业成员!请联系企业管理员,添加您的账号的企业通讯录!"));
die();
// next(U.error("不是企业成员!请联系企业管理员,添加您的账号的企业通讯录!"));
} else if (array_key_exists("UserId", $userIdInfo)) {
$getUserInfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=" . $accessToken;
// 44468cd93cdfefb8a7f911b5e1f7dfd0
$data = array("user_ticket" => $userIdInfo["user_ticket"]);
$ajaxUserInfo = $this->http_post($getUserInfoUrl, $data);
$userInfo = json_decode($ajaxUserInfo["content"], true);
if ($userInfo["errcode"] == 0) {
$user = $this->Api_model->getUserByWxUserId($userIdInfo["UserId"]);
if ($user["success"]) {
echo json_encode($this->saveLoginInfo($user['userinfo']));
die();
} else {
$_SESSION["wxUserInfo"] = $userInfo;
echo json_encode(array("sessionid" => session_id(), "status" => -1, "success" => false, "msg" => "此微信账号(" . $userInfo["name"] . ")没有与系统账号关联,请用您的账号密码登录一次,完成首次绑定!"));
die();
}
return;
} else {
echo json_encode(array("success" => false, "msg" => $userInfo["errmsg"]));
die();
}
}
} else {
echo json_encode(array("success" => false, "msg" => $userIdInfo["errmsg"]));
die();
}
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
+145
View File
@@ -0,0 +1,145 @@
<?php
use Restserver\Libraries\REST_Controller;
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
//To Solve File REST_Controller not found
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
class Article extends REST_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Base_model');
// $this->load->model('Record_model');
// $this->load->model('Dept_model', 'Dept');
// $this->config->load('config', true);
}
public function index()
{
$this->load->view('login_view');
}
public function testapi()
{
echo "test api ok...";
}
public function phpinfo()
{
phpinfo();
}
public function testdb()
{
$this->load->database();
$query = $this->db->query("show tables");
var_dump($query);
var_dump($query->result());
var_dump($query->row_array());
// 有结果表明数据库连接正常 reslut() 与 row_array 结果有时不太一样
// 一般加载到时model里面使用。
}
function list_get()
{
$items = [
["id" => 1,
"timestamp" => "20180808",
"author" => "qiaokun",
"reviewer" => "draft",
"title" => "draft",
"content_short" => "我是测试数据",
"content" => "<p>我是测试数据我是测试数据</p><p><img src=\"https://wpimg.wallstcn.com/4c69009c-0fd4-4153-b112-6cb53d1cf943\"></p>",
"forecast" => '3.1515',
"importance" => '1',
"type|1" => 'CN',
"status" => 'published',
"display_time" => "",
"comment_disabled" => true,
"pageviews" => 300,
"image_uri" => "https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3'",
"platforms" =>"a-platform"
],
["id" => 2,
"timestamp" => "20180808",
"author" => "qiaokun",
"reviewer" => "draft",
"title" => "draft",
"content_short" => "我是测试数据",
"content" => "<p>我是测试数据我是测试数据</p><p><img src=\"https://wpimg.wallstcn.com/4c69009c-0fd4-4153-b112-6cb53d1cf943\"></p>",
"forecast" => '3.1515',
"importance" => '1',
"type|1" => 'CN',
"status" => 'published',
"display_time" => "",
"comment_disabled" => true,
"pageviews" => 300,
"image_uri" => "https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3'",
"platforms" =>"a-platform"
],
];
$message = [
"code" => 20000,
"data" => [
"items" => $items,
"total" => count($items)
]
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
function goods_get()
{
$items = array(
array('id' => 1, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 2, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 3, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 4, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 5, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 6, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 7, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 8, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 9, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 10, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 11, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 31, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 13, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 24, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 35, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 19, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 22, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 33, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
);
$message = [
"code" => 20000,
"data" => [
"items" => $items
]
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
+121
View File
@@ -0,0 +1,121 @@
<?php
use Restserver\Libraries\REST_Controller;
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
//To Solve File REST_Controller not found
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
class Table extends REST_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Base_model');
// $this->load->model('Record_model');
// $this->load->model('Dept_model', 'Dept');
// $this->config->load('config', true);
}
public function index()
{
$this->load->view('login_view');
}
public function testapi()
{
echo "test api ok...";
}
public function phpinfo()
{
phpinfo();
}
public function testdb()
{
$this->load->database();
$query = $this->db->query("show tables");
var_dump($query);
var_dump($query->result());
var_dump($query->row_array());
// 有结果表明数据库连接正常 reslut() 与 row_array 结果有时不太一样
// 一般加载到时model里面使用。
}
function list_get()
{
$items = [
["id" => 1,
"title" => "www",
"status" => "draft",
"author" => "qiaokun",
"display_time" => "",
"pageviews" => 300
],
["id" => 3,
"title" => "bbb",
"status" => "bbbb",
"author" => "乔锟",
"display_time" => "",
"pageviews" => 300
],
];
$message = [
"code" => 20000,
"data" => [
"items" => $items
]
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
function goods_get()
{
$items = array(
array('id' => 1, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 2, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 3, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 4, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 5, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 6, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 7, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 8, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 9, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 10, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 11, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 31, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 13, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 24, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 35, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 19, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 22, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 33, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
);
$message = [
"code" => 20000,
"data" => [
"items" => $items
]
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
+418
View File
@@ -0,0 +1,418 @@
<?php
use Restserver\Libraries\REST_Controller;
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
//To Solve File REST_Controller not found
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
//require APPPATH . 'libraries/kindeditor/php/JSON.php';
class Uploadimg extends REST_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Base_model');
}
public function testapi_get()
{
echo "test api ok...";
echo APPPATH . "\n";
echo SELF . "\n";
echo BASEPATH . "\n";
echo FCPATH . "\n";
echo SYSDIR . "\n";
var_dump($this->config->item('rest_language'));
var_dump($this->config->item('language'));
var_dump($this->config);
}
public function upload_post()
{
$uploadDir = FCPATH . 'uploads/';
$id = 'T' . $this->POST('identify');
$php_path = dirname(__FILE__) . '/';//dirname($_SERVER['DOCUMENT_ROOT']); dirname(__FILE__)
// $php_url = "";//dirname($_SERVER['HTTP_HOST']) . '/';//PHP_SELF
$php_url = $_SERVER['HTTP_HOST'] . '/'; //PHP_SELF
$save_path = $uploadDir;
//文件保存目录URL
$save_url = $php_url . 'uploads/';
// nginx服务器端修改绝对路径
//$save_url = "http://172.30.3.11/static/home/kindeditor/attached/";
// var_dump($save_path);
// var_dump($save_url);
// string(46) "D:\Q\code\vue\CodeIgniter-3.1.10\uploads\imgs\"
// string(28) "www.cirest.com:8889/uploads/"
//定义允许上传的文件扩展名
$ext_arr = array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
);
//最大文件大小 10M 默认是1M
$max_size = 10000000;
$save_path = realpath($save_path) . '/';
$save_path = str_replace('\\', '/', $save_path);
//PHP上传失败
if (!empty($_FILES['file']['error'])) {
switch ($_FILES['file']['error']) {
case '1':
$error = '超过php.ini允许的大小。';
break;
case '2':
$error = '超过表单允许的大小。';
break;
case '3':
$error = '图片只有部分被上传。';
break;
case '4':
$error = '请选择图片。';
break;
case '6':
$error = '找不到临时目录。';
break;
case '7':
$error = '写文件到硬盘出错。';
break;
case '8':
$error = 'File upload stopped by extension。';
break;
case '999':
default:
$error = '未知错误。';
}
$this->alert($error);
}
//有上传文件时
if (empty($_FILES) === false) {
//原文件名
$file_name = $_FILES['file']['name'];
//服务器上临时文件名
$tmp_name = $_FILES['file']['tmp_name'];
//文件大小
$file_size = $_FILES['file']['size'];
//检查文件名
if (!$file_name) {
$this->alert("请选择文件。");
}
//检查目录
if (@is_dir($save_path) === false) {
$this->alert("上传目录不存在。");
}
//检查目录写权限
if (@is_writable($save_path) === false) {
$this->alert("上传目录没有写权限。");
}
//检查是否已上传
if (@is_uploaded_file($tmp_name) === false) {
$this->alert("上传失败。");
}
//检查文件大小
if ($file_size > $max_size) {
$this->alert("上传文件大小超过限制(<10M)。");
}
//检查目录名
$dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
if (empty($ext_arr[$dir_name])) {
$this->alert("目录名不正确。");
}
//获得文件扩展名
$temp_arr = explode(".", $file_name);
$file_ext = array_pop($temp_arr);
$file_ext = trim($file_ext);
$file_ext = strtolower($file_ext);
//检查扩展名
if (!in_array($file_ext, $ext_arr[$dir_name])) {
$this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
}
/*
* 以 T+身份证号作为临时目录 , 以身份证作为正式目录
*/
$identify = empty($id) ? '' : trim($id);
if ($identify == '') {
echo "Invalid session identify.";
exit;
}
//创建文件夹
if ($dir_name !== '') {
$save_path .= $dir_name . "/" . $identify . "/";
$save_url .= $dir_name . "/" . $identify . "/";
if (!file_exists($save_path)) {
mkdir($save_path, 0777, true); // true 允许创建多级目录
}
}
$ymd = date("Ym");
$save_path .= $ymd . "/";
$save_url .= $ymd . "/";
if (!file_exists($save_path)) {
mkdir($save_path);
}
//新文件名
$new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
//移动文件
$file_path = $save_path . $new_file_name;
if (move_uploaded_file($tmp_name, $file_path) === false) {
$this->alert("上传文件失败。");
}
@chmod($file_path, 0644);
$file_url = $save_url . $new_file_name;
header('Content-type: text/html; charset=UTF-8');
// Insert file information in the database
// $insert = $db->query("INSERT INTO files (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
$link = "http://" . $file_url;
// http://www.cirest.com:8889/uploads/image/T410000000000000000/201902/20190228071354_96833.png
$message = [
"code" => 20000,
"error" => 0,
"message" => "上传成功",
"link" => $link,
"filepath" => preg_replace('/^http.*uploads/', '/uploads', $link)
];
echo json_encode($message);
// $this->set_response($message, REST_Controller::HTTP_OK);
// alert里面使用时 exit() 产生的是空,或字符串,使用原生的json_encode返回统一的字符串,在客户端在统一处理成对象
}
}
public function delimg_post()
{
$php_path = dirname(__FILE__) . '/';//dirname($_SERVER['DOCUMENT_ROOT']); dirname(__FILE__)
//文件保存目录路径
$save_path = $php_path . '../../../../';
$save_path = realpath($save_path) . '/';
$save_path = str_replace('\\', '/', $save_path);
// var_dump($save_path);
// "D:/Q/code/vue/CodeIgniter-3.1.10/"
$DelFileName = $this->POST('filename');
$DelFileType = $this->POST('isdir');
$FilePath = $save_path . $DelFileName;
// var_dump($FilePath);return;
if ($DelFileType == 'F') {
if (!is_file($FilePath)) {
$message = [
"code" => 20000,
"data" => "文件不存在 - " . $DelFileName,
"message" => "文件不存在 - " . $DelFileName
];
echo json_encode($message);
} else {
if (!unlink($FilePath)) {
$message = [
"code" => 20000,
"data" => "Error deleting " . $FilePath,
"message" => "Error deleting " . $FilePath
];
echo json_encode($message);
} else {
// 必须返回code 由于前端vue封装的 request 请求,返回数据对code进行判断
$message = [
"code" => 20000,
"data" => '服务器删除成功!',
"message" => '服务器删除成功!'
];
echo json_encode($message);
}
}
exit;
}
if ($DelFileType == 'D') {
if (!@rmdir($FilePath)) {
echo "文件夹 " . $FilePath . " 不为空,不能删除!";
} else {
echo "succeed";
}
exit;
}
}
private function alert($msg)
{
header('Content-type: text/html; charset=UTF-8');
$message = [
"code" => 20000,
"error" => 1,
"message" => $msg
];
echo json_encode($message);
exit();
// var_dump($message);
// $this->set_response($message, REST_Controller::HTTP_OK);
// die();
}
public function onsubmit_post()
{
$identify = $this->POST('identify');
$phone = $this->POST('phone');
$idinfo = $this->POST('idinfo');
$bankinfo = $this->POST('bankinfo');
// $data = [
// 'identify' => $identify,
// 'phone' => $phone,
// 'idinfo' => $idinfo,
// 'check' => '待审核'
// ];
// 写入数据库表 身份证号,手机号,证件照,文件路径等
$where = [
'identify' => $identify,
'phone' => $phone,
];
$data = [
'idinfo' => $idinfo,
'bankinfo' => $bankinfo,
'check' => '待审核'
];
$result = $this->Base_model->_update_key('upload_tbl', $data, $where);
if ($result) {
$message = [
"code" => 20000,
"message" => '写入数据库表成功,请请待审核通知!',
"data" => array_merge($where, $data)
];
$this->set_response($message, REST_Controller::HTTP_OK);
} else {
$message = [
"code" => 20000,
"message" => '写入数据库表失败!',
"data" => array_merge($where, $data)
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
// Chevereto 图床免费版本地址:https://github.com/Chevereto/Chevereto-Free
// https://chevereto.com/docs/api-v1
// 上传图片测试
public function chevereto_post()
{
// 1. 上传本地文件时应使用 $fields post base64_encode方法
// Always use POST when uploading local files. Url encoding may alter the base64 source
// due to encoded characters or just by URL request length limit due to GET request.
// base64编码 会导致过长 url request
// var_dump($_FILES); 参考 uploadimg 可以做一些前置校验处理 // 前置判断 if (empty($_FILES) === false)
$key = '5486424e4dfb6b87453dd4bb25c0dcb0';
$url = 'http://172.17.1.110/chevereto/api/1/upload';
// What do we send to chevereto api?
$fields = array(
'key' => urlencode($key),
// The image encoded in base64
'source' => base64_encode(file_get_contents($_FILES["file"]['tmp_name'])),
// format: txt / json txt 只返回图片地址或错误信息 eg.Duplicated upload 较为简洁
'format' => urlencode('json')
);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, sizeof($fields));
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 240);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: '));
//execute post
$result = curl_exec($ch);
//释放curl句柄
curl_close($ch);
echo $result;
//close connection
// 2. 上传远程图片地址可使用 _get source=urlencode{source} 方法即可
// $key = '6a55c7f9fa13813c2da613dc7b5b920b';
// // 设定远程图片地址
// $source = 'https://img3.doubanio.com/view/group_topic/large/public/p67032015.jpg';
// // format: txt / json txt 只返回图片地址或错误信息 eg.Duplicated upload 较为简洁
// $url = 'http://172.17.1.110:8888/api/1/upload/?key={key}&source={source}&format=txt';
// $url = str_replace(array('{key}','{source}'),array($key,urlencode($source)),$url);
//
// //初始化
// $ch = curl_init();
// //设置选项,包括URL
// curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_HEADER, 0);
// //执行并获取HTML文档内容
// $output = curl_exec($ch);
// //释放curl句柄
// curl_close($ch);
// echo $output;
// 失败
// {
// "status_txt": "Bad Request",
// "error": {
// "context": "Exception",
// "code": 102,
// "message": "Duplicated upload"
// },
// "status_code": 400
// }
// 成功
// {
// "status_txt": "OK",
// "image": {
// "image": {
// "size": "89163",
// "url": "http://172.17.1.110:8888/images/2019/07/09/p67032015.jpg",
// "extension": "jpg",
// "mime": "image/jpeg",
// "name": "p67032015",
// "filename": "p67032015.jpg"
// },
// },
// "success": {
// "code": 200,
// "message": "image uploaded"
// },
// "status_code": 200
// }
}
}
+358
View File
@@ -0,0 +1,358 @@
<?php
use Restserver\Libraries\REST_Controller;
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
//To Solve File REST_Controller not found
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
class Menu extends REST_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Base_model');
// $this->config->load('config', true);
}
public function index_get()
{
$this->load->view('login_view');
}
public function insertx_post()
{
// $id = $this->post('id'); // POST param
$parms = $this->post(); // 获取表单参数,类型为数组
var_dump($parms);
$result = $this->Base_model->_insert_key('sys_role_perm', $parms);
var_dump($result);
}
public function gettest_post()
{
$result = $this->Base_model->_get_key('sys_perm', 'perm_type,r_id rid', 'perm_type="role" and r_id=1');
var_dump($result);
var_dump($result[0]['perm_type']);
var_dump($this->uri->uri_string);
var_dump($this->uri);
}
public function testapi_get()
{
echo "test api ok...";
echo APPPATH . "\n";
echo SELF . "\n";
echo BASEPATH . "\n";
echo FCPATH . "\n";
echo SYSDIR . "\n";
var_dump($this->config->item('rest_language'));
var_dump($this->config->item('language'));
var_dump($this->config);
// $message = [
// "code" => 20000,
// "data" => [
// "__FUNCTION__" => __FUNCTION__,
// "__CLASS__" => __CLASS__,
// "uri" => $this->uri
// ],
//
// ];
// "data": {
// "__FUNCTION__": "router_get",
// "__CLASS__": "User",
// "uri": {
// "keyval": [],
// "uri_string": "api/v2/user/router",
// "segments": {
// "1": "api",
// "2": "v2",
// "3": "user",
// "4": "router"
// },
}
public function phpinfo_get()
{
phpinfo();
}
public function testdb_get()
{
$this->load->database();
$query = $this->db->query("show tables");
var_dump($query);
var_dump($query->result());
var_dump($query->row_array());
// 有结果表明数据库连接正常 reslut() 与 row_array 结果有时不太一样
// 一般加载到时model里面使用。
}
// 增
function add_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->set_response($retPerm, REST_Controller::HTTP_OK);
return;
}
// $id = $this->post('id'); // POST param
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms);
// var_dump($parms['path']);
// 参数检验/数据预处理
// 菜单类型为目录
if (!$parms['type']) {
$parms['component'] = 'Layout';
}
$menu_id = $this->Base_model->_insert_key('sys_menu', $parms);
if (!$menu_id) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['title'] . ' - 菜单添加失败'
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
// 生成该菜单对应的权限: sys_perm, 权限类型为: menu, 生成唯一的 perm_id
$perm_id = $this->Base_model->_insert_key('sys_perm', ['perm_type' => 'menu', "r_id" => $menu_id]);
if (!$perm_id) {
var_dump($this->uri->uri_string . ' 生成该菜单对应的权限: sys_perm, 失败...');
var_dump(['perm_type' => 'menu', "r_id" => $menu_id]);
return;
}
// 超级管理员角色自动拥有该权限 perm_id
$role_perm_id = $this->Base_model->_insert_key('sys_role_perm', ["role_id" => 1, "perm_id" => $perm_id]);
if (!$role_perm_id) {
var_dump($this->uri->uri_string . ' 超级管理员角色自动拥有该权限 perm_id, 失败...');
var_dump(["role_id" => 1, "perm_id" => $perm_id]);
return;
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['title'] . ' - 菜单添加成功'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 改
function edit_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->set_response($retPerm, REST_Controller::HTTP_OK);
return;
}
// $id = $this->post('id'); // POST param
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['path']);
// 参数检验/数据预处理
if ($parms['id'] == $parms['pid']) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => '父节点不能是自己'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 菜单类型为目录
if ($parms['type'] == 0) {
$parms['component'] = 'Layout';
}
// 菜单类型为功能按钮时
if ($parms['type'] == 2) {
$parms['component'] = '';
$parms['icon'] = '';
}
$id = $parms['id'];
unset($parms['id']); // 择出索引id
$where = ["id" => $id];
if (!$this->Base_model->_update_key('sys_menu', $parms, $where)) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['title'] . ' - 菜单更新错误'
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['title'] . ' - 菜单更新成功'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 删
function del_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->set_response($retPerm, REST_Controller::HTTP_OK);
return;
}
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['path']);
// 参数检验/数据预处理
// 存在子节点 不能删除返回
$hasChild = $this->Base_model->hasChildMenu($parms['id']);
if ($hasChild) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['title'] . ' - 存在子节点不能删除'
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
// 删除外键关联表 sys_role_perm , sys_perm, sys_menu
// 1. 根据sys_menu id及'menu' 查找 perm_id
// 2. 删除sys_role_perm 中perm_id记录
// 3. 删除sys_perm中 perm_type='menu' and r_id = menu_id 记录,即第1步中获取的 perm_id, 一一对应
// 4. 删除sys_menu 中 id = menu_id 的记录
$where = 'perm_type="menu" and r_id=' . $parms['id'];
$arr = $this->Base_model->_get_key('sys_perm', '*', $where);
if (empty($arr)) {
var_dump($this->uri->uri_string . ' 未查找到 sys_perm 表中记录');
var_dump($where);
return;
}
$perm_id = $arr[0]['id']; // 正常只有一条记录
$this->Base_model->_delete_key('sys_role_perm', ['perm_id' => $perm_id]);
$this->Base_model->_delete_key('sys_perm', ['id' => $perm_id]);
// 删除基础表 sys_menu
if (!$this->Base_model->_delete_key('sys_menu', $parms)) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['title'] . ' - 菜单删除错误'
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['title'] . ' - 菜单删除成功'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 查
function view_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->set_response($retPerm, REST_Controller::HTTP_OK);
return;
}
$MenuTreeArr = $this->permission->getPermission($Token, 'menu', true);
$MenuTree = $this->permission->genVueMenuTree($MenuTreeArr, 'id', 'pid', 0);
$message = [
"code" => 20000,
"data" => $MenuTree,
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 根据token拉取 treeselect 下拉选项菜单
function treeoptions_get()
{
// 此 uri 可不做权限/token过期验证,则在菜单里,可以不加入此项路由path /sys/menu/treeoptions。
//
// $uri = $this->uri->uri_string;
// $Token = $this->input->get_request_header('X-Token', TRUE);
// $retPerm = $this->permission->HasPermit($Token, $uri);
// if ($retPerm['code'] != 50000) {
// $this->set_response($retPerm, REST_Controller::HTTP_OK);
// return;
// }
$Token = $this->input->get_request_header('X-Token', TRUE);
$MenuTreeArr = $this->permission->getPermission($Token, 'menu', false);
array_unshift($MenuTreeArr, ['id' => 0, 'pid' => -1, 'title' => '顶级菜单']);
$MenuTree = $this->permission->genVueMenuTree($MenuTreeArr, 'id', 'pid', -1);
$message = [
"code" => 20000,
"data" => $MenuTree,
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
function list_get()
{
// $result = $this->some_model();
$result['success'] = TRUE;
if ($result['success']) {
$List = array(
array('order_no' => '201805138451313131', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'success'),
array('order_no' => '300000000000000000', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'pending'),
array('order_no' => '444444444444444444', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'success'),
array('order_no' => '888888888888888888', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'pending'),
);
$message = [
"code" => 20000,
"data" => [
"total" => count($List),
"items" => $List
]
];
$this->set_response($message, REST_Controller::HTTP_OK);
} else {
$message = [
"code" => 50008,
"message" => 'Login failed, unable to get user details.'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
}
+478
View File
@@ -0,0 +1,478 @@
<?php
use Restserver\Libraries\REST_Controller;
defined('BASEPATH') OR exit('No direct script access allowed');
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
/** @noinspection PhpIncludeInspection */
//To Solve File REST_Controller not found
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';
class Role extends REST_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Base_model');
$this->load->model('Role_model');
// $this->config->load('config', true);
}
public function index_get()
{
$this->load->view('login_view');
}
public function insertx_post()
{
// $id = $this->post('id'); // POST param
$parms = $this->post(); // 获取表单参数,类型为数组
var_dump($parms);
$result = $this->Base_model->_insert_key('sys_role_perm', $parms);
var_dump($result);
}
public function gettest_post()
{
$result = $this->Base_model->_get_key('sys_perm', 'perm_type,r_id rid', 'perm_type="role" and r_id=1');
var_dump($result);
var_dump($result[0]['perm_type']);
var_dump($this->uri->uri_string);
var_dump($this->uri);
}
public function testapi_get()
{
echo "test api ok...";
echo APPPATH . "\n";
echo SELF . "\n";
echo BASEPATH . "\n";
echo FCPATH . "\n";
echo SYSDIR . "\n";
var_dump($this->config->item('rest_language'));
var_dump($this->config->item('language'));
var_dump($this->config);
// $message = [
// "code" => 20000,
// "data" => [
// "__FUNCTION__" => __FUNCTION__,
// "__CLASS__" => __CLASS__,
// "uri" => $this->uri
// ],
//
// ];
// "data": {
// "__FUNCTION__": "router_get",
// "__CLASS__": "User",
// "uri": {
// "keyval": [],
// "uri_string": "api/v2/user/router",
// "segments": {
// "1": "api",
// "2": "v2",
// "3": "user",
// "4": "router"
// },
}
public function phpinfo_get()
{
phpinfo();
}
public function testdb_get()
{
$this->load->database();
$query = $this->db->query("show tables");
var_dump($query);
var_dump($query->result());
var_dump($query->row_array());
// 有结果表明数据库连接正常 reslut() 与 row_array 结果有时不太一样
// 一般加载到时model里面使用。
}
// 增
function add_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->set_response($retPerm, REST_Controller::HTTP_OK);
return;
}
$parms = $this->post(); // 获取表单参数,类型为数组
if ($this->Base_model->_key_exists('sys_role', ['name' => $parms['name']])) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色名重复'
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
// 加入新增时间
$parms['create_time'] = time();
$role_id = $this->Base_model->_insert_key('sys_role', $parms);
if (!$role_id) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色新增失败'
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
// 生成该角色对应的权限: sys_perm, 权限类型为: role, 生成唯一的 perm_id
$perm_id = $this->Base_model->_insert_key('sys_perm', ['perm_type' => 'role', "r_id" => $role_id]);
if (!$perm_id) {
var_dump($this->uri->uri_string . ' 生成该角色对应的权限: sys_perm, 失败...');
var_dump(['perm_type' => 'role', "r_id" => $role_id]);
return;
}
// 超级管理员角色自动拥有该权限 perm_id
$role_perm_id = $this->Base_model->_insert_key('sys_role_perm', ["role_id" => 1, "perm_id" => $perm_id]);
if (!$role_perm_id) {
var_dump($this->uri->uri_string . ' 超级管理员角色自动拥有该权限 perm_id, 失败...');
var_dump(["role_id" => 1, "perm_id" => $perm_id]);
return;
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['name'] . ' - 角色新增成功'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 改
function edit_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->set_response($retPerm, REST_Controller::HTTP_OK);
return;
}
// $id = $this->post('id'); // POST param
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['path']);
// 参数检验/数据预处理
// 超级管理员角色不允许修改
if ($parms['id'] == 1) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色不允许修改'
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
$id = $parms['id'];
unset($parms['id']); // 剃除索引id
// 加入更新时间
$parms['update_time'] = time();
$where = ["id" => $id];
if (!$this->Base_model->_update_key('sys_role', $parms, $where)) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色更新错误'
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['name'] . ' - 角色更新成功'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 删
function del_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->set_response($retPerm, REST_Controller::HTTP_OK);
return;
}
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['path']);
// 参数检验/数据预处理
// 超级管理员角色不允许删除
if ($parms['id'] == 1) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色不允许删除'
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
// 删除外键关联表 sys_role_perm , sys_perm, sys_role
// 1. 根据sys_role id及'menu' 查找 perm_id
// 2. 删除sys_role_perm 中perm_id记录
// 3. 删除sys_perm中 perm_type='role' and r_id = role_id 记录,即第1步中获取的 perm_id, 一一对应
// 4. 删除sys_role 中 id = role_id 的记录
$where = 'perm_type="role" and r_id=' . $parms['id'];
$arr = $this->Base_model->_get_key('sys_perm', '*', $where);
if (empty($arr)) {
var_dump($this->uri->uri_string . ' 未查找到 sys_perm 表中记录');
var_dump($where);
return;
}
$perm_id = $arr[0]['id']; // 正常只有一条记录
$this->Base_model->_delete_key('sys_role_perm', ['perm_id' => $perm_id]); // 必须删除权限id 因为超级管理员角色自动拥有该权限否则会造成删除关联错误
$this->Base_model->_delete_key('sys_role_perm', ['role_id' => $parms['id']]); // 再删除该角色对应的权限id(原有的菜单)
$this->Base_model->_delete_key('sys_perm', ['id' => $perm_id]);
$this->Base_model->_delete_key('sys_user_role', ['role_id' => $parms['id']]);
// 删除基础表 sys_role
if (!$this->Base_model->_delete_key('sys_role', $parms)) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色删除错误'
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['name'] . ' - 角色删除成功'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 查
function view_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->set_response($retPerm, REST_Controller::HTTP_OK);
return;
}
$RoleArr = $this->Role_model->getRoleList();
$message = [
"code" => 20000,
"data" => $RoleArr,
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 获取所有菜单 不需权限验证
function allmenus_get()
{
$MenuTreeArr = $this->Role_model->getAllMenus();
if (empty($MenuTreeArr)) {
$message = [
"code" => 20000,
"data" => $MenuTreeArr,
"message" => "数据库表中没有菜单"
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
$MenuTree = $this->permission->genVueMenuTree($MenuTreeArr, 'id', 'pid', 0);
$message = [
"code" => 20000,
"data" => $MenuTree,
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 获取所有角色带perm_id 不需权限验证
function allroles_get()
{
$AllRolesArr = $this->Role_model->getAllRoles();
if (empty($AllRolesArr)) {
$message = [
"code" => 20000,
"data" => $AllRolesArr,
"message" => "数据库表中没有角色"
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
$message = [
"code" => 20000,
"data" => $AllRolesArr,
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 获取角色拥有的菜单权限 不需权限验证
function rolemenu_post()
{
$parms = $this->post(); // 获取表单参数,类型为数组
$RoleId = $parms['roleId'];
$MenuTreeArr = $this->Role_model->getRoleMenu($RoleId);
$message = [
"code" => 20000,
"data" => $MenuTreeArr,
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 获取角色拥有的角色权限 不需权限验证
function rolerole_post()
{
$parms = $this->post(); // 获取表单参数,类型为数组
$RoleId = $parms['roleId'];
$RoleRoleArr = $this->Role_model->getRoleRole($RoleId);
$message = [
"code" => 20000,
"data" => $RoleRoleArr,
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
// 保存角色对应权限
function saveroleperm_post()
{
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['roleId']);
// var_dump($parms['rolePerms']);
// 参数检验/数据预处理
// 超级管理员角色不允许删除
if ($parms['roleId'] == 1) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => '超级管理员角色拥有所有权限,不允许修改!'
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
$RolePermArr = $this->Role_model->getRolePerm($parms['roleId']);
$AddArr = $this->permission->array_diff_assoc2($parms['rolePerms'], $RolePermArr);
// var_dump('------------只存在于前台传参 做添加操作-------------');
// var_dump($AddArr);
$failed = false;
$failedArr = [];
foreach ($AddArr as $k => $v) {
$ret = $this->Base_model->_insert_key('sys_role_perm', $v);
if (!$ret) {
$failed = true;
array_push($failedArr, $v);
}
}
if ($failed) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => '授权失败 ' . json_encode($failedArr)
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
$DelArr = $this->permission->array_diff_assoc2($RolePermArr, $parms['rolePerms']);
// var_dump('------------只存在于后台数据库 删除操作-------------');
// var_dump($DelArr);
$failed = false;
$failedArr = [];
foreach ($DelArr as $k => $v) {
$ret = $this->Base_model->_delete_key('sys_role_perm', $v);
if (!$ret) {
$failed = true;
array_push($failedArr, $v);
}
}
if ($failed) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => '授权失败 ' . json_encode($failedArr)
];
$this->set_response($message, REST_Controller::HTTP_OK);
return;
}
$message = [
"code" => 20000,
"type" => 'success',
"data" => $parms,
"message" => '授权操作成功',
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
function list_get()
{
// $result = $this->some_model();
$result['success'] = TRUE;
if ($result['success']) {
$List = array(
array('order_no' => '201805138451313131', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'success'),
array('order_no' => '300000000000000000', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'pending'),
array('order_no' => '444444444444444444', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'success'),
array('order_no' => '888888888888888888', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'pending'),
);
$message = [
"code" => 20000,
"data" => [
"total" => count($List),
"items" => $List
]
];
$this->set_response($message, REST_Controller::HTTP_OK);
} else {
$message = [
"code" => 50008,
"message" => 'Login failed, unable to get user details.'
];
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
}
File diff suppressed because it is too large Load Diff
+138
View File
@@ -0,0 +1,138 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
class Article extends RestController
{
function __construct()
{
parent::__construct();
$this->load->model('Base_model');
// $this->load->model('Record_model');
// $this->load->model('Dept_model', 'Dept');
// $this->config->load('config', true);
}
public function index()
{
$this->load->view('login_view');
}
public function testapi()
{
echo "test api ok...";
}
public function phpinfo()
{
phpinfo();
}
public function testdb()
{
$this->load->database();
$query = $this->db->query("show tables");
var_dump($query);
var_dump($query->result());
var_dump($query->row_array());
// 有结果表明数据库连接正常 reslut() 与 row_array 结果有时不太一样
// 一般加载到时model里面使用。
}
function list_get()
{
$items = [
["id" => 1,
"timestamp" => "20180808",
"author" => "qiaokun",
"reviewer" => "draft",
"title" => "draft",
"content_short" => "我是测试数据",
"content" => "<p>我是测试数据我是测试数据</p><p><img src=\"https://wpimg.wallstcn.com/4c69009c-0fd4-4153-b112-6cb53d1cf943\"></p>",
"forecast" => '3.1515',
"importance" => '1',
"type|1" => 'CN',
"status" => 'published',
"display_time" => "",
"comment_disabled" => true,
"pageviews" => 300,
"image_uri" => "https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3'",
"platforms" =>"a-platform"
],
["id" => 2,
"timestamp" => "20180808",
"author" => "pocoyo",
"reviewer" => "draft",
"title" => "draft",
"content_short" => "我是测试数据",
"content" => "<p>我是测试数据我是测试数据</p><p><img src=\"https://wpimg.wallstcn.com/4c69009c-0fd4-4153-b112-6cb53d1cf943\"></p>",
"forecast" => '3.1515',
"importance" => '1',
"type|1" => 'CN',
"status" => 'published',
"display_time" => "",
"comment_disabled" => true,
"pageviews" => 300,
"image_uri" => "https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3'",
"platforms" =>"a-platform"
],
];
$message = [
"code" => 20000,
"data" => [
"items" => $items,
"total" => count($items)
]
];
$this->set_response($message, RestController::HTTP_OK);
}
function goods_get()
{
$items = array(
array('id' => 1, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 2, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 3, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 4, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 5, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 6, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 7, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 8, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 9, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 10, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 11, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 31, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 13, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 24, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 35, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 19, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 22, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 33, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
);
$message = [
"code" => 20000,
"data" => [
"items" => $items
]
];
$this->set_response($message, RestController::HTTP_OK);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
+20
View File
@@ -0,0 +1,20 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends AdminController
{
protected $base_model = 'package_model';
function count_total_get()
{
$ret = [
'count'=>[]
];
foreach (['sample','customer','sample_upgrade_order'] as $model) {
$this->load->model($model.'_model');
$ret['count'][$model] = (int)$this->{$model.'_model'}->total();
}
$ret['count']['order_total'] = 0;
$this->success($ret);
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 样品
*/
class Disease extends AdminController
{
protected $base_model = 'disease_model';
protected function _validate_rule(){
return array(
array(
'field' => 'id',
'label' => '序号',
'rules' => 'trim|min_length[0]|max_length[20]'
),
array(
'field' => 'name',
'label' => '名称',
'rules' => 'trim|min_length[0]|max_length[40]'
),
array(
'field' => 'pathogenesis',
'label' => '致病机理',
'rules' => 'trim|min_length[0]|max_length[800]'
),
array(
'field' => 'clinical_symptoms',
'label' => '临床症状',
'rules' => 'trim|min_length[0]|max_length[800]'
),
array(
'field' => 'category',
'label' => '所属类别',
'rules' => 'trim|min_length[0]|max_length[50]'
),
array(
'field' => 'advice_treatment',
'label' => '诊疗建议',
'rules' => 'trim|min_length[0]|max_length[800]'
),
array(
'field' => 'advice_parenting',
'label' => '养育建议',
'rules' => 'trim|min_length[0]|max_length[800]'
),
array(
'field' => 'reference',
'label' => '参考文献',
'rules' => 'trim|min_length[0]|max_length[800]'
),
array(
'field' => 'species',
'label' => '物种',
'rules' => 'trim|integer|min_length[0]|max_length[2]'
),
array(
'field' => 'gene_type',
'label' => '基因类别',
'rules' => 'trim|integer|min_length[0]|max_length[2]'
),
);
}
protected function _import_field_map(){
return [
'名称'=>'name',
'致病机理'=>'pathogenesis',
'临床症状'=>'clinical_symptoms',
'所属类别'=>'category',
'诊疗建议'=>'advice_treatment',
'养育建议'=>'advice_parenting',
'参考文献'=>'reference',
'species'=>'species',
'gene_type'=>'gene_type',
];
}
}
+128
View File
@@ -0,0 +1,128 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Package extends AdminController
{
protected $base_model = 'package_model';
function list_get()
{
$data = $this->_list_get(true);
$package_up_ids = [];
$disease_ids = [];
foreach ($data['items'] as &$item) {
$item['content'] = empty($item['content'])?[]:json_decode($item['content'],true);
$item['structure'] = array_values(array_filter(explode(',',$item['structure'])));
$item['structure_hide'] = array_values(array_filter(explode(',',$item['structure_hide'])));
$item['cert'] = array_values(array_filter(explode(',',$item['cert'])));
$item['disease'] = array_values(array_filter(explode(',',$item['disease'])));
//套餐升级目标
$package_up_ids[] = $item['package_up'];
//套餐自带疾病
$disease_ids = array_merge($disease_ids,$item['disease']);
//套餐疾病选项
foreach ($item['content'] as $val) {
$disease_ids = array_merge($disease_ids,$val['disease_id']);
}
}
//提供所有升级目标套餐的值
$data['options']['package'] = $this->package_model->get($package_up_ids,null,true,'base.id,base.name');
//提供所有疾病选项
$this->load->model('disease_model');
$data['options']['disease'] = $this->disease_model->get($disease_ids,null,true,'base.id,base.name');
$this->success($data);
}
function update_post()
{
$config = array(
array(
'field' => 'id',
'label' => '序号',
'rules' => 'trim|min_length[0]|max_length[20]'
),
array(
'field' => 'name',
'label' => '套餐名称',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'is_breed',
'label' => '繁育套餐',
'rules' => 'trim|min_length[1]|max_length[2]',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'species',
'label' => '物种',
'rules' => 'trim|required|min_length[1]|max_length[2]',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'package_up',
'label' => '升级目标',
'rules' => 'trim|min_length[1]|max_length[2]',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'description',
'label' => '描述',
'rules' => 'trim|min_length[0]|max_length[20]'
),
array(
'field' => 'price',
'label' => '价格',
'rules' => 'trim|min_length[0]|max_length[20]'
)
);
//涉及字段序列化的特殊操作
$data = $this->json_validation($config);
//处理content字段
if(!is_array($data['content'])){
$this->error('套餐内容需要传入数组');
}
if(!empty($data['content']))foreach ($data['content'] as $item) {
if(empty($item['name'])){
$this->error('套餐选项名称不能为空');
}
if(empty($item['disease_id'])){
$this->error('套餐疾病选项不能为空');
}
}
$data['content'] = json_encode($data['content']);
$data['structure'] = implode(',',$data['structure']);
$data['structure_hide'] = implode(',',$data['structure_hide']);
$data['cert'] = implode(',',$data['cert']);
$data['disease'] = implode(',',$data['disease']);
$fields = array_column($config,'field');
$fields[] = 'content';
$fields[] = 'structure';
$fields[] = 'structure_hide';
$fields[] = 'cert';
$fields[] = 'disease';
foreach ($data as $key => $val) {
if(!in_array($key,$fields)){
unset($data[$key]);
}
}
//print_r($data);die;
if(empty($data['id'])){
$ret = $this->{$this->base_model}->add($data);
if($ret === -1){
$this->error('名称不能与已有的重复');
}
}else{
$this->{$this->base_model}->update($data, ['id'=>$data['id']]);
}
$this->success();
}
}
+174
View File
@@ -0,0 +1,174 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 样品
*/
class Sample extends AdminController
{
protected $base_model = 'sample_model';
function image_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
// $retPerm = $this->permission->HasPermit($Token, $uri);
// if ($retPerm['code'] != 50000) {
// $this->response($retPerm, RestController::HTTP_OK);
// }
$dir = 'pet_img_custom/';
$path = 'uploads/'.$dir;
$config['upload_path'] = './'.$path;
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 10000;
$config['max_width'] = 4000;
$config['max_height'] = 4000;
//设置文件名,前端传来的文件固定是png
$config['file_name'] = time();
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('avatar'))
{
$this->error( $this->upload->display_errors());
}
else
{
$data = $this->upload->data();
}
$this->success([
'path'=>$dir.$data['file_name'],
'full_path'=>base_url().$path.$data['file_name']
]);
}
function update_post()
{
$config = array(
array(
'field' => 'id',
'label' => '序号',
'rules' => 'trim|min_length[1]|max_length[10]'
),
array(
'field' => 'series_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[1]|max_length[20]'
),
array(
'field' => 'user_id',
'label' => '用户',
'rules' => 'trim|required|min_length[1]|max_length[20]',
'errors' => array(
'required' => '需要搜索绑定 %s',
),
),
array(
'field' => 'name',
'label' => '用户姓名',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'tel',
'label' => '手机',
'rules' => 'required'
),
array(
'field' => 'pet_name',
'label' => '宠物名称',
'rules' => 'required'
),
array(
'field' => 'pet_img',
'label' => '宠物头像',
),
array(
'field' => 'pet_sex',
'label' => '宠物性别',
'rules' => 'required'
),
array(
'field' => 'pet_species',
'label' => '宠物物种',
),
array(
'field' => 'pet_birthday',
'label' => '宠物生日',
'rules' => 'required'
),
array(
'field' => 'is_sterilized',
'label' => '是否绝育',
),
array(
'field' => 'package_id',
'label' => '套餐ID'
)
);
//读取输入数据
$data = $this->json_validation($config);
//不允许修改套餐
//unset($data['package_id']);
//对于新样品,从序列号读取套餐
if(empty($data['id'])){
$this->load->model('series_number_model');
$series = $this->series_number_model->get($data['series_id']);
if(!$series){
$this->error('序列号不存在');
}
if(empty($series['package_ori'])){
$this->error('序列号未绑定套餐');
}
$data['package_id'] = $series['package_ori'];
}
$this->_update_post($config,$data);
}
function list_get()
{
$ret = $this->_list_get(true);
$this->load->model('sample_model');
$ret['step'] = $this->sample_model->step_back;
$this->load->model('package_model');
$package_map = $this->package_model->get(false,null,true,'id,name');
$package_map = array_column($package_map,'name','id');
foreach ($ret['items'] as &$item) {
$item['package_ori_name'] = isset($package_map[$item['package_ori']])?$package_map[$item['package_ori']]:'';
$item['package_name'] = isset($package_map[$item['package_id']])?$package_map[$item['package_id']]:'';
}
$this->success($ret);
}
//批量更新状态
function batch_update_status_post()
{
$data_arr = $this->json_input();
$this->load->model('sample_model');
if(empty($data_arr['ids']) || !is_array($data_arr['ids'])){
$this->error('请选择要操作的样品');
}
if(empty($data_arr['step']) || !isset($this->sample_model->step_back[$data_arr['step']])){
$this->error('状态错误');
}
if(empty($data_arr['timestamp'])){
$data_arr['timestamp'] = time();
}
$ret = $this->sample_model->update(
['step'=>$data_arr['step']],
'id in ('.implode(',',$data_arr['ids']).')',
false
);
if($ret){
//记录状态变更时间
//如果完成,给用户发通知
if($data_arr['step'] == Sample_model::STEP_COMPLETE){
$this->sample_model->complete($data_arr['ids']);
}
}
$this->success();
}
}
@@ -0,0 +1,10 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 样品升级订单管理
*/
class Sample_upgrade_order extends AdminController
{
protected $base_model = 'sample_upgrade_order_model';
}
+46
View File
@@ -0,0 +1,46 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 通用搜索控件,如用户等
*/
class Search extends AdminController
{
function _get($model,$nama_field = 'name')
{
$this->load->model($model);
$searchText = $this->input->get('name');
$searchId = $this->input->get('id');
$param = [];
if(!empty($searchId)){
$param['id'] = $searchId;
}else{
$param[$nama_field] = $searchText;
}
$page = 1;
$limit = 100;
$items = $this->$model->listing($param, ($page-1)*$limit,$limit,'base.id,base.'.$nama_field);
$this->success($items);
}
function user_get()
{
$this->_get('customer_model','nickname');
}
function package_get()
{
$this->_get('package_model');
}
function disease_get()
{
$this->_get('disease_model');
}
function series_number_get()
{
$this->_get('series_number_model','device_id');
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 序列号
*/
class Series_number extends AdminController
{
protected $base_model = 'series_number_model';
function list_get()
{
$items = parent::_list_get(true);
$this->load->model('package_model');
$package = $this->package_model->get(false,'id,name',true);
$package_map = [
'0'=>'未绑定套餐'
];
foreach ($package as $item) {
$package_map[$item['id']] = $item['name'];
}
foreach ($items['items'] as &$item) {
$item['status_desc'] = !empty($item['sample_id'])?'已激活':'未激活';
$item['package_name'] = $package_map[$item['package_ori']];
}
//统计
$items['stat'] = [
'total'=>(int)$this->{$this->base_model}->total(),
'used'=>(int)$this->{$this->base_model}->total(['s.id>0'],true),
'unused'=>(int)$this->{$this->base_model}->total(['s.id is null'],true),
];
$this->success($items);
}
//批量新建
function batch_create_post()
{
$data = $this->json_input();
if(empty($data['package_ori'])){
$this->error('套餐不能为空');
}
$package_id = trim($data['package_ori']);
$number = explode("\n",trim($data['device_id']));
$devices = [];
foreach ($number as $item) {
$item = trim($item);
if(empty($item)){
continue;
}
$devices[] = [
'device_id'=>$item,
'package_ori'=>$package_id
];
}
if(empty($devices)){
$this->error('序列号为空');
}
$config = array(
array(
'field' => 'device_id',
'label' => '序号',
'rules' => 'trim|min_length[0]|max_length[20]'
),
array(
'field' => 'package_ori',
'label' => '套餐名称',
'rules' => 'trim|required|min_length[1]|max_length[11]',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
);
$this->_batch_create_post($config,$devices);
$this->success();
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 样品升级订单管理
*/
class Ship_order extends AdminController
{
protected $base_model = 'ship_order_model';
}
+114
View File
@@ -0,0 +1,114 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
class Table extends RestController
{
function __construct()
{
parent::__construct();
$this->load->model('Base_model');
// $this->load->model('Record_model');
// $this->load->model('Dept_model', 'Dept');
// $this->config->load('config', true);
}
public function index()
{
$this->load->view('login_view');
}
public function testapi()
{
echo "test api ok...";
}
public function phpinfo()
{
phpinfo();
}
public function testdb()
{
$this->load->database();
$query = $this->db->query("show tables");
var_dump($query);
var_dump($query->result());
var_dump($query->row_array());
// 有结果表明数据库连接正常 reslut() 与 row_array 结果有时不太一样
// 一般加载到时model里面使用。
}
function list_get()
{
$items = [
["id" => 1,
"title" => "www",
"status" => "draft",
"author" => "qiaokun",
"display_time" => "",
"pageviews" => 300
],
["id" => 3,
"title" => "bbb",
"status" => "bbbb",
"author" => "乔锟",
"display_time" => "",
"pageviews" => 300
],
];
$message = [
"code" => 20000,
"data" => [
"items" => $items
]
];
$this->response($message, RestController::HTTP_OK);
}
function goods_get()
{
$items = array(
array('id' => 1, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 2, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 3, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 4, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 5, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 6, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 7, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 8, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 9, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 10, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 11, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 31, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 13, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 24, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 35, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
array('id' => 19, 'title' => 'iphone 7 ', 'price' => 399, 'num' => 1),
array('id' => 22, 'title' => 'hdcms 7 ', 'price' => 2000, 'num' => 2),
array('id' => 33, 'title' => 'aaaas 7 ', 'price' => 2000, 'num' => 2),
);
$message = [
"code" => 20000,
"data" => [
"items" => $items
]
];
$this->response($message, RestController::HTTP_OK);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
+410
View File
@@ -0,0 +1,410 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
class Uploadimg extends RestController
{
function __construct()
{
parent::__construct();
$this->load->model('Base_model');
}
public function testapi_get()
{
echo "test api ok...";
echo APPPATH . "\n";
echo SELF . "\n";
echo BASEPATH . "\n";
echo FCPATH . "\n";
echo SYSDIR . "\n";
var_dump($this->config->item('rest_language'));
var_dump($this->config->item('language'));
var_dump($this->config);
}
public function upload_post()
{
$uploadDir = FCPATH . 'uploads/';
$id = 'T' . $this->POST('identify');
$php_path = dirname(__FILE__) . '/';//dirname($_SERVER['DOCUMENT_ROOT']); dirname(__FILE__)
// $php_url = "";//dirname($_SERVER['HTTP_HOST']) . '/';//PHP_SELF
$php_url = $_SERVER['HTTP_HOST'] . '/'; //PHP_SELF
$save_path = $uploadDir;
//文件保存目录URL
$save_url = $php_url . 'uploads/';
// nginx服务器端修改绝对路径
//$save_url = "http://172.30.3.11/static/home/kindeditor/attached/";
// var_dump($save_path);
// var_dump($save_url);
// string(46) "D:\Q\code\vue\CodeIgniter-3.1.10\uploads\imgs\"
// string(28) "www.cirest.com:8889/uploads/"
//定义允许上传的文件扩展名
$ext_arr = array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
);
//最大文件大小 10M 默认是1M
$max_size = 10000000;
$save_path = realpath($save_path) . '/';
$save_path = str_replace('\\', '/', $save_path);
//PHP上传失败
if (!empty($_FILES['file']['error'])) {
switch ($_FILES['file']['error']) {
case '1':
$error = '超过php.ini允许的大小。';
break;
case '2':
$error = '超过表单允许的大小。';
break;
case '3':
$error = '图片只有部分被上传。';
break;
case '4':
$error = '请选择图片。';
break;
case '6':
$error = '找不到临时目录。';
break;
case '7':
$error = '写文件到硬盘出错。';
break;
case '8':
$error = 'File upload stopped by extension。';
break;
case '999':
default:
$error = '未知错误。';
}
$this->alert($error);
}
//有上传文件时
if (empty($_FILES) === false) {
//原文件名
$file_name = $_FILES['file']['name'];
//服务器上临时文件名
$tmp_name = $_FILES['file']['tmp_name'];
//文件大小
$file_size = $_FILES['file']['size'];
//检查文件名
if (!$file_name) {
$this->alert("请选择文件。");
}
//检查目录
if (@is_dir($save_path) === false) {
$this->alert("上传目录不存在。");
}
//检查目录写权限
if (@is_writable($save_path) === false) {
$this->alert("上传目录没有写权限。");
}
//检查是否已上传
if (@is_uploaded_file($tmp_name) === false) {
$this->alert("上传失败。");
}
//检查文件大小
if ($file_size > $max_size) {
$this->alert("上传文件大小超过限制(<10M)。");
}
//检查目录名
$dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
if (empty($ext_arr[$dir_name])) {
$this->alert("目录名不正确。");
}
//获得文件扩展名
$temp_arr = explode(".", $file_name);
$file_ext = array_pop($temp_arr);
$file_ext = trim($file_ext);
$file_ext = strtolower($file_ext);
//检查扩展名
if (!in_array($file_ext, $ext_arr[$dir_name])) {
$this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
}
/*
* 以 T+身份证号作为临时目录 , 以身份证作为正式目录
*/
$identify = empty($id) ? '' : trim($id);
if ($identify == '') {
echo "Invalid session identify.";
exit;
}
//创建文件夹
if ($dir_name !== '') {
$save_path .= $dir_name . "/" . $identify . "/";
$save_url .= $dir_name . "/" . $identify . "/";
if (!file_exists($save_path)) {
mkdir($save_path, 0777, true); // true 允许创建多级目录
}
}
$ymd = date("Ym");
$save_path .= $ymd . "/";
$save_url .= $ymd . "/";
if (!file_exists($save_path)) {
mkdir($save_path);
}
//新文件名
$new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
//移动文件
$file_path = $save_path . $new_file_name;
if (move_uploaded_file($tmp_name, $file_path) === false) {
$this->alert("上传文件失败。");
}
@chmod($file_path, 0644);
$file_url = $save_url . $new_file_name;
header('Content-type: text/html; charset=UTF-8');
// Insert file information in the database
// $insert = $db->query("INSERT INTO files (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
$link = "http://" . $file_url;
// http://www.cirest.com:8889/uploads/image/T410000000000000000/201902/20190228071354_96833.png
$message = [
"code" => 20000,
"error" => 0,
"message" => "上传成功",
"link" => $link,
"filepath" => preg_replace('/^http.*uploads/', '/uploads', $link)
];
echo json_encode($message);
// $this->response($message, RestController::HTTP_OK);
// alert里面使用时 exit() 产生的是空,或字符串,使用原生的json_encode返回统一的字符串,在客户端在统一处理成对象
}
}
public function delimg_post()
{
$php_path = dirname(__FILE__) . '/';//dirname($_SERVER['DOCUMENT_ROOT']); dirname(__FILE__)
//文件保存目录路径
$save_path = $php_path . '../../../../';
$save_path = realpath($save_path) . '/';
$save_path = str_replace('\\', '/', $save_path);
// var_dump($save_path);
// "D:/Q/code/vue/CodeIgniter-3.1.10/"
$DelFileName = $this->POST('filename');
$DelFileType = $this->POST('isdir');
$FilePath = $save_path . $DelFileName;
// var_dump($FilePath);return;
if ($DelFileType == 'F') {
if (!is_file($FilePath)) {
$message = [
"code" => 20000,
"data" => "文件不存在 - " . $DelFileName,
"message" => "文件不存在 - " . $DelFileName
];
echo json_encode($message);
} else {
if (!unlink($FilePath)) {
$message = [
"code" => 20000,
"data" => "Error deleting " . $FilePath,
"message" => "Error deleting " . $FilePath
];
echo json_encode($message);
} else {
// 必须返回code 由于前端vue封装的 request 请求,返回数据对code进行判断
$message = [
"code" => 20000,
"data" => '服务器删除成功!',
"message" => '服务器删除成功!'
];
echo json_encode($message);
}
}
exit;
}
if ($DelFileType == 'D') {
if (!@rmdir($FilePath)) {
echo "文件夹 " . $FilePath . " 不为空,不能删除!";
} else {
echo "succeed";
}
exit;
}
}
private function alert($msg)
{
header('Content-type: text/html; charset=UTF-8');
$message = [
"code" => 20000,
"error" => 1,
"message" => $msg
];
echo json_encode($message);
exit();
// var_dump($message);
// $this->response($message, RestController::HTTP_OK);
// die();
}
public function onsubmit_post()
{
$identify = $this->POST('identify');
$phone = $this->POST('phone');
$idinfo = $this->POST('idinfo');
$bankinfo = $this->POST('bankinfo');
// $data = [
// 'identify' => $identify,
// 'phone' => $phone,
// 'idinfo' => $idinfo,
// 'check' => '待审核'
// ];
// 写入数据库表 身份证号,手机号,证件照,文件路径等
$where = [
'identify' => $identify,
'phone' => $phone,
];
$data = [
'idinfo' => $idinfo,
'bankinfo' => $bankinfo,
'check' => '待审核'
];
$result = $this->Base_model->_update_key('upload_tbl', $data, $where);
if ($result) {
$message = [
"code" => 20000,
"message" => '写入数据库表成功,请请待审核通知!',
"data" => array_merge($where, $data)
];
$this->response($message, RestController::HTTP_OK);
} else {
$message = [
"code" => 20000,
"message" => '写入数据库表失败!',
"data" => array_merge($where, $data)
];
$this->response($message, RestController::HTTP_OK);
}
}
// Chevereto 图床免费版本地址:https://github.com/Chevereto/Chevereto-Free
// https://chevereto.com/docs/api-v1
// 上传图片测试
public function chevereto_post()
{
// 1. 上传本地文件时应使用 $fields post base64_encode方法
// Always use POST when uploading local files. Url encoding may alter the base64 source
// due to encoded characters or just by URL request length limit due to GET request.
// base64编码 会导致过长 url request
// var_dump($_FILES); 参考 uploadimg 可以做一些前置校验处理 // 前置判断 if (empty($_FILES) === false)
$key = '5486424e4dfb6b87453dd4bb25c0dcb0';
$url = 'http://172.17.1.110/chevereto/api/1/upload';
// What do we send to chevereto api?
$fields = array(
'key' => urlencode($key),
// The image encoded in base64
'source' => base64_encode(file_get_contents($_FILES["file"]['tmp_name'])),
// format: txt / json txt 只返回图片地址或错误信息 eg.Duplicated upload 较为简洁
'format' => urlencode('json')
);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, sizeof($fields));
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 240);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: '));
//execute post
$result = curl_exec($ch);
//释放curl句柄
curl_close($ch);
echo $result;
//close connection
// 2. 上传远程图片地址可使用 _get source=urlencode{source} 方法即可
// $key = '6a55c7f9fa13813c2da613dc7b5b920b';
// // 设定远程图片地址
// $source = 'https://img3.doubanio.com/view/group_topic/large/public/p67032015.jpg';
// // format: txt / json txt 只返回图片地址或错误信息 eg.Duplicated upload 较为简洁
// $url = 'http://172.17.1.110:8888/api/1/upload/?key={key}&source={source}&format=txt';
// $url = str_replace(array('{key}','{source}'),array($key,urlencode($source)),$url);
//
// //初始化
// $ch = curl_init();
// //设置选项,包括URL
// curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_HEADER, 0);
// //执行并获取HTML文档内容
// $output = curl_exec($ch);
// //释放curl句柄
// curl_close($ch);
// echo $output;
// 失败
// {
// "status_txt": "Bad Request",
// "error": {
// "context": "Exception",
// "code": 102,
// "message": "Duplicated upload"
// },
// "status_code": 400
// }
// 成功
// {
// "status_txt": "OK",
// "image": {
// "image": {
// "size": "89163",
// "url": "http://172.17.1.110:8888/images/2019/07/09/p67032015.jpg",
// "extension": "jpg",
// "mime": "image/jpeg",
// "name": "p67032015",
// "filename": "p67032015.jpg"
// },
// },
// "success": {
// "code": 200,
// "message": "image uploaded"
// },
// "status_code": 200
// }
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 用户
*/
class User extends AdminController
{
protected $base_model = 'customer_model';
}
+69
View File
@@ -0,0 +1,69 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 样品
*/
class Variety extends AdminController
{
protected $base_model = 'variety_model';
protected function _validate_rule(){
return array(
array(
'field' => 'id',
'label' => '序号',
'rules' => 'trim|min_length[0]|max_length[20]'
),
array(
'field' => 'name',
'label' => '名称',
'rules' => 'trim|min_length[0]|max_length[100]'
),
array(
'field' => 'origin',
'label' => '历史起源',
'rules' => 'trim|min_length[0]|max_length[100]'
),
array(
'field' => 'migration',
'label' => '迁徙发展',
'rules' => 'trim|min_length[0]|max_length[100]'
),
array(
'field' => 'characteristic',
'label' => '品种特点',
'rules' => 'trim|min_length[0]|max_length[2000]'
),
array(
'field' => 'fun_story',
'label' => '趣事',
'rules' => 'trim|min_length[0]|max_length[2000]'
),
array(
'field' => 'gene_disease',
'label' => '常见遗传病',
'rules' => 'trim|min_length[0]|max_length[2000]'
),
array(
'field' => 'species',
'label' => '物种',
'rules' => 'trim|integer|min_length[0]|max_length[2]'
),
);
}
protected function _import_field_map(){
return [
'名称'=>'name',
'历史起源'=>'origin',
'迁徙发展'=>'migration',
'犬种特点'=>'characteristic',
'品种特点'=>'characteristic',
'趣事'=>'fun_story',
'常见遗传病'=>'gene_disease',
'species'=>'species',
];
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
class Dept extends RestController
{
function __construct()
{
parent::__construct();
$this->load->model('Base_model');
$this->load->model('Dept_model');
// $this->config->load('config', true);
}
// 增
function add_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms);return;
if ($this->Base_model->_key_exists('sys_dept', ['name' => $parms['name']])) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 机构名称重复'
];
$this->response($message, RestController::HTTP_OK);
}
$dept_id = $this->Base_model->_insert_key('sys_dept', $parms);
if (!$dept_id) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 机构新增失败'
];
$this->response($message, RestController::HTTP_OK);
}
// 超级管理员用户的超级管理员角色自动归属该机构
$user_role_id = $this->Base_model->_insert_key('sys_user_role', ["user_id" => 1, "role_id" => 1, "dept_id" => $dept_id]);
if (!$user_role_id) {
var_dump($this->uri->uri_string . ' 超级管理员用户的超级管理员角色自动归属该机构, 失败...');
var_dump(["user_id" => 1, "role_id" => 1, "dept_id" => $dept_id]);
return;
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['name'] . ' - 机构新增成功'
];
$this->response($message, RestController::HTTP_OK);
}
// 改
function edit_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
// $id = $this->post('id'); // POST param
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['path']);
// 参数检验/数据预处理
$id = $parms['id'];
unset($parms['id']); // 剃除索引id
unset($parms['children']); // 剃除传递上来的子节点信息
if ($id == $parms['pid']) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 上级机构不能为自己'
];
$this->response($message, RestController::HTTP_OK);
}
$where = ["id" => $id];
if (!$this->Base_model->_update_key('sys_dept', $parms, $where)) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 机构更新错误'
];
$this->response($message, RestController::HTTP_OK);
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['name'] . ' - 机构更新成功'
];
$this->response($message, RestController::HTTP_OK);
}
// 删
function del_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['path']);
// 参数检验/数据预处理
// 含有子节点不允许删除
$hasChild = $this->Dept_model->hasChildDept($parms['id']);
if ($hasChild) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 存在子节点不能删除'
];
$this->response($message, RestController::HTTP_OK);
}
// 先删除外键关联表
if (!$this->Base_model->_delete_key('sys_user_role', ['dept_id' => $parms['id']])) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => '删除关联表失败 ' . json_encode($parms)
];
$this->response($message, RestController::HTTP_OK);
}
// 删除基础表 sys_dept
if (!$this->Base_model->_delete_key('sys_dept', ['id' => $parms['id']])) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 机构删除失败'
];
$this->response($message, RestController::HTTP_OK);
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['name'] . ' - 机构删除成功'
];
$this->response($message, RestController::HTTP_OK);
}
// 查
function view_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
$DeptArr = $this->Dept_model->getDeptList();
$DeptTree = $this->permission->genDeptTree($DeptArr, 'id', 'pid', 0);
$message = [
"code" => 20000,
"data" => $DeptTree,
];
$this->response($message, RestController::HTTP_OK);
}
}
+342
View File
@@ -0,0 +1,342 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
class Menu extends RestController
{
function __construct()
{
parent::__construct();
$this->load->model('Base_model');
// $this->config->load('config', true);
}
public function index_get()
{
$this->load->view('login_view');
}
public function insertx_post()
{
// $id = $this->post('id'); // POST param
$parms = $this->post(); // 获取表单参数,类型为数组
var_dump($parms);
$result = $this->Base_model->_insert_key('sys_role_perm', $parms);
var_dump($result);
}
public function gettest_post()
{
$result = $this->Base_model->_get_key('sys_perm', 'perm_type,r_id rid', 'perm_type="role" and r_id=1');
var_dump($result);
var_dump($result[0]['perm_type']);
var_dump($this->uri->uri_string);
var_dump($this->uri);
}
public function testapi_get()
{
echo "test api ok...";
echo APPPATH . "\n";
echo SELF . "\n";
echo BASEPATH . "\n";
echo FCPATH . "\n";
echo SYSDIR . "\n";
var_dump($this->config->item('rest_language'));
var_dump($this->config->item('language'));
var_dump($this->config);
// $message = [
// "code" => 20000,
// "data" => [
// "__FUNCTION__" => __FUNCTION__,
// "__CLASS__" => __CLASS__,
// "uri" => $this->uri
// ],
//
// ];
// "data": {
// "__FUNCTION__": "router_get",
// "__CLASS__": "User",
// "uri": {
// "keyval": [],
// "uri_string": "api/v2/user/router",
// "segments": {
// "1": "api",
// "2": "v2",
// "3": "user",
// "4": "router"
// },
}
public function phpinfo_get()
{
phpinfo();
}
public function testdb_get()
{
$this->load->database();
$query = $this->db->query("show tables");
var_dump($query);
var_dump($query->result());
var_dump($query->row_array());
// 有结果表明数据库连接正常 reslut() 与 row_array 结果有时不太一样
// 一般加载到时model里面使用。
}
// 增
function add_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
// $id = $this->post('id'); // POST param
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms);
// var_dump($parms['path']);
// 参数检验/数据预处理
// 菜单类型为目录
if (!$parms['type']) {
$parms['component'] = 'Layout';
}
$menu_id = $this->Base_model->_insert_key('sys_menu', $parms);
if (!$menu_id) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['title'] . ' - 菜单添加失败'
];
$this->response($message, RestController::HTTP_OK);
}
// 生成该菜单对应的权限: sys_perm, 权限类型为: menu, 生成唯一的 perm_id
$perm_id = $this->Base_model->_insert_key('sys_perm', ['perm_type' => 'menu', "r_id" => $menu_id]);
if (!$perm_id) {
var_dump($this->uri->uri_string . ' 生成该菜单对应的权限: sys_perm, 失败...');
var_dump(['perm_type' => 'menu', "r_id" => $menu_id]);
return;
}
// 超级管理员角色自动拥有该权限 perm_id
$role_perm_id = $this->Base_model->_insert_key('sys_role_perm', ["role_id" => 1, "perm_id" => $perm_id]);
if (!$role_perm_id) {
var_dump($this->uri->uri_string . ' 超级管理员角色自动拥有该权限 perm_id, 失败...');
var_dump(["role_id" => 1, "perm_id" => $perm_id]);
return;
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['title'] . ' - 菜单添加成功'
];
$this->response($message, RestController::HTTP_OK);
}
// 改
function edit_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
// $id = $this->post('id'); // POST param
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['path']);
// 参数检验/数据预处理
if ($parms['id'] == $parms['pid']) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => '父节点不能是自己'
];
$this->response($message, RestController::HTTP_OK);
}
// 菜单类型为目录
if ($parms['type'] == 0) {
$parms['component'] = 'Layout';
}
// 菜单类型为功能按钮时
if ($parms['type'] == 2) {
$parms['component'] = '';
$parms['icon'] = '';
}
$id = $parms['id'];
unset($parms['id']); // 择出索引id
$where = ["id" => $id];
if (!$this->Base_model->_update_key('sys_menu', $parms, $where)) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['title'] . ' - 菜单更新错误'
];
$this->response($message, RestController::HTTP_OK);
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['title'] . ' - 菜单更新成功'
];
$this->response($message, RestController::HTTP_OK);
}
// 删
function del_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['path']);
// 参数检验/数据预处理
// 存在子节点 不能删除返回
$hasChild = $this->Base_model->hasChildMenu($parms['id']);
if ($hasChild) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['title'] . ' - 存在子节点不能删除'
];
$this->response($message, RestController::HTTP_OK);
}
// 删除外键关联表 sys_role_perm , sys_perm, sys_menu
// 1. 根据sys_menu id及'menu' 查找 perm_id
// 2. 删除sys_role_perm 中perm_id记录
// 3. 删除sys_perm中 perm_type='menu' and r_id = menu_id 记录,即第1步中获取的 perm_id, 一一对应
// 4. 删除sys_menu 中 id = menu_id 的记录
$where = 'perm_type="menu" and r_id=' . $parms['id'];
$arr = $this->Base_model->_get_key('sys_perm', '*', $where);
if (empty($arr)) {
var_dump($this->uri->uri_string . ' 未查找到 sys_perm 表中记录');
var_dump($where);
return;
}
$perm_id = $arr[0]['id']; // 正常只有一条记录
$this->Base_model->_delete_key('sys_role_perm', ['perm_id' => $perm_id]);
$this->Base_model->_delete_key('sys_perm', ['id' => $perm_id]);
// 删除基础表 sys_menu
if (!$this->Base_model->_delete_key('sys_menu', $parms)) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['title'] . ' - 菜单删除错误'
];
$this->response($message, RestController::HTTP_OK);
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['title'] . ' - 菜单删除成功'
];
$this->response($message, RestController::HTTP_OK);
}
// 查
function view_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
$MenuTreeArr = $this->permission->getPermission($Token, 'menu', true);
$MenuTree = $this->permission->genVueMenuTree($MenuTreeArr, 'id', 'pid', 0);
$message = [
"code" => 20000,
"data" => $MenuTree,
];
$this->response($message, RestController::HTTP_OK);
}
// 根据token拉取 treeselect 下拉选项菜单
function treeoptions_get()
{
// 此 uri 可不做权限/token过期验证,则在菜单里,可以不加入此项路由path /sys/menu/treeoptions。
//
// $uri = $this->uri->uri_string;
// $Token = $this->input->get_request_header('X-Token', TRUE);
// $retPerm = $this->permission->HasPermit($Token, $uri);
// if ($retPerm['code'] != 50000) {
// $this->response($retPerm, RestController::HTTP_OK);
// return;
// }
$Token = $this->input->get_request_header('X-Token', TRUE);
$MenuTreeArr = $this->permission->getPermission($Token, 'menu', false);
array_unshift($MenuTreeArr, ['id' => 0, 'pid' => -1, 'title' => '顶级菜单']);
$MenuTree = $this->permission->genVueMenuTree($MenuTreeArr, 'id', 'pid', -1);
$message = [
"code" => 20000,
"data" => $MenuTree,
];
$this->response($message, RestController::HTTP_OK);
}
function list_get()
{
// $result = $this->some_model();
$result['success'] = TRUE;
if ($result['success']) {
$List = array(
array('order_no' => '201805138451313131', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'success'),
array('order_no' => '300000000000000000', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'pending'),
array('order_no' => '444444444444444444', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'success'),
array('order_no' => '888888888888888888', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'pending'),
);
$message = [
"code" => 20000,
"data" => [
"total" => count($List),
"items" => $List
]
];
$this->response($message, RestController::HTTP_OK);
} else {
$message = [
"code" => 50008,
"message" => 'Login failed, unable to get user details.'
];
$this->response($message, RestController::HTTP_OK);
}
}
}
+455
View File
@@ -0,0 +1,455 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
class Role extends RestController
{
function __construct()
{
parent::__construct();
$this->load->model('Base_model');
$this->load->model('Role_model');
// $this->config->load('config', true);
}
public function index_get()
{
$this->load->view('login_view');
}
public function insertx_post()
{
// $id = $this->post('id'); // POST param
$parms = $this->post(); // 获取表单参数,类型为数组
var_dump($parms);
$result = $this->Base_model->_insert_key('sys_role_perm', $parms);
var_dump($result);
}
public function gettest_post()
{
$result = $this->Base_model->_get_key('sys_perm', 'perm_type,r_id rid', 'perm_type="role" and r_id=1');
var_dump($result);
var_dump($result[0]['perm_type']);
var_dump($this->uri->uri_string);
var_dump($this->uri);
}
public function testapi_get()
{
echo "test api ok...";
echo APPPATH . "\n";
echo SELF . "\n";
echo BASEPATH . "\n";
echo FCPATH . "\n";
echo SYSDIR . "\n";
var_dump($this->config->item('rest_language'));
var_dump($this->config->item('language'));
var_dump($this->config);
// $message = [
// "code" => 20000,
// "data" => [
// "__FUNCTION__" => __FUNCTION__,
// "__CLASS__" => __CLASS__,
// "uri" => $this->uri
// ],
//
// ];
// "data": {
// "__FUNCTION__": "router_get",
// "__CLASS__": "User",
// "uri": {
// "keyval": [],
// "uri_string": "api/v2/user/router",
// "segments": {
// "1": "api",
// "2": "v2",
// "3": "user",
// "4": "router"
// },
}
public function phpinfo_get()
{
phpinfo();
}
public function testdb_get()
{
$this->load->database();
$query = $this->db->query("show tables");
var_dump($query);
var_dump($query->result());
var_dump($query->row_array());
// 有结果表明数据库连接正常 reslut() 与 row_array 结果有时不太一样
// 一般加载到时model里面使用。
}
// 增
function add_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
$parms = $this->post(); // 获取表单参数,类型为数组
if ($this->Base_model->_key_exists('sys_role', ['name' => $parms['name']])) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色名重复'
];
$this->response($message, RestController::HTTP_OK);
}
// 加入新增时间
$parms['create_time'] = time();
$role_id = $this->Base_model->_insert_key('sys_role', $parms);
if (!$role_id) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色新增失败'
];
$this->response($message, RestController::HTTP_OK);
}
// 生成该角色对应的权限: sys_perm, 权限类型为: role, 生成唯一的 perm_id
$perm_id = $this->Base_model->_insert_key('sys_perm', ['perm_type' => 'role', "r_id" => $role_id]);
if (!$perm_id) {
var_dump($this->uri->uri_string . ' 生成该角色对应的权限: sys_perm, 失败...');
var_dump(['perm_type' => 'role', "r_id" => $role_id]);
return;
}
// 超级管理员角色自动拥有该权限 perm_id
$role_perm_id = $this->Base_model->_insert_key('sys_role_perm', ["role_id" => 1, "perm_id" => $perm_id]);
if (!$role_perm_id) {
var_dump($this->uri->uri_string . ' 超级管理员角色自动拥有该权限 perm_id, 失败...');
var_dump(["role_id" => 1, "perm_id" => $perm_id]);
return;
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['name'] . ' - 角色新增成功'
];
$this->response($message, RestController::HTTP_OK);
}
// 改
function edit_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
// $id = $this->post('id'); // POST param
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['path']);
// 参数检验/数据预处理
// 超级管理员角色不允许修改
if ($parms['id'] == 1) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色不允许修改'
];
$this->response($message, RestController::HTTP_OK);
}
$id = $parms['id'];
unset($parms['id']); // 剃除索引id
// 加入更新时间
$parms['update_time'] = time();
$where = ["id" => $id];
if (!$this->Base_model->_update_key('sys_role', $parms, $where)) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色更新错误'
];
$this->response($message, RestController::HTTP_OK);
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['name'] . ' - 角色更新成功'
];
$this->response($message, RestController::HTTP_OK);
}
// 删
function del_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['path']);
// 参数检验/数据预处理
// 超级管理员角色不允许删除
if ($parms['id'] == 1) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色不允许删除'
];
$this->response($message, RestController::HTTP_OK);
}
// 删除外键关联表 sys_role_perm , sys_perm, sys_role, sys_user_role
// 1. 根据sys_role id及'role' 查找 perm_id
// 2. 删除sys_role_perm 中perm_id记录
// 3. 删除sys_perm中 perm_type='role' and r_id = role_id 记录,即第1步中获取的 perm_id, 一一对应
// 4. 删除sys_user_role role_id 记录
// 5. 删除sys_role 中 id = role_id 的记录
$where = 'perm_type="role" and r_id=' . $parms['id'];
$arr = $this->Base_model->_get_key('sys_perm', '*', $where);
if (empty($arr)) {
var_dump($this->uri->uri_string . ' 未查找到 sys_perm 表中记录');
var_dump($where);
return;
}
$perm_id = $arr[0]['id']; // 正常只有一条记录
$this->Base_model->_delete_key('sys_role_perm', ['perm_id' => $perm_id]); // 必须删除权限id 因为超级管理员角色自动拥有该权限否则会造成删除关联错误
$this->Base_model->_delete_key('sys_role_perm', ['role_id' => $parms['id']]); // 再删除该角色对应的权限id(原有的菜单)
$this->Base_model->_delete_key('sys_perm', ['id' => $perm_id]);
$this->Base_model->_delete_key('sys_user_role', ['role_id' => $parms['id']]);
// 删除基础表 sys_role
if (!$this->Base_model->_delete_key('sys_role', $parms)) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => $parms['name'] . ' - 角色删除错误'
];
$this->response($message, RestController::HTTP_OK);
}
$message = [
"code" => 20000,
"type" => 'success',
"message" => $parms['name'] . ' - 角色删除成功'
];
$this->response($message, RestController::HTTP_OK);
}
// 查
function view_post()
{
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
$RoleArr = $this->Role_model->getRoleList();
$message = [
"code" => 20000,
"data" => $RoleArr,
];
$this->response($message, RestController::HTTP_OK);
}
// 获取所有菜单 不需权限验证
function allmenus_get()
{
$MenuTreeArr = $this->Role_model->getAllMenus();
if (empty($MenuTreeArr)) {
$message = [
"code" => 20000,
"data" => $MenuTreeArr,
"message" => "数据库表中没有菜单"
];
$this->response($message, RestController::HTTP_OK);
}
$MenuTree = $this->permission->genVueMenuTree($MenuTreeArr, 'id', 'pid', 0);
$message = [
"code" => 20000,
"data" => $MenuTree,
];
$this->response($message, RestController::HTTP_OK);
}
// 获取所有角色带perm_id 不需权限验证
function allroles_get()
{
$AllRolesArr = $this->Role_model->getAllRoles();
if (empty($AllRolesArr)) {
$message = [
"code" => 20000,
"data" => $AllRolesArr,
"message" => "数据库表中没有角色"
];
$this->response($message, RestController::HTTP_OK);
}
$message = [
"code" => 20000,
"data" => $AllRolesArr,
];
$this->response($message, RestController::HTTP_OK);
}
// 获取角色拥有的菜单权限 不需权限验证
function rolemenu_post()
{
$parms = $this->post(); // 获取表单参数,类型为数组
$RoleId = $parms['roleId'];
$MenuTreeArr = $this->Role_model->getRoleMenu($RoleId);
$message = [
"code" => 20000,
"data" => $MenuTreeArr,
];
$this->response($message, RestController::HTTP_OK);
}
// 获取角色拥有的角色权限 不需权限验证
function rolerole_post()
{
$parms = $this->post(); // 获取表单参数,类型为数组
$RoleId = $parms['roleId'];
$RoleRoleArr = $this->Role_model->getRoleRole($RoleId);
$message = [
"code" => 20000,
"data" => $RoleRoleArr,
];
$this->response($message, RestController::HTTP_OK);
}
// 保存角色对应权限
function saveroleperm_post()
{
$parms = $this->post(); // 获取表单参数,类型为数组
// var_dump($parms['roleId']);
// var_dump($parms['rolePerms']);
// 参数检验/数据预处理
// 超级管理员角色不允许删除
if ($parms['roleId'] == 1) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => '超级管理员角色拥有所有权限,不允许修改!'
];
$this->response($message, RestController::HTTP_OK);
}
$RolePermArr = $this->Role_model->getRolePerm($parms['roleId']);
$AddArr = $this->permission->array_diff_assoc2($parms['rolePerms'], $RolePermArr);
// var_dump('------------只存在于前台传参 做添加操作-------------');
// var_dump($AddArr);
$failed = false;
$failedArr = [];
foreach ($AddArr as $k => $v) {
$ret = $this->Base_model->_insert_key('sys_role_perm', $v);
if (!$ret) {
$failed = true;
array_push($failedArr, $v);
}
}
if ($failed) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => '授权失败 ' . json_encode($failedArr)
];
$this->response($message, RestController::HTTP_OK);
}
$DelArr = $this->permission->array_diff_assoc2($RolePermArr, $parms['rolePerms']);
// var_dump('------------只存在于后台数据库 删除操作-------------');
// var_dump($DelArr);
$failed = false;
$failedArr = [];
foreach ($DelArr as $k => $v) {
$ret = $this->Base_model->_delete_key('sys_role_perm', $v);
if (!$ret) {
$failed = true;
array_push($failedArr, $v);
}
}
if ($failed) {
$message = [
"code" => 20000,
"type" => 'error',
"message" => '授权失败 ' . json_encode($failedArr)
];
$this->response($message, RestController::HTTP_OK);
}
$message = [
"code" => 20000,
"type" => 'success',
"data" => $parms,
"message" => '授权操作成功',
];
$this->response($message, RestController::HTTP_OK);
}
function list_get()
{
// $result = $this->some_model();
$result['success'] = TRUE;
if ($result['success']) {
$List = array(
array('order_no' => '201805138451313131', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'success'),
array('order_no' => '300000000000000000', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'pending'),
array('order_no' => '444444444444444444', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'success'),
array('order_no' => '888888888888888888', 'timestamp' => 'iphone 7 ', 'username' => 'iphone 7 ', 'price' => 399, 'status' => 'pending'),
);
$message = [
"code" => 20000,
"data" => [
"total" => count($List),
"items" => $List
]
];
$this->response($message, RestController::HTTP_OK);
} else {
$message = [
"code" => 50008,
"message" => 'Login failed, unable to get user details.'
];
$this->response($message, RestController::HTTP_OK);
}
}
}
File diff suppressed because it is too large Load Diff
+116
View File
@@ -0,0 +1,116 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
class Widgets extends RestController
{
function index_get($id = '')
{
// Example data for testing.
$widgets = array(
1 => array('id' => 1, 'name' => 'sprocket'),
2 => array('id' => 2, 'name' => 'gear')
);
// get参数为空
if (!$id) {
$id = $this->get('id');
var_dump($id);
}
if (!$id) {
//$widgets = $this->widgets_model->getWidgets();
if ($widgets)
$this->response($widgets, 200); // 200 being the HTTP response code
else
$this->response(array('error' => 'Couldn\'t find any widgets!'), 404);
}
// get参数不为空
//$widget = $this->widgets_model->getWidget($id);
$widget = @$widgets[$id]; // test code
if ($widget)
$this->response($widget, 200); // 200 being the HTTP response code
else
$this->response(array('error' => 'Widget could not be found'), 404);
}
function index_post()
{
$data = $this->_post_args;
echo json_encode($data);
try {
//$id = $this->widgets_model->createWidget($data);
$id = 3; // test code
//throw new Exception('Invalid request data', 400); // test code
//throw new Exception('Widget already exists', 409); // test code
} catch (Exception $e) {
// Here the model can throw exceptions like the following:
// * For invalid input data: new Exception('Invalid request data', 400)
// * For a conflict when attempting to create, like a resubmit: new Exception('Widget already exists', 409)
$this->response(array('error' => $e->getMessage()), $e->getCode());
}
if ($id) {
$widget = array('id' => $id, 'name' => $data['name']); // test code
//$widget = $this->widgets_model->getWidget($id);
$this->response($widget, 201); // 201 being the HTTP response code
} else
$this->response(array('error' => 'Widget could not be created'), 404);
}
public function index_put()
{
$data = $this->_put_args;
try {
//$id = $this->widgets_model->updateWidget($data);
$id = $data['id']; // test code
//throw new Exception('Invalid request data', 400); // test code
} catch (Exception $e) {
// Here the model can throw exceptions like the following:
// * For invalid input data: new Exception('Invalid request data', 400)
// * For a conflict when attempting to create, like a resubmit: new Exception('Widget already exists', 409)
$this->response(array('error' => $e->getMessage()), $e->getCode());
}
if ($id) {
$widget = array('id' => $data['id'], 'name' => $data['name']); // test code
//$widget = $this->widgets_model->getWidget($id);
$this->response($widget, 200); // 200 being the HTTP response code
} else
$this->response(array('error' => 'Widget could not be found'), 404);
}
function index_delete($id = '')
{
// Example data for testing.
$widgets = array(
1 => array('id' => 1, 'name' => 'sprocket'),
2 => array('id' => 2, 'name' => 'gear'),
3 => array('id' => 3, 'name' => 'nut')
);
if (!$id) {
$id = $this->get('id');
}
if (!$id) {
$this->response(array('error' => 'An ID must be supplied to delete a widget'), 400);
}
//$widget = $this->widgets_model->getWidget($id);
$widget = @$widgets[$id]; // test code
if ($widget) {
try {
//$this->widgets_model->deleteWidget($id);
//throw new Exception('Forbidden', 403); // test code
} catch (Exception $e) {
// Here the model can throw exceptions like the following:
// * Client is not authorized: new Exception('Forbidden', 403)
$this->response(array('error' => $e->getMessage()), $e->getCode());
}
$this->response($widget, 200); // 200 being the HTTP response code
} else
$this->response(array('error' => 'Widget could not be found'), 404);
}
}
+383
View File
@@ -0,0 +1,383 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use EasyWeChat\Foundation\Application as OfficialAccount;
class Active extends ApiController
{
private $_user_id = 0;
function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->model('series_number_model');
$this->load->model('package_model');
$this->load->model('series_number_model');
$this->load->model('sample_model');
$this->load->model('customer_model');
//跨域
header("Access-Control-Allow-Origin: ".$this->config->config['allow-origin']['user']);
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header('Access-Control-Allow-Headers:x-requested-with,content-type');
header('Access-Control-Allow-Credentials: true');
//未登录告警
if(empty($this->session->{Customer_model::SESSION_KEY})){
$this->error('您的授权信息不存在或已过期,请从微信公众号菜单进入');
}
$this->_user_id = $this->session->{Customer_model::SESSION_KEY};
}
public function ticket_get()
{
$config = [
'app_id' => WEIXIN_APPID,
'secret' => WEIXIN_APPSECERT,
'token' => WEIXIN_TOKEN,
'aes_key' => WEIXIN_EncodingAESKey,
'response_type' => 'array',
];
$app = new OfficialAccount($config);
$app->js->setUrl($_SERVER['HTTP_REFERER']);
$config = $app->js->config(array('updateAppMessageShareData', 'updateTimelineShareData', 'scanQRCode'), $debug = false, $beta = false, $json = true);
$this->success(['config'=>json_decode($config)]);
}
public function check_number_post()
{
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[5]|max_length[20]'
),
);
$data = $this->json_validation($config);
$series = $this->series_number_model->get($data['device_id'],'device_id');
if(!$series){
$this->error('序列号不存在');
}
$sample = $this->sample_model->get($series['id'],'series_id');
if($sample){
$this->error('序列号已使用');
}
$package = $this->package_model->get($series['package_ori']);
if(!$package){
$this->error('套餐不存在');
}
$this->success(['package'=>$package]);
}
public function create_post()
{
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[5]|max_length[20]'
),
array(
'field' => 'name',
'label' => '用户姓名',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'tel',
'label' => '手机',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => '邮箱',
'rules' => 'required'
),
array(
'field' => 'pet_name',
'label' => '宠物名称',
'rules' => 'required'
),
array(
'field' => 'pet_age',
'label' => '宠物年龄',
'rules' => 'required'
),
array(
'field' => 'pet_breed',
'label' => '宠物品系',
'rules' => 'required'
),
array(
'field' => 'pet_sex',
'label' => '宠物性别',
'rules' => 'required'
),
array(
'field' => 'pet_birthday',
'label' => '宠物生日',
'rules' => 'required'
),
array(
'field' => 'pet_species',
'label' => '物种',
'rules' => 'required'
),
array(
'field' => 'pet_img',
'label' => '宠物头像地址',
'rules' => 'required'
),
array(
'field' => 'package_id',
'label' => '检测套餐',
'rules' => 'required'
),
array(
'field' => 'note',
'label' => '其他需求',
'rules' => 'required'
)
);
$data = $this->json_validation($config);
$series = $this->series_number_model->get($data['device_id'],'device_id');
if(!$series){
$this->error('序列号不存在');
}
$sample = $this->sample_model->get($series['id'],'series_id');
if($sample){
$this->error('序列号已使用');
}
$package = $this->package_model->get($series['package_ori']);
if(!$package){
$this->error('套餐不存在');
}
$ret = $this->sample_model->add(
array_intersect_key(array_column($config,'field'),$data)
);
if($ret){
$this->success();
}else{
$this->error('提交失败');
}
}
//获取需回寄的样品
public function ship_get()
{
$ret = $this->sample_model->get($this->_user_id,'user_id',true);
//只展示需回寄样品
foreach ($ret as $key=>$item) {
if($item['step'] >= Sample_model::STEP_SENT){
unset($ret[$key]);
}
}
$this->success($ret);
}
//样品回寄
public function ship_post()
{
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[5]|max_length[20]'
),
array(
'field' => 'name',
'label' => '用户姓名',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'tel',
'label' => '手机',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => '邮箱',
'rules' => 'required'
),
array(
'field' => 'pet_name',
'label' => '宠物名称',
'rules' => 'required'
),
array(
'field' => 'pet_age',
'label' => '宠物年龄',
'rules' => 'required'
),
array(
'field' => 'pet_breed',
'label' => '宠物品系',
'rules' => 'required'
),
array(
'field' => 'pet_sex',
'label' => '宠物性别',
'rules' => 'required'
),
array(
'field' => 'pet_birthday',
'label' => '宠物生日',
'rules' => 'required'
),
array(
'field' => 'pet_species',
'label' => '物种',
'rules' => 'required'
),
array(
'field' => 'pet_img',
'label' => '宠物头像地址',
'rules' => 'required'
),
array(
'field' => 'package_id',
'label' => '检测套餐',
'rules' => 'required'
),
array(
'field' => 'note',
'label' => '其他需求',
'rules' => 'required'
)
);
$data = $this->json_validation($config);
$series = $this->series_number_model->get($data['device_id'],'device_id');
}
//进度查询:样品列表
public function list_get()
{
$ret = $this->sample_model->get($this->_user_id,'user_id',true);
$this->success($ret);
}
//进度查询:样品进度详情
public function detail_get()
{
$config = array(
array(
'field' => 'id',
'label' => '样品ID',
'rules' => 'trim|required|min_length[5]|max_length[20]'
)
);
$this->load->library('form_validation');
$data = $this->input->get();
$this->form_validation->set_data($data);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() === FALSE)
{
$this->error('参数错误',$this->form_validation->error_array());
}
$row = $this->sample_model->get(trim($data['id']),'device_id');
if($row['user_id'] != $this->_user_id){
$this->error('您没有权限查看该样品');
}
$this->success($row);
}
//进度查询:快递详情
public function track_get()
{
$json_params = file_get_contents('php://input');
$data = json_decode($json_params, true);
$config = array(
array(
'field' => 'device_id',
'label' => '序列号',
'rules' => 'trim|required|min_length[5]|max_length[20]'
),
array(
'field' => 'name',
'label' => '用户姓名',
'rules' => 'trim|required|min_length[2]|max_length[20]',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'tel',
'label' => '手机',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => '邮箱',
'rules' => 'required'
),
array(
'field' => 'pet_name',
'label' => '宠物名称',
'rules' => 'required'
),
array(
'field' => 'pet_age',
'label' => '宠物年龄',
'rules' => 'required'
),
array(
'field' => 'pet_breed',
'label' => '宠物品系',
'rules' => 'required'
),
array(
'field' => 'pet_sex',
'label' => '宠物性别',
'rules' => 'required'
),
array(
'field' => 'pet_birthday',
'label' => '宠物生日',
'rules' => 'required'
),
array(
'field' => 'pet_species',
'label' => '物种',
'rules' => 'required'
),
array(
'field' => 'pet_img',
'label' => '宠物头像地址',
'rules' => 'required'
),
array(
'field' => 'package_id',
'label' => '检测套餐',
'rules' => 'required'
),
array(
'field' => 'note',
'label' => '其他需求',
'rules' => 'required'
)
);
$this->load->library('form_validation');
$this->load->model('package_model');
$this->form_validation->set_data($data);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == FALSE)
{
print_r($this->form_validation->error_array());
$this->error('错误');
}
else
{
echo '成功';
}
$this->success();
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* @author luoxuancai 2017/7/13
*/
class Report extends CI_Controller {
public function __construct()
{
parent::__construct();
//$this->load->model('Model_UsersInfo');
$this->load->model('report_model');
}
//新报告检测
public function index()
{
//未完成的检测
$list = $this->Model_UsersInfo->get_uncompleted_list();
//扫描目录
foreach ($list as $userInfo) {
//print_r($this->report_model->get_report_file($userInfo['device_id']));die;
if($this->report_model->is_report_ready($userInfo['device_id'])){
//设置完成
$this->Model_UsersInfo->set_completed($userInfo['id']);
//发送微信通知
}
}
}
//快递
public function ship()
{
die('dfdfd');
//未完成的检测
$list = $this->Model_UsersInfo->get_uncompleted_list();
//扫描目录
foreach ($list as $userInfo) {
//print_r($this->report_model->get_report_file($userInfo['device_id']));die;
if($this->report_model->is_report_ready($userInfo['device_id'])){
//设置完成
$this->Model_UsersInfo->set_completed($userInfo['id']);
//发送微信通知
}
}
}
//快递
public function test()
{
die('dfdfd');
}
}
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+322
View File
@@ -0,0 +1,322 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
//统一API的返回
class ApiController extends RestController
{
protected $_user_id = 0;
protected $http_status = [
'METHOD_NOT_ALLOWED'=>400
];
protected function json_input($require=TRUE){
$json_params = file_get_contents('php://input');
if(empty($json_params)){
if($require){
$this->error('请输入参数');
}
return [];
}
try{
return json_decode($json_params, true);
}catch (Exception $e){
return [];
}
}
protected function error($msg='',$data=[]){
$message = [
"code" => 50000,
"data" => $data,
"message" => $msg
];
$this->response($message, parent::HTTP_OK);
die;
}
public function success($data=[],$msg=''){
$message = [
"code" => 20000,
"data" => $data,
"message" => $msg
];
$this->response($message, parent::HTTP_OK);
die;
}
//接收请求检验
function json_validation($config){
$data = $this->json_input();
$this->load->library('form_validation');
$this->form_validation->set_data($data);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() === FALSE)
{
$error_arr = $this->form_validation->error_array();
$this->error(reset($error_arr),$error_arr);
}
return $data;
}
/**
* 服务器端请求校验
* @DATE 20220522
**/
function checkUser(){
//尝试跟服务端对接
$ret = $this->serverSign();
if($ret !== null){
if(!$ret){
$this->error('您的签名错误');
}
//通过头部的open id获取用户信息
$this->load->model('customer_model');
$customer = $this->customer_model->get(
$this->_head_args['Uah-Open-Id'],
'openid'
);
if(!$customer){
$this->error('用户OPENID不存在');
}
$this->_user_id = $customer['id'];
return;
}
//跟前端对接,未登录告警
if(empty($this->session->{Customer_model::SESSION_KEY})){
$this->error('您的授权信息不存在或已过期,请从微信公众号菜单进入');
}
$this->_user_id = $this->session->{Customer_model::SESSION_KEY};
}
/**
* 服务器端请求校验
* @DATE 20220522
**/
function serverSign(){
$str = '';
foreach (['Uah-Open-Id','Uah-Timestamp'] as $val) {
if(empty($this->_head_args[$val])){
return null;
}
$str.=$this->_head_args[$val];
}
if(empty($this->_head_args['Uah-Sign'])){
return null;
}
$conf = $this->config->item('uah_server_token');
//echo $str.$conf;
//echo md5($str.$conf);
//echo $this->_head_args['Uah-Sign'];
return md5($str.$conf) == $this->_head_args['Uah-Sign'];
}
}
//提供后台的统一方法
class AdminController extends ApiController
{
protected $base_model = 'sample_model';
public function __construct()
{
parent::__construct();
$this->load->model($this->base_model);
$uri = $this->uri->uri_string;
$Token = $this->input->get_request_header('X-Token', TRUE);
$retPerm = $this->permission->HasPermit($Token, $uri);
if ($retPerm['code'] != 50000) {
$this->response($retPerm, RestController::HTTP_OK);
}
}
//单条更新的校验规则
protected function _validate_rule(){
return [];
}
//批量导入的字段对应表
protected function _import_field_map(){
return [];
}
function list_get()
{
return $this->_list_get();
}
function _list_get($is_return = false, $select = null)
{
$filters = $this->input->get();
$page = $this->input->get('page');
$limit = $this->input->get('limit');
$page = empty($page)?1:$page;
$limit = empty($limit)?50:$limit;
$sort = $this->input->get('sort');
$sort_type = substr($sort,0,1);
$sort_name = 'base.'.substr($sort,1);
$sort_type = $sort_type=='-'?'DESC':'ASC';
unset($filters['sort']);
unset($filters['limit']);
unset($filters['page']);
$items = $this->{$this->base_model}->listing($filters, ($page-1)*$limit,$limit,$select,$sort_name,$sort_type);
if($is_return){
return $items;
}
$this->success($items);
}
function detail_get()
{
return $this->_detail_get();
}
function _detail_get($is_return = false)
{
$id = $this->security->xss_clean($this->input->get('id'));
$item = $this->{$this->base_model}->get($id);
if($is_return){
return $item;
}
$this->success([
"item" => $item
]);
}
function update_post()
{
$this->_update_post($this->_validate_rule());
}
function _update_post($validate_config,$data = [])
{
if(empty($data)){
$data = $this->json_validation($validate_config);
}
$fields = array_column($validate_config,'field');
foreach ($data as $key => $val) {
if(!in_array($key,$fields)){
unset($data[$key]);
}
}
if(empty($data['id'])){
$ret = $this->{$this->base_model}->add($data);
if($ret === -1){
$this->error('名称重复');
}
}else{
$this->{$this->base_model}->update($data, ['id'=>$data['id']]);
}
$this->success();
}
function delete_post()
{
return $this->_delete_post();
}
function _delete_post()
{
$data = $this->json_input();
$this->{$this->base_model}->batchDel($data);
$this->success();
}
//批量新建
function _batch_create_post($validate_config,$data_arr=[])
{
if(empty($data_arr)){
$data_arr = $this->json_input();
}
$this->load->library('form_validation');
foreach ($data_arr as $item) {
$this->form_validation->set_data($item);
$this->form_validation->set_rules($validate_config);
if ($this->form_validation->run() === FALSE)
{
$error_arr = $this->form_validation->error_array();
$this->error(reset($error_arr),$error_arr);
}
$ret = $this->{$this->base_model}->batchAdd($data_arr);
if(is_string($ret)){
$this->error($ret);
}
$this->success();
}
}
//批量更新单一属性
function batch_update_post()
{
$data_arr = $this->json_input();
//id必传,其他字段检查规则中有没有
if(empty($data_arr['id'])){
$this->error('请传入id');
}
$ids = [];
foreach ($data_arr['id'] as $id) {
$ids[] = (int)$id;
}
unset($data_arr['id']);
$this->{$this->base_model}->update($data_arr, 'id in ('.implode(',',$ids).')');
$this->success();
}
//批量更新插入
function batch_update_insert_post()
{
$data = $this->_arr_fill($this->_import_field_map(),$this->json_input());
$this->_batch_update_insert_post($this->_validate_rule(),$data);
$this->success();
}
//批量更新插入
function _batch_update_insert_post($validate_config,$data_arr=[])
{
if(empty($data_arr)){
$data_arr = $this->json_input();
}
$this->load->library('form_validation');
foreach ($data_arr as $item) {
$this->form_validation->set_data($item);
$this->form_validation->set_rules($validate_config);
if ($this->form_validation->run() === FALSE)
{
$error_arr = $this->form_validation->error_array();
$this->error(reset($error_arr),$error_arr);
}
$ret = $this->{$this->base_model}->batchUpdateInsert($data_arr);
$this->success();
}
}
//数组字段映射并补充不存在的字段
function _arr_fill($map,$input)
{
$data = [];
foreach ($input as $item) {
$tmp = [];
//中文改成英文
foreach ($item as $k=>$v) {
if(!isset($map[$k])){
continue;
}
$tmp[$map[$k]] = $v;
}
//补充不存在的字段
foreach ($map as $k=>$v) {
if(!isset($tmp[$v])){
$tmp[$v] = '';
}
}
$data[] = $tmp;
}
return $data;
}
}
+257
View File
@@ -0,0 +1,257 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//定义一些可复用的功能
class MY_Model extends CI_Model
{
protected $table = '';
protected $join = [];//定义以下属性[table,on,type]
protected $keyword_field = [];//作为关键词搜索的字段
protected $has_create_time = true;//是否有创建时间create_time
protected $has_update_time = true;//是否有更新时间update_time
protected $list_field = 'base.*';//默认列表筛选的字段
protected $unique_field = null;//不允许重复的字段
protected $where_field_map = [];//过滤条件字段重命名
protected $null_field = [];//特定字段的0值填充为null值
public function __construct()
{
$this->load->database();
}
function listing($filters = [], $offset, $segment, $select=null, $order_field='base.id',$order='DESC')
{
if(empty($select)){
$select = $this->list_field;
}
$this->db->select('SQL_CALC_FOUND_ROWS '.$select,false);
$this->db->from($this->table.' as base');
if(!empty($this->join)){
foreach ($this->join as $_join) {
$this->db->join($_join['table'], $_join['on'],$_join['type']);
}
}
if(!empty($order_field)){
$this->db->order_by($order_field,$order);
}
//包含筛选条件
if(!empty($filters)) foreach ($filters as $key=>$val) {
if($val === ''){
continue;
}
//容易冲突的键
if(in_array($key,['id','name','create_time'])){
$key = 'base.'.$key;
}
//字段别名
if(isset($this->where_field_map[$key])){
$key = $this->where_field_map[$key];
}
//某些字段的0值填充为null
if($val == '0' && in_array($key,$this->null_field)){
$this->db->where("$key is null");
continue;
}
//含有关键词
if(!empty($this->keyword_field)) {
if($key === 'title'){
//对于关键词,拼合所有筛选条件
$likeCriteria = [];
foreach ($this->keyword_field as $_field) {
$likeCriteria[] = $_field." LIKE '%".$val."%'";
}
$this->db->where('('.implode(' OR ',$likeCriteria).')');
continue;
}elseif(in_array($key,$this->keyword_field)){
$this->db->where($key." LIKE '%".$val."%'");
continue;
}
}
//对于数组
if(is_array($val)){
$this->db->where("$key BETWEEN {$val[0]} and {$val[1]}");
continue;
}
//含有比较符号
$op = substr($val,0,1);
if(in_array($op,['>','<'])){
$this->db->where($key.' '.$op,substr($val,1));
continue;
}
//普通值
$this->db->where($key,$val);
continue;
}
$this->db->limit($segment, $offset);
$query = $this->db->get();
$result['items'] = $query->result_array();
//echo $this->db->last_query(); die;
$query = $this->db->query('SELECT FOUND_ROWS() AS `Count`');
$result['total'] = (int)$query->row()->Count;
return $result;
}
public function get($id=false, $field='base.id', $is_list=false, $select=null)
{
if(empty($select)){
$select = $this->list_field;
}
$this->db->select($select);
$this->db->from($this->table.' as base');
if(!empty($this->join)){
foreach ($this->join as $_join) {
$this->db->join($_join['table'], $_join['on'],$_join['type']);
}
}
if($id !== false){
if(is_array($id)){
$this->db->where_in($field, $id);
}else{
$this->db->where($field, $id);
}
}
$query = $this->db->get();
if($is_list){
return $query->result_array();
}else{
return $query->row_array();
}
}
//更新单个或多个
public function update($data, $where, $one_row = true)
{
if($one_row){
if(!empty($this->unique_field)){
$ret = $this->get($data[$this->unique_field],$this->unique_field);
if($ret && $ret['id'] != $data['id']){
return -1;
}
}
}
if($this->has_update_time){
$data['update_time'] = empty($data['update_time'])?time():$data['update_time'];
}
$this->db->where($where);
$this->db->update($this->table,$data);
return $this->db->affected_rows();
}
public function add($data)
{
if($this->has_create_time){
$data['create_time'] = empty($data['create_time'])?time():$data['create_time'];
}
if(!empty($this->unique_field)){
$ret = $this->get($data[$this->unique_field],$this->unique_field);
if($ret){
return -1;
}
}
$this->db->insert($this->table,$data);
return $this->db->insert_id();
}
function batchAdd($data)
{
if(!empty($this->unique_field)){
$val = array_column($data,$this->unique_field);
$ret = $this->get($val,$this->unique_field);
if($ret){
return $ret[$this->unique_field].'已存在,不能重复添加';
}
}
if($this->has_create_time){
$time = time();
foreach ($data as &$item) {
$item['create_time'] = $time;
}
}
return $this->db->insert_batch($this->table, $data);
}
//与批量新建的区别是检测到重复字段则更新
function batchUpdateInsert($data)
{
//需要新增的条目
$left = [];
foreach ($data as $item) {
//有id则更新
if(!empty($item['id'])){
$this->update($item,'id = '.$item['id']);
continue;
}
if(!empty($this->unique_field)){
$val = array_column($item,$this->unique_field);
$this->get($val,$this->unique_field);
//存在则更新
$this->update($item,$this->unique_field.' = "'.$item[$this->unique_field].'"');
continue;
}
$left[] = $item;
}
if($this->has_create_time){
$time = time();
unset($item);
foreach ($left as &$item) {
$item['create_time'] = $time;
}
}
/*$temp1 = array_keys($left[0]);
* 检查字段情况
foreach ($left as $k=>$item) {
foreach ($temp1 as $key) {
if(!in_array($key, array_keys($item))){
die($k.$key);
}
}
}
die('');
*/
return $this->db->insert_batch($this->table, $left);
}
function batchDel($id, $field='id')
{
$this->db->where_in($field, $id);
return $this->db->delete($this->table);
}
//获取总数
function total($filters=[],$join=false)
{
$this->db->select('count(*) as count');
$this->db->from($this->table.' base');
//支持筛选条件
if($filters){
foreach ($filters as $filter) {
$this->db->where($filter);
}
}
//支持连表
if($join && !empty($this->join)){
foreach ($this->join as $_join) {
$this->db->join($_join['table'], $_join['on'],$_join['type']);
}
}
$query = $this->db->get();
$row = $query->row_array();
return $row['count'];
}
//按天统计
function sumByDay($start=0,$end=0)
{
$this->db->select('count(*) as count');
$this->db->from($this->table);
$this->db->where('create_time>=', $start);
$this->db->where('create_time<=', $end);
$this->db->group_by('DATE_FORMAT(from_unixtime(create_time),\'%Y-%m-%d\')');
$query = $this->db->get();
return $query->result_array();
}
}
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+49
View File
@@ -0,0 +1,49 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use \Firebase\JWT\JWT;
use chriskacerguis\RestServer\RestController;
class ManageAuth
{
private $CI;
function __construct()
{
$this->CI = &get_instance(); //获取CI对象
}
// var_dump(uri_string()); => api/v2/sys/user/login
//token及权限认证
public function auth()
{
$uri_no_prefix = str_replace(config_item('jwt_api_prefix'), '', uri_string()); // /sys/user/login 不带 api/v2 前缀
if (!in_array($uri_no_prefix, config_item('jwt_white_list'))) { // 不在白名单里需要校验 token
$headers = $this->CI->input->request_headers();
$Token = $headers['X-Token'];
try {
$decoded = JWT::decode($Token, config_item('jwt_key'), ['HS256']); //HS256方式,这里要和签发的时候对应
$userId = $decoded->user_id;
$retPerm = $this->CI->permission->HasPermit($userId, uri_string());
if ($retPerm['code'] != 50000) {
$this->CI->response($retPerm, RestController::HTTP_OK);
}
} catch (\Firebase\JWT\ExpiredException $e) { // access_token过期
$message = [
"code" => 50014,
"message" => $e->getMessage()
];
$this->CI->response($message, RestController::HTTP_UNAUTHORIZED);
} catch (Exception $e) { //其他错误
$message = [
"code" => 50015,
"message" => $e->getMessage()
];
$this->CI->response($message, RestController::HTTP_UNAUTHORIZED);
}
}
} // public function auth() end
} // class ManageAuth end
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+18
View File
@@ -0,0 +1,18 @@
<?php
/*
* English language
*/
$lang['text_rest_invalid_api_key'] = 'Invalid API key %s'; // %s is the REST API key
$lang['text_rest_invalid_credentials'] = 'Invalid credentials';
$lang['text_rest_ip_denied'] = 'IP denied';
$lang['text_rest_ip_unauthorized'] = 'IP unauthorized';
$lang['text_rest_unauthorized'] = 'Unauthorized';
$lang['text_rest_ajax_only'] = 'Only AJAX requests are allowed';
$lang['text_rest_api_key_unauthorized'] = 'This API key does not have access to the requested controller';
$lang['text_rest_api_key_permissions'] = 'This API key does not have enough permissions';
$lang['text_rest_api_key_time_limit'] = 'This API key has reached the time limit for this method';
$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';
$lang['text_rest_unknown_method'] = 'Unknown method';
$lang['text_rest_unsupported'] = 'Unsupported protocol';
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
@@ -0,0 +1,18 @@
<?php
/*
* Simple Chinese language
*/
$lang['text_rest_invalid_api_key'] = '无效的 API key %s'; // %s is the REST API key
$lang['text_rest_invalid_credentials'] = '无效的凭证';
$lang['text_rest_ip_denied'] = 'IP 地址被拒绝';
$lang['text_rest_ip_unauthorized'] = 'IP 地址未认证';
$lang['text_rest_unauthorized'] = '未认证';
$lang['text_rest_ajax_only'] = '只允许 AJAX 类型的请求';
$lang['text_rest_api_key_unauthorized'] = '此 API key无法存取指定的 controller';
$lang['text_rest_api_key_permissions'] = '此 API key没有足够的权限';
$lang['text_rest_api_key_time_limit'] = '此 API key已经超过有效期限';
$lang['text_rest_ip_address_time_limit'] = 'This IP Address has reached the time limit for this method';//todo translate
$lang['text_rest_unknown_method'] = '未知的方法';
$lang['text_rest_unsupported'] = '不支持的请求方法';
+98
View File
@@ -0,0 +1,98 @@
<?php
class Captcha
{
private $width;
private $height;
private $codeNum;
private $code;
private $im;
function __construct($width = 80, $height = 35, $codeNum = 4)
{
$this->width = $width;
$this->height = $height;
$this->codeNum = $codeNum;
}
function showImg()
{
//创建图片
$this->createImg();
//设置干扰元素
$this->setDisturb();
//设置验证码
$this->setCaptcha();
//输出图片
$this->outputImg();
}
function getCaptcha()
{
$this->createCode();
return $this->code;
}
private function createImg()
{
$this->im = imagecreatetruecolor($this->width, $this->height);
// $bgColor = imagecolorallocate($this->im, 0, 0, 0);
$bgColor = imagecolorallocate($this->im, 255, 255, 255);
imagefill($this->im, 0, 0, $bgColor);
}
private function setDisturb()
{
$area = ($this->width * $this->height) / 20;
$disturbNum = ($area > 250) ? 250 : $area;
//加入点干扰
for ($i = 0; $i < $disturbNum; $i++) {
$color = imagecolorallocate($this->im, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($this->im, rand(1, $this->width - 2), rand(1, $this->height - 2), $color);
}
//加入弧线
for ($i = 0; $i <= 5; $i++) {
$color = imagecolorallocate($this->im, rand(128, 255), rand(125, 255), rand(100, 255));
imagearc($this->im, rand(0, $this->width), rand(0, $this->height), rand(30, 300), rand(20, 200), 50, 30, $color);
}
}
private function createCode()
{
// $str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ";
$str = "0123456789";
for ($i = 0; $i < $this->codeNum; $i++) {
$this->code .= $str{rand(0, strlen($str) - 1)};
}
}
private function setCaptcha()
{
for ($i = 0; $i < $this->codeNum; $i++) {
// $color = imagecolorallocate($this->im, rand(50, 250), rand(100, 250), rand(128, 250));
$color = imagecolorallocate($this->im, rand(0, 50), rand(0, 100), rand(0, 128));
$size = rand(floor($this->height / 5), floor($this->height / 3));
$x = floor($this->width / $this->codeNum) * $i + 5;
$y = rand(0, $this->height - 20);
imagechar($this->im, $size, $x, $y, $this->code{$i}, $color);
}
}
private function outputImg()
{
if (imagetypes() & IMG_JPG) {
header('Content-type:image/jpeg');
imagejpeg($this->im);
} elseif (imagetypes() & IMG_GIF) {
header('Content-type: image/gif');
imagegif($this->im);
} elseif (imagetype() & IMG_PNG) {
header('Content-type: image/png');
imagepng($this->im);
} else {
die("Don't support image type!");
}
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* 压缩整个目录
*/
class MakeZip
{
/**
* description:主方法:生成压缩包
* @author: MY
* @param $dir_path 想要压缩的目录:如 './demo/'
* @param $zipName 压缩后的文件名:如 './folder/demo.zip'
* @return string
*/
function zip($dir_path, $zipName)
{
// Get real path for our folder
$rootPath = realpath($dir_path);
// Initialize archive object
$zip = new ZipArchive();
$zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
return true;
}
}
+340
View File
@@ -0,0 +1,340 @@
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Permission Class
*
* 基础权限类,及生成树类
*
*/
class Permission
{
private $idKey = 'id'; //主键的键名
private $fidKey = 'fid'; //父ID的键名
private $root = 0; //最顶层fid
private $pId = 0; //父fid
private $data = array(); //源数据
private $treeArray = array(); //属性数组
private $state = 'closed'; //默认关闭
/**
* 获得一个带children的树形数组
* @return multitype:
*/
public function getTreeArray($data, $idKey, $fidKey, $root, $closed = '0')
{
if ($idKey) $this->idKey = $idKey;
if ($fidKey) $this->fidKey = $fidKey;
if ($root) $this->root = $root;
if ($data) {
//var_dump($data);
$this->data = $data;
$this->getChildren($this->root, $closed);
}
//去掉键名
//var_dump($this->treeArray);
return array_values($this->treeArray);
}
/**
* @param int $root 父id值
* @return null or array
*/
private function getChildren($root, $closed)
{
$children = '';
foreach ($this->data as &$node) {
if ($root == $node[$this->fidKey]) {
$node['children'] = $this->getChildren($node[$this->idKey], $closed);
$children[] = $node;
}
//只要一级节点
if ($this->root == $node[$this->fidKey]) {
//$s=array('state'=>'close');
//array_push($node,'close');
if ($closed) {
$node['state'] = $this->state;
}
$this->treeArray[$node[$this->idKey]] = $node;
}
}
return $children;
}
/**
* 根据 $token 权限类型 获取该 token->userid->role 对应的所有权限
* @parms$type 根据$perm_type = 'menu'时,判断是否菜单带有功能控件
* return array
*/
function getPermission($token, $perm_type, $menuCtrl = true)
{
$CI = &get_instance();
$CI->load->model('Base_model');
$BasetblArr = $CI->Base_model->getBaseTable($perm_type);
if (empty($BasetblArr)) {
var_dump($this->uri->uri_string . '$this->Base_model->getBaseTable 获取基础表失败...');
return;
}
$tblname = $BasetblArr[0]['r_table'];
$PermArr = $CI->Base_model->getPerm($tblname, $token, $perm_type, $menuCtrl);
return $PermArr;
}
/**
* @parms, 根据$token获取拥有的菜单功能按钮控件权限 与vue前台perm.js 配合判断按钮隐藏与否
* return array
*/
function getMenuCtrlPerm($token)
{
$CI = &get_instance();
$CI->load->model('Base_model');
$PermArr = $CI->Base_model->getCtrlPerm($token);
// 返回样例
// array(2) {
// [0]=>
// array(1) {
// ["path"]=>
// string(13) "/sys/menu/add"
// }
// [1]=>
// array(1) {
// ["path"]=>
// string(14) "/sys/menu/edit"
// }
// }
return $PermArr;
}
/**
* 后端根据 $token,$uri 判断是否该用户是否过期及拥有的功能按钮控件操作权限
* 增/删/改/查 控制器引用
* @parms $token,$uri
* return Array
* return ['code' => 50008, 'message' => "非法的token"];
* return ['code' => 50014, 'message' => "Token 过期了"];
* return ['code' => 50016, 'message' => "无操作权限"];
* return ['code' => 50000, 'message' => "有操作权限"];
*/
function HasPermit($token, $uri)
{
$CI = &get_instance();
$CI->load->model('Base_model');
// 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了;
$tokenArr = $CI->Base_model->TokenExpired($token);
if ($tokenArr['code'] != 20000) {
return $tokenArr;
}
$PermArr = $CI->Base_model->getCtrlPerm($token);
// getCtrlPerm 返回样例
// array(2) {
// [0]=>
// array(1) {
// ["path"]=>
// string(13) "/sys/menu/add"
// }
// [1]=>
// array(1) {
// ["path"]=>
// string(14) "/sys/menu/edit"
// }
// }
if (empty($PermArr)) {
return ['code' => 50016, 'message' => "无操作权限 " . $uri, 'data' => $PermArr];
}
// var_dump($this->uri->uri_string); // string(19) "api/v2/sys/menu/add"
foreach ($PermArr as $k => $v) {
if (strpos($uri, $v['path'])) {
return ['code' => 50000, 'message' => "有操作权限 " . $uri, 'data' => $PermArr];
}
}
return ['code' => 50016, 'message' => "无操作权限 " . $uri, 'data' => $PermArr];
}
/**
* 将数据格式化成树形结构路由菜单
*/
function genVueRouter($data, $idKey, $fidKey, $pId)
{
$tree = array();
foreach ($data as $k => $v) {
// 找到父节点为$pId的节点,然后进行递归查找其子节点,
if ($v[$fidKey] == $pId) {
// 数据库取出为string类型,强制类型转换成整形,方便前端使用
isset($v['id']) ? $v['id'] = intval($v['id']) : '';
isset($v['pid']) ? $v['pid'] = intval($v['pid']) : '';
isset($v['type']) ? $v['type'] = intval($v['type']) : '';
isset($v['hidden']) ? $v['hidden'] = intval($v['hidden']) : '';
isset($v['listorder']) ? $v['listorder'] = intval($v['listorder']) : '';
// 构造 vue-admin 路由结构 meta
$v['meta'] = [
'title' => $v['title'],
'icon' => $v['icon']
];
unset($v['title']);
unset($v['icon']);
$v['children'] = $this->genVueRouter($data, $idKey, $fidKey, $v[$idKey]);
$tree[] = $v; // 循环数组添加元素 属于同一层级
}
}
// print_r($tree);
return $tree;
}
// 菜单管理 -> 菜单列表
function genVueMenuTree($data, $idKey, $fidKey, $pId)
{
$tree = array();
foreach ($data as $k => $v) {
// 找到父节点为$pId的节点,然后进行递归查找其子节点,
if ($v[$fidKey] == $pId) {
// 数据库取出为string类型,强制类型转换成整形,方便前端使用
isset($v['id']) ? $v['id'] = intval($v['id']) : '';
isset($v['pid']) ? $v['pid'] = intval($v['pid']) : '';
isset($v['type']) ? $v['type'] = intval($v['type']) : '';
isset($v['hidden']) ? $v['hidden'] = intval($v['hidden']) : '';
isset($v['listorder']) ? $v['listorder'] = intval($v['listorder']) : '';
$v['children'] = $this->genVueMenuTree($data, $idKey, $fidKey, $v[$idKey]);
// vue treeselect 组件子节点为空时会列出,将空的子节点删除 children key.
if (empty($v['children'])) {
unset($v['children']);
}
$tree[] = $v; // 循环数组添加元素 属于同一层级
// print_r($tree);
}
}
return $tree;
}
/**
* 指定格式两个二维数组比较差集
* @param $array1
* @param $array2
* @return array
*/
// $arr1 = [
// ['role_id'=>1,'perm_id'=>1],
// ['role_id'=>1,'perm_id'=>2]
// ];
function array_diff_assoc2($array1, $array2)
{
$ret = array();
foreach ($array1 as $k => $v) {
# var_dump($v);
$isExist = false;
foreach ($array2 as $k2 => $v2) {
if (empty(array_diff_assoc($v, $v2))) {
$isExist = true;
break;
}
}
if (!$isExist) array_push($ret, $v);
}
return $ret;
}
/**
* 将数据格式化成树形结构
*/
function genTree($data, $idKey, $fidKey, $pId)
{
// $tree = '';
$tree = array();
foreach ($data as $k => $v) {
// 找到父节点为$pId的节点,然后进行递归查找其子节点,
// 同时将子节点赋值至该节点的'children'元素,同时判断是否叶子节点
if ($v[$fidKey] == $pId) {
$v['children'] = $this->genTree($data, $idKey, $fidKey, $v[$idKey]);
// print_r($pId);
// $v['isLeaf']=$v['children']?0:1;
// $v['state']=$v['children']?'closed':'open';
$tree[] = $v; // 循环数组添加元素 属于同一层级
// print_r($v);
// print_r($tree);
}
}
return $tree;
}
/**
* 将数据格式化成树形结构 ___非递归方式,使用了数组指针,与前面json方式一样,array 必须以1开头___
* @author Xuefen.Tong
* @param array $items
* @return array
*/
function genTree9($items)
{
$tree = array(); //格式化好的树
foreach ($items as $item)
if (isset($items[$item['pid']]))
$items[$item['pid']]['son'][] = &$items[$item['id']];
else
$tree[] = &$items[$item['id']];
return $tree;
}
/**
* 获取全部机构
* TODO:根据当前USERID 获取用户最高级机构所有下属机构
*/
function getDept()
{
$CI = &get_instance();
$CI->load->model('Dept_model', 'Dept');
$array = $CI->Dept->getDeptids();
// var_dump($array);
$max = 10000;
$j = 0;
for ($i = 0; $i < count($array); $i++) {
// var_dump($array[$i]->DeptId);
$arr = $CI->Dept->getDeptFatherId($array[$i]->DeptId);
// var_dump($arr[0]->FatherLst);
// var_dump(explode(",",$arr[0]->FatherLst));
// var_dump(count(explode(",",$arr[0]->FatherLst)));
$fid_length = count(explode(",", $arr[0]->FatherLst));
if ($fid_length < $max) {
$max = $fid_length;
$j = $i; // 指针父机构最小长度
}
}
$fdeptid = $array[$j]->DeptId; // 最高机构ID
$data = $CI->Dept->getOptDept($fdeptid); //获取下属所有机构树
$ret = $CI->Dept->getFahterId($fdeptid); //获取最高机构直属父ID作为终止节点
$root = $ret[0]->FatherId; // treelib 需要终止节点
// $root 最顶层fid
// $b=$this->treelib->getTreeArray($data,'Id','FatherId',$root,1);
// $b=$this->treelib->getTreeArray($data,'Id','FatherId',$root,1);
// $b=str_replace(',"state":"closed","children":""',',"state":"open","children":""',json_encode($b));
// echo json_encode($b);
// $b=$this->genTree($data,'Id','FatherId',$root);
$b = $this->genTree($data, 'id', 'FatherId', $root);
echo json_encode($b);
}
}
+368
View File
@@ -0,0 +1,368 @@
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Permission Class
*
* 基础权限类,及生成树类
*
*/
class Permission
{
private $idKey = 'id'; //主键的键名
private $fidKey = 'fid'; //父ID的键名
private $root = 0; //最顶层fid
private $pId = 0; //父fid
private $data = array(); //源数据
private $treeArray = array(); //属性数组
private $state = 'closed'; //默认关闭
/**
* 获得一个带children的树形数组
* @return multitype:
*/
public function getTreeArray($data, $idKey, $fidKey, $root, $closed = '0')
{
if ($idKey) $this->idKey = $idKey;
if ($fidKey) $this->fidKey = $fidKey;
if ($root) $this->root = $root;
if ($data) {
//var_dump($data);
$this->data = $data;
$this->getChildren($this->root, $closed);
}
//去掉键名
//var_dump($this->treeArray);
return array_values($this->treeArray);
}
/**
* @param int $root 父id值
* @return null or array
*/
private function getChildren($root, $closed)
{
$children = '';
foreach ($this->data as &$node) {
if ($root == $node[$this->fidKey]) {
$node['children'] = $this->getChildren($node[$this->idKey], $closed);
$children[] = $node;
}
//只要一级节点
if ($this->root == $node[$this->fidKey]) {
//$s=array('state'=>'close');
//array_push($node,'close');
if ($closed) {
$node['state'] = $this->state;
}
$this->treeArray[$node[$this->idKey]] = $node;
}
}
return $children;
}
/**
* 根据 $token 权限类型 获取该 token->userid->role 对应的所有权限
* @parms$type 根据$perm_type = 'menu'时,判断是否菜单带有功能控件
* return array
*/
function getPermission($token, $perm_type, $menuCtrl = true)
{
$CI = &get_instance();
$CI->load->model('Base_model');
$BasetblArr = $CI->Base_model->getBaseTable($perm_type);
if (empty($BasetblArr)) {
var_dump($this->uri->uri_string . '$this->Base_model->getBaseTable 获取基础表失败...');
return;
}
$tblname = $BasetblArr[0]['r_table'];
$PermArr = $CI->Base_model->getPerm($tblname, $token, $perm_type, $menuCtrl);
return $PermArr;
}
/**
* @parms, 根据$token获取拥有的菜单功能按钮控件权限 与vue前台perm.js 配合判断按钮隐藏与否
* return array
*/
function getMenuCtrlPerm($token)
{
$CI = &get_instance();
$CI->load->model('Base_model');
$PermArr = $CI->Base_model->getCtrlPerm($token);
// 返回样例
// array(2) {
// [0]=>
// array(1) {
// ["path"]=>
// string(13) "/sys/menu/add"
// }
// [1]=>
// array(1) {
// ["path"]=>
// string(14) "/sys/menu/edit"
// }
// }
return $PermArr;
}
/**
* 后端根据 $token,$uri 判断是否该用户是否过期及拥有的功能按钮控件操作权限
* 增/删/改/查 控制器引用
* @parms $token,$uri
* return Array
* return ['code' => 50008, 'message' => "非法的token"];
* return ['code' => 50014, 'message' => "Token 过期了"];
* return ['code' => 50016, 'message' => "无操作权限"];
* return ['code' => 50000, 'message' => "有操作权限"];
*/
function HasPermit($token, $uri)
{
$CI = &get_instance();
$CI->load->model('Base_model');
// 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了;
$tokenArr = $CI->Base_model->TokenExpired($token);
if ($tokenArr['code'] != 20000) {
return $tokenArr;
}
$PermArr = $CI->Base_model->getCtrlPerm($token);
// getCtrlPerm 返回样例
// array(2) {
// [0]=>
// array(1) {
// ["path"]=>
// string(13) "/sys/menu/add"
// }
// [1]=>
// array(1) {
// ["path"]=>
// string(14) "/sys/menu/edit"
// }
// }
//暂不细分后台权限
return ['code' => 50000, 'message' => "有操作权限 " . $uri, 'data' => $PermArr];
if (empty($PermArr)) {
return ['code' => 50016, 'message' => "无操作权限 " . $uri, 'data' => $PermArr];
}
// var_dump($this->uri->uri_string); // string(19) "api/v2/sys/menu/add"
foreach ($PermArr as $k => $v) {
if (strpos($uri, $v['path'])) {
return ['code' => 50000, 'message' => "有操作权限 " . $uri, 'data' => $PermArr];
}
}
return ['code' => 50016, 'message' => "无操作权限 " . $uri, 'data' => $PermArr];
}
/**
* 将数据格式化成树形结构路由菜单
*/
function genVueRouter($data, $idKey, $fidKey, $pId)
{
$tree = array();
foreach ($data as $k => $v) {
// 找到父节点为$pId的节点,然后进行递归查找其子节点,
if ($v[$fidKey] == $pId) {
// 数据库取出为string类型,强制类型转换成整形,方便前端使用
isset($v['id']) ? $v['id'] = intval($v['id']) : '';
isset($v['pid']) ? $v['pid'] = intval($v['pid']) : '';
isset($v['type']) ? $v['type'] = intval($v['type']) : '';
isset($v['hidden']) ? $v['hidden'] = intval($v['hidden']) : '';
isset($v['listorder']) ? $v['listorder'] = intval($v['listorder']) : '';
// 构造 vue-admin 路由结构 meta
$v['meta'] = [
'title' => $v['title'],
'icon' => $v['icon']
];
unset($v['title']);
unset($v['icon']);
$v['children'] = $this->genVueRouter($data, $idKey, $fidKey, $v[$idKey]);
$tree[] = $v; // 循环数组添加元素 属于同一层级
}
}
// print_r($tree);
return $tree;
}
// 菜单管理 -> 菜单列表
function genVueMenuTree($data, $idKey, $fidKey, $pId)
{
$tree = array();
foreach ($data as $k => $v) {
// 找到父节点为$pId的节点,然后进行递归查找其子节点,
if ($v[$fidKey] == $pId) {
// 数据库取出为string类型,强制类型转换成整形,方便前端使用
isset($v['id']) ? $v['id'] = intval($v['id']) : '';
isset($v['pid']) ? $v['pid'] = intval($v['pid']) : '';
isset($v['type']) ? $v['type'] = intval($v['type']) : '';
isset($v['hidden']) ? $v['hidden'] = intval($v['hidden']) : '';
isset($v['listorder']) ? $v['listorder'] = intval($v['listorder']) : '';
$v['children'] = $this->genVueMenuTree($data, $idKey, $fidKey, $v[$idKey]);
// vue treeselect 组件子节点为空时会列出,将空的子节点删除 children key.
if (empty($v['children'])) {
unset($v['children']);
}
$tree[] = $v; // 循环数组添加元素 属于同一层级
// print_r($tree);
}
}
return $tree;
}
// 生成部门机构树
function genDeptTree($data, $idKey, $fidKey, $pId)
{
$tree = array();
foreach ($data as $k => $v) {
// 找到父节点为$pId的节点,然后进行递归查找其子节点,
if ($v[$fidKey] == $pId) {
// 数据库取出为string类型,强制类型转换成整形,方便前端使用
isset($v['id']) ? $v['id'] = intval($v['id']) : '';
isset($v['pid']) ? $v['pid'] = intval($v['pid']) : '';
isset($v['listorder']) ? $v['listorder'] = intval($v['listorder']) : '';
$v['children'] = $this->genDeptTree($data, $idKey, $fidKey, $v[$idKey]);
// vue treeselect 组件子节点为空时会列出,将空的子节点删除 children key.
if (empty($v['children'])) {
unset($v['children']);
}
$tree[] = $v; // 循环数组添加元素 属于同一层级
}
}
return $tree;
}
/**
* 指定格式两个二维数组比较差集
* @param $array1
* @param $array2
* @return array
*/
// $arr1 = [
// ['role_id'=>1,'perm_id'=>1],
// ['role_id'=>1,'perm_id'=>2]
// ];
function array_diff_assoc2($array1, $array2)
{
$ret = array();
foreach ($array1 as $k => $v) {
# var_dump($v);
$isExist = false;
foreach ($array2 as $k2 => $v2) {
if (empty(array_diff_assoc($v, $v2))) {
$isExist = true;
break;
}
}
if (!$isExist) array_push($ret, $v);
}
return $ret;
}
/**
* 将数据格式化成树形结构
*/
function genTree($data, $idKey, $fidKey, $pId)
{
// $tree = '';
$tree = array();
foreach ($data as $k => $v) {
// 找到父节点为$pId的节点,然后进行递归查找其子节点,
// 同时将子节点赋值至该节点的'children'元素,同时判断是否叶子节点
if ($v[$fidKey] == $pId) {
$v['children'] = $this->genTree($data, $idKey, $fidKey, $v[$idKey]);
// print_r($pId);
// $v['isLeaf']=$v['children']?0:1;
// $v['state']=$v['children']?'closed':'open';
$tree[] = $v; // 循环数组添加元素 属于同一层级
// print_r($v);
// print_r($tree);
}
}
return $tree;
}
/**
* 将数据格式化成树形结构 ___非递归方式,使用了数组指针,与前面json方式一样,array 索引必须以1开头___
* @author Xuefen.Tong
* @param array $items
* @return array
*/
function genTree9($items)
{
$tree = array(); //格式化好的树
foreach ($items as $item)
if (isset($items[$item['pid']]))
$items[$item['pid']]['son'][] = &$items[$item['id']];
else
$tree[] = &$items[$item['id']];
return $tree;
}
/**
* 获取全部机构
* TODO:根据当前USERID 获取用户最高级机构所有下属机构
*/
function getDept()
{
$CI = &get_instance();
$CI->load->model('Dept_model', 'Dept');
$array = $CI->Dept->getDeptids();
// var_dump($array);
$max = 10000;
$j = 0;
for ($i = 0; $i < count($array); $i++) {
// var_dump($array[$i]->DeptId);
$arr = $CI->Dept->getDeptFatherId($array[$i]->DeptId);
// var_dump($arr[0]->FatherLst);
// var_dump(explode(",",$arr[0]->FatherLst));
// var_dump(count(explode(",",$arr[0]->FatherLst)));
$fid_length = count(explode(",", $arr[0]->FatherLst));
if ($fid_length < $max) {
$max = $fid_length;
$j = $i; // 指针父机构最小长度
}
}
$fdeptid = $array[$j]->DeptId; // 最高机构ID
$data = $CI->Dept->getOptDept($fdeptid); //获取下属所有机构树
$ret = $CI->Dept->getFahterId($fdeptid); //获取最高机构直属父ID作为终止节点
$root = $ret[0]->FatherId; // treelib 需要终止节点
// $root 最顶层fid
// $b=$this->treelib->getTreeArray($data,'Id','FatherId',$root,1);
// $b=$this->treelib->getTreeArray($data,'Id','FatherId',$root,1);
// $b=str_replace(',"state":"closed","children":""',',"state":"open","children":""',json_encode($b));
// echo json_encode($b);
// $b=$this->genTree($data,'Id','FatherId',$root);
$b = $this->genTree($data, 'id', 'FatherId', $root);
echo json_encode($b);
}
}
+192
View File
@@ -0,0 +1,192 @@
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* 上传及图像处理
*/
class Uploads
{
const DIR = 'uploads';
const DIR_PET_IMG = 'pet_img';
const DIR_PER_CERT_IMG = 'pet_cert_img';
const DIR_PER_CERT_ZIP = 'pet_cert_zip';
public function get_upload_path(){
return FCPATH.self::DIR.DIRECTORY_SEPARATOR;
}
/**
* 上传宠物证书base64
*/
public function save_cert_img_base64($content,$device_id,$filename)
{
$device_id = strtoupper($device_id);
$upload_path = $this->get_upload_path();
$pet_img_path = Uploads::DIR_PER_CERT_IMG.DIRECTORY_SEPARATOR.$device_id.DIRECTORY_SEPARATOR;
$type = $this->base64_image_save(
$content,
$upload_path.$pet_img_path,
$filename
);
if(!$type){
return false;
}
//png转为jpg,降低文件大小
$img = imagecreatefrompng($upload_path.$pet_img_path.$filename.'.'.$type);
if($img){
imagejpeg($img, $upload_path.$pet_img_path.$filename.'.jpg',75);
imagedestroy($img);
unlink($upload_path.$pet_img_path.$filename.'.'.$type);
}
return $filename.'.jpg';
}
/**
* 上传宠物头像
*/
public function save_pet_img_base64($content,$device_id)
{
$device_id = strtoupper($device_id);
$upload_path = $this->get_upload_path();
$pet_img_path = Uploads::DIR_PET_IMG.DIRECTORY_SEPARATOR;
$type = $this->base64_image_save(
$content,
$upload_path.$pet_img_path,
$device_id.'_ori'
);
if(!$type){
return false;
}
$source = $pet_img_path.$device_id.'_ori.'.$type;
$target = $pet_img_path.$device_id.'_300.'.$type;
$ret = $this->image_center_crop($upload_path.$source, 300, 300, $upload_path.$target);
if(!$ret){
return $source;
}
return $target;
}
/**
* 上传图片
*/
public function upload_img($arr)
{
$list = array();
foreach ($arr as $k => $v) {
$name = $v['name'];
$type = strtolower(substr($name, strrpos($name, '.') + 1)); // 得到文件类型,并且都转化成小写
$allow_type = array(
'jpg',
'jpeg',
'gif',
'png',
'mp4',
); // 定义允许上传的类型
// 判断文件类型是否被允许上传
if (! in_array($type, $allow_type)) {
// 如果不被允许,则直接停止程序运行
return;
}
// 判断是否是通过HTTP POST上传的
if (! is_uploaded_file($v['tmp_name'])) {
// 如果不是通过HTTP POST上传的
return;
}
$upload_path = FCPATH.self::DIR.DIRECTORY_SEPARATOR."users_info_img/";
if (! file_exists($upload_path)) {
mkdir($upload_path);
}
$img_id = time() . rand(1, 100) . "." . $type;
$list[$k] ='users_info_img/'.$img_id;
if (move_uploaded_file($v['tmp_name'], $upload_path . $img_id)) {
} else {
return;
}
}
return $list[0];
}
/* base64格式编码转换为图片并保存对应文件夹 */
function base64_image_save($base64_image_content,$path,$name)
{
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
$type = $result[2] === 'jpeg'?'jpg':$result[2];
if (!file_exists($path)) {
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($path, 0755);
}
$new_file = $name . ".{$type}";
if (file_put_contents($path . $new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
return $type;
} else {
return false;
}
} else {
return false;
}
}
/**
* 居中裁剪图片
* @param string $source [原图路径]
* @param int $width [设置宽度]
* @param int $height [设置高度]
* @param string $target [目标路径]
* @return bool [裁剪结果]
*/
public function image_center_crop($source, $width, $height, $target)
{
if (!file_exists($source)) return false;
/* 根据类型载入图像 */
switch (exif_imagetype($source)) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($source);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($source);
break;
}
if (!isset($image)) return false;
/* 获取图像尺寸信息 */
$target_w = $width;
$target_h = $height;
$source_w = imagesx($image);
$source_h = imagesy($image);
/* 计算裁剪宽度和高度 */
$judge = (($source_w / $source_h) > ($target_w / $target_h));
$resize_w = $judge ? ($source_w * $target_h) / $source_h : $target_w;
$resize_h = !$judge ? ($source_h * $target_w) / $source_w : $target_h;
$start_x = $judge ? ($resize_w - $target_w) / 2 : 0;
$start_y = !$judge ? ($resize_h - $target_h) / 2 : 0;
/* 绘制居中缩放图像 */
$resize_img = imagecreatetruecolor($resize_w, $resize_h);
imagecopyresampled($resize_img, $image, 0, 0, 0, 0, $resize_w, $resize_h, $source_w, $source_h);
$target_img = imagecreatetruecolor($target_w, $target_h);
imagecopy($target_img, $resize_img, 0, 0, $start_x, $start_y, $resize_w, $resize_h);
/* 将图片保存至文件 */
if (!file_exists(dirname($target))) mkdir(dirname($target), 0777, true);
switch (exif_imagetype($source)) {
case IMAGETYPE_JPEG:
imagejpeg($target_img, $target);
break;
case IMAGETYPE_PNG:
imagepng($target_img, $target);
break;
case IMAGETYPE_GIF:
imagegif($target_img, $target);
break;
}
return boolval(file_exists($target));
}
}
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+258
View File
@@ -0,0 +1,258 @@
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Base_model extends CI_Model
{
/*
* 1. 通用数据库操作方法 增删改查
* 2. 权限/菜单模型部分
*/
function __construct()
{
parent::__construct();
$this->load->database();
}
/************************
* 数据库操作模型部分
***********************/
/**
* 获取值
* $table: 表名
* $select: 查找项, $select = '*' 或 $select = 'id,title'
* $where: 条件项 $where= 'id=1' 或 $where = 'id=1 and title="blah"'
* $order: $order = 'id desc'
* 返回值是数组
*/
function _get_key($table, $select = '', $where = '', $order = '')
{
if ($select) {
$this->db->select($select);
}
if ($where) {
$this->db->where($where);
}
if ($order) {
$this->db->order_by($order);
}
$query = $this->db->get($table);
return $query->result_array();
}
function _insert_key($table, $data)
{
$this->db->insert($table, $data);
// 如果$table没有配置自增主键,则insert_id返回值为0
return $this->db->insert_id();
}
// TODO: 更新错误判断 https://stackoverflow.com/questions/20030642/check-if-db-update-successful-with-codeigniter-when-potentially-no-rows-are-upd
function _update_key($table, $data, $where)
{
$this->db->trans_start();
$this->db->where($where);
$this->db->update($table, $data);
$this->db->trans_complete();
// return $this->db->affected_rows();
// was there any update or error?
if ($this->db->affected_rows() == '1') {
return TRUE;
} else {
// any trans error?
if ($this->db->trans_status() === FALSE) {
return FALSE;
}
return TRUE;
}
}
function _key_exists($table, $where)
{
$this->db->where($where);
$this->db->from($table);
return $this->db->count_all_results();
}
function _delete_key($table, $where)
{
$this->db->where($where);
$this->db->delete($table);
return $this->db->affected_rows();
}
function _total($table)
{
$sql = "select count(*) cnt from $table";
$query = $this->db->query($sql);
if (($query->row_array()) == null) {
return 0;
} else {
$result = $query->result_array();
return $result[0]->cnt;
}
}
function total($table, $field, $keyword)
{
$sql = "select count(*) numrows from $table where $field like '%$keyword%' ";
$query = $this->db->query($sql);
if (($query->row_array()) == null) {
return 0;
} else {
$result = $query->result_array();
return $result;
}
}
/************************
* 数据库操作模型部分结束
***********************/
/************************
* 权限模型部分
***********************/
/** 根据perm_type 获取关联的基础表名称
* @return array
*/
function getBaseTable($perm_type)
{
$sql = "select r_table from sys_perm_type where type = '" . $perm_type . "'";
$query = $this->db->query($sql);
return $query->result_array();
}
/**
* 根据token, perm_type 获取 perm_id,perm_type,r_id
* @return array
*/
function getPerm($basetable, $token, $perm_type, $menuCtrl)
{
$hasCtrl = $menuCtrl ? "" : " WHERE basetbl.type != 2";
$sql = "SELECT
DISTINCT t.id perm_id,
basetbl.*
FROM
(
SELECT
p.*
FROM
sys_user_token ut,
sys_user_role ur,
sys_role_perm rp,
sys_perm p,
sys_role r
WHERE
ut.token = '" . $token . "'
AND ur.user_id = ut.user_id
AND rp.role_id = ur.role_id
AND p.id = rp.perm_id
AND r.id = ur.role_id
AND r.status=1
AND p.perm_type = '" . $perm_type . "'
) t
LEFT JOIN " . $basetable . " basetbl ON t.r_id = basetbl.id" . $hasCtrl . " order by basetbl.listorder";
$query = $this->db->query($sql);
return $query->result_array();
}
function getCtrlPerm($token)
{
$sql = "SELECT
basetbl.path
FROM
(
SELECT
p.*
FROM
sys_user_token ut,
sys_user_role ur,
sys_role_perm rp,
sys_perm p,
sys_role r
WHERE
ut.token = '" . $token . "'
AND ur.user_id = ut.user_id
AND rp.role_id = ur.role_id
AND p.id = rp.perm_id
AND r.id = ur.role_id
AND r.status=1
AND p.perm_type = 'menu'
) t
LEFT JOIN sys_menu basetbl ON t.r_id = basetbl.id
WHERE basetbl.type = 2";
$query = $this->db->query($sql);
return $query->result_array();
}
/**
* 判断 token 是否过期
* // 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了;
*/
function TokenExpired($token)
{
$sql = "SELECT
*
FROM
`sys_user_token`
WHERE
token = '$token'";
$query = $this->db->query($sql);
$Arr = $query->result_array();
if (empty($Arr)) {
return ['code' => 50008, 'message' => "非法的token"];
}
$now = time();
if ($now > $Arr[0]['expire_time']) {
return ['code' => 50014, 'message' => "Token 过期了"];
}
// TODO: 当token合法时,自动续期?
$update_time = time();
$expire_time = $update_time + 2 * 60 * 60; // 2小时过期
$data = [
'expire_time' => $expire_time,
'last_update_time' => $update_time
];
$this->_update_key('sys_user_token', $data, ['token' => $token]);
return ['code' => 20000, 'message' => "Token 合法"];
}
/***********************
* 权限模型部分结束
***********************/
/************************
* 菜单模型部分
************************/
/**
* 菜单是否拥有子节点
*/
function hasChildMenu($id)
{
$sql = "SELECT getChildLst(" . $id . ") children";
$query = $this->db->query($sql);
// var_dump($query->result_array()[0]["children"]);
// string(14) "$,2,5,6,8,9,10"
$array = explode(",", $query->result_array()[0]["children"]);
if (count($array) > 2) {
return true;
} else {
return false;
}
}
/***********************
* 菜单模型部分结束
***********************/
}
+261
View File
@@ -0,0 +1,261 @@
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Base_model extends CI_Model
{
/*
* 1. 通用数据库操作方法 增删改查
* 2. 权限/菜单模型部分
*/
function __construct()
{
parent::__construct();
$this->load->database();
}
/************************
* 数据库操作模型部分
***********************/
/**
* 获取值
* $table: 表名
* $select: 查找项, $select = '*' 或 $select = 'id,title'
* $where: 条件项 $where= 'id=1' 或 $where = 'id=1 and title="blah"'
* $order: $order = 'id desc'
* 返回值是数组
*/
function _get_key($table, $select = '', $where = '', $order = '')
{
if ($select) {
$this->db->select($select);
}
if ($where) {
$this->db->where($where);
}
if ($order) {
$this->db->order_by($order);
}
$query = $this->db->get($table);
return $query->result_array();
}
function _insert_key($table, $data)
{
$this->db->insert($table, $data);
// 如果$table没有配置自增主键,则insert_id返回值为0
return $this->db->insert_id();
}
// TODO: 更新错误判断 https://stackoverflow.com/questions/20030642/check-if-db-update-successful-with-codeigniter-when-potentially-no-rows-are-upd
function _update_key($table, $data, $where)
{
$this->db->trans_start();
$this->db->where($where);
$this->db->update($table, $data);
$this->db->trans_complete();
// return $this->db->affected_rows();
// was there any update or error?
if ($this->db->affected_rows() == '1') {
return TRUE;
} else {
// any trans error?
if ($this->db->trans_status() === FALSE) {
return FALSE;
}
return TRUE;
}
}
function _key_exists($table, $where)
{
$this->db->where($where);
$this->db->from($table);
return $this->db->count_all_results();
}
function _delete_key($table, $where)
{
$this->db->where($where);
$this->db->delete($table);
return $this->db->affected_rows();
}
function _total($table)
{
$sql = "select count(*) cnt from $table";
$query = $this->db->query($sql);
if (($query->row_array()) == null) {
return 0;
} else {
$result = $query->result_array();
return $result[0]->cnt;
}
}
function total($table, $field, $keyword)
{
$sql = "select count(*) numrows from $table where $field like '%$keyword%' ";
$query = $this->db->query($sql);
if (($query->row_array()) == null) {
return 0;
} else {
$result = $query->result_array();
return $result;
}
}
/************************
* 数据库操作模型部分结束
***********************/
/************************
* 权限模型部分
***********************/
/** 根据perm_type 获取关联的基础表名称
* @return array
*/
function getBaseTable($perm_type)
{
$sql = "select r_table from sys_perm_type where type = '" . $perm_type . "'";
$query = $this->db->query($sql);
return $query->result_array();
}
/**
* 根据token, perm_type 获取 perm_id,perm_type,r_id
* @return array
*/
function getPerm($basetable, $token, $perm_type, $menuCtrl)
{
$hasCtrl = $menuCtrl ? "" : " WHERE basetbl.type != 2";
$sql = "SELECT
DISTINCT t.id perm_id,
basetbl.*
FROM
(
SELECT
p.*
FROM
sys_user_token ut,
sys_user_role ur,
sys_role_perm rp,
sys_perm p,
sys_role r
WHERE
ut.token = '" . $token . "'
AND ur.role_id = ut.role_id
AND rp.role_id = ur.role_id
AND p.id = rp.perm_id
AND r.id = ur.role_id
AND r.status=1
AND p.perm_type = '" . $perm_type . "'
) t
LEFT JOIN " . $basetable . " basetbl ON t.r_id = basetbl.id" . $hasCtrl . " order by basetbl.listorder";
$query = $this->db->query($sql);
return $query->result_array();
}
function getCtrlPerm($token)
{
$sql = "SELECT
basetbl.path
FROM
(
SELECT
DISTINCT p.*
FROM
sys_user_token ut,
sys_user_role ur,
sys_role_perm rp,
sys_perm p,
sys_role r
WHERE
ut.token = '" . $token . "'
AND ur.role_id = ut.role_id
AND rp.role_id = ur.role_id
AND p.id = rp.perm_id
AND r.id = ur.role_id
AND r.status=1
AND p.perm_type = 'menu'
) t
LEFT JOIN sys_menu basetbl ON t.r_id = basetbl.id
WHERE basetbl.type = 2";
$query = $this->db->query($sql);
return $query->result_array();
}
/**
* 判断 token 是否过期
* // 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了;
*/
function TokenExpired($token)
{
$sql = "SELECT
*
FROM
`sys_user_token`
WHERE
token = '$token'";
$query = $this->db->query($sql);
$Arr = $query->result_array();
if (empty($Arr)) {
return ['code' => 50008, 'message' => "非法的token"];
}
$now = time();
if ($now > $Arr[0]['expire_time']) {
return ['code' => 50014, 'message' => "Token 过期了"];
}
// TODO: 当token合法时,到期前30分钟内如果有操作,则自动续期,可减少插入次数?
if (($Arr[0]['expire_time'] - $now) < 0.5 * 60 * 60) {
$expire_time = $now + 2 * 60 * 60; // 2小时过期
$data = [
'expire_time' => $expire_time,
'last_update_time' => $now
];
$this->_update_key('sys_user_token', $data, ['token' => $token]);
}
return ['code' => 20000, 'message' => "Token 合法"];
}
/***********************
* 权限模型部分结束
***********************/
/************************
* 菜单模型部分
************************/
/**
* 菜单是否拥有子节点
*/
function hasChildMenu($id)
{
$sql = "SELECT getChildLst(" . $id . ") children";
$query = $this->db->query($sql);
// var_dump($query->result_array()[0]["children"]);
// string(14) "$,2,5,6,8,9,10"
$array = explode(",", $query->result_array()[0]["children"]);
if (count($array) > 2) {
return true;
} else {
return false;
}
}
/***********************
* 菜单模型部分结束
***********************/
}
+23
View File
@@ -0,0 +1,23 @@
<?php
class Breeding_plan_model extends MY_Model
{
protected $table = 'breeding_plan';
protected $join = [];
protected $keyword_field = ['user_id'];
protected $list_field = 'base.*';
protected $where_field_map = [];
protected $null_field = ['s.id'];
protected $unique_field = 'id';
//获取用户的计划总数
public function getUserTotal($user_id)
{
$this->db->select('count(*) as count');
$this->db->from($this->table);
$this->db->where('user_id', $user_id);
$list = $this->db->get()->row_array();
return $list['count'];
}
}
+550
View File
@@ -0,0 +1,550 @@
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* 猫单基因繁育版疾病
*/
class Cat_disease_desc_model
{
protected
$list = [
'原发性青光眼'=>[
'检测项目'=>'原发性青光眼',
'检测手段'=>'Sanger 测序',
'基因型'=>'CTCC/CTCCCTCC',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会患原发性青光眼,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。患病严重',
]
],
'先天性肌无力'=>[
'检测项目'=>'先天性肌无力',
'检测手段'=>'Sanger 测序',
'基因型'=>'C/T',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会患先天性肌无力,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。患病严重',
]
],
'糖原贮积病IV型'=>[
'检测项目'=>'糖原贮积病IV型',
'检测手段'=>'Sanger 测序',
'基因型'=>'无6.2Kb缺失和334bp插入/ 6.2Kb缺失和334bp插入',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现糖原贮积病症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。患病严重',
]
],
'低钾血症'=>[
'检测项目'=>'低钾血症',
'检测手段'=>'Sanger 测序',
'基因型'=>'C/ T',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会患低钾血症,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。患病严重',
]
],
'视网膜萎缩症'=>[
'检测项目'=>'视网膜萎缩症',
'检测手段'=>'Sanger 测序',
'基因型'=>'A/C',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会患视网膜萎缩症,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。视网膜萎缩严重',
]
],
'丙酮酸激酶缺乏症'=>[
'检测项目'=>'丙酮酸激酶缺乏症',
'检测手段'=>'Sanger 测序',
'基因型'=>'G/A',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现丙酮酸激酶缺乏症症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。丙酮酸激酶缺乏症症状严重',
]
],
'肥厚性心肌病'=>[
'检测项目'=>'肥厚性心肌病',
'检测手段'=>'Sanger 测序',
'基因型'=>'
C/Gp.A31P
G/Ap.R820W',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。可能会出现一定程度的肥厚性心肌病的症状,会传递给一半的后代',
'F/F'=>'携带两份突变基因。心肌肥厚症状严重',
]
],
'GM1神经节苷脂沉积症'=>[
'检测项目'=>'GM1神经节苷脂沉积症',
'检测手段'=>'Sanger 测序',
'基因型'=>'C/G',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现GM1神经节苷脂累积病的症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。GM1神经节苷脂累积病症状严重',
]
],
'多囊肾病'=>[
'检测项目'=>'多囊肾病',
'检测手段'=>'Sanger 测序',
'基因型'=>'C/A',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。患多囊肾病,会传递给一半的后代',
'F/F'=>'携带两份突变基因。多囊肾病症状严重',
]
],
'折耳和软骨发育不良'=>[
'检测项目'=>'折耳和软骨发育不良',
'检测手段'=>'Sanger 测序',
'基因型'=>'G/T',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>': 立耳,不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>': 折耳,携带一份突变基因。会传递给一半的后代',
'F/F'=>': 折耳,携带两份突变基因。可能带有严重软骨发育不良症',
]
],
'脊髓肌肉萎缩'=>[
'检测项目'=>'脊髓肌肉萎缩',
'检测手段'=>'Sanger 测序',
'基因型'=>'无140kb缺失/ 140kb缺失',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现脊髓肌肉萎缩症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。脊髓肌肉萎缩严重',
]
],
'GM2神经节苷脂沉积症'=>[
'检测项目'=>'GM2神经节苷脂沉积症',
'检测手段'=>'Sanger 测序',
'基因型'=>'TAATGTAGGTTCTCA / -intron11exon1215bp_del
TACTGGATATTGTGACTATGAATAC/inrc.1467_1491inv
GACC/-del GACC',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现GM2神经节苷脂沉积症症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。GM2神经节苷脂沉积症症状严重',
]
],
'急性间歇性卟啉症'=>[
'检测项目'=>'急性间歇性卟啉症',
'检测手段'=>'Sanger 测序',
'基因型'=>'ACAG / -c.107_110delACAG
G/Ac.826-1G>A
-/-c.189dupT
GAG/-c.844delGAG',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。患有急性间歇性卟啉症,会传递给一半的后代',
'F/F'=>'携带两份突变基因。急性间歇性卟啉症症状严重',
]
],
'凝血因子XII缺乏症'=>[
'检测项目'=>'凝血因子XII缺乏症',
'检测手段'=>'Sanger 测序',
'基因型'=>' G / C',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现凝血因子XII缺乏症症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。凝血因子XII缺乏症症状严重',
]
],
'先天性红细胞生成性卟啉症'=>[
'检测项目'=>'先天性红细胞生成性卟啉症',
'检测手段'=>'Sanger 测序',
'基因型'=>'
G / Ac.140C>T
C/Tc. 331G>A',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现先天性红细胞生成性卟啉症症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。先天性红细胞生成性卟啉症症状严重',
]
],
'自身免疫性淋巴细胞增生综合症'=>[
'检测项目'=>'自身免疫性淋巴细胞增生综合症',
'检测手段'=>'Sanger 测序',
'基因型'=>'-/Ac.413_414insA',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会患自身免疫性淋巴细胞增生综合症,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。自身免疫性淋巴细胞增生综合症症状严重',
]
],
'头部缺陷'=>[
'检测项目'=>'头部缺陷',
'检测手段'=>'Sanger 测序',
'基因型'=>'CTCTCAGGACTG/-',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。出现一定程度的头部缺陷症状,会传递给一半的后代',
'F/F'=>'携带两份突变基因。头部缺陷症状严重',
]
],
'高乳糜微粒血症'=>[
'检测项目'=>'高乳糜微粒血症',
'检测手段'=>'Sanger 测序',
'基因型'=>'C/T',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现乳糜微粒血症症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。高乳糜微粒血症症状严重',
]
],
'先天性肾上腺增生'=>[
'检测项目'=>'先天性肾上腺增生',
'检测手段'=>'Sanger 测序',
'基因型'=>'G/A',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现先天性肾上腺增生,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。先天性肾上腺增生严重',
]
],
'预期寿命较短的先天性少毛症'=>[
'检测项目'=>'预期寿命较短的先天性少毛症',
'检测手段'=>'Sanger 测序',
'基因型'=>'ACAG/-',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现预期寿命较短的先天性少毛症症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。预期寿命较短的先天性少毛症症状严重',
]
],
'胱氨酸尿症'=>[
'检测项目'=>'胱氨酸尿症',
'检测手段'=>'Sanger 测序',
'基因型'=>'
C/Tc.1342C>T
A/Gc.1846A>G
C/Tc.1175C>T
G/Ac.706G>A
T/Ac.881T>A',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。患胱氨酸尿症,会传递给一半的后代',
'F/F'=>'携带两份突变基因。胱氨酸尿症症状严重',
]
],
'二氢嘧啶酶缺陷症'=>[
'检测项目'=>'二氢嘧啶酶缺陷症',
'检测手段'=>'Sanger 测序',
'基因型'=>'C/T',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现二氢嘧啶酶缺陷症症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。二氢嘧啶酶缺陷症症状严重',
]
],
'乙型血友病'=>[
'检测项目'=>'乙型血友病',
'检测手段'=>'Sanger 测序',
'基因型'=>'
C/Tc.1014C>T
G/Ac.247G>A',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。可能出现乙型血友病症状,会传递给一半的后代',
'F/F'=>'携带两份突变基因。乙型血友病症状严重',
]
],
'高草酸尿症'=>[
'检测项目'=>'高草酸尿症',
'检测手段'=>'Sanger 测序',
'基因型'=>'G/A',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现高草酸尿症症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。高草酸尿症症状严重',
]
],
'黏多糖贮积症I型'=>[
'检测项目'=>'黏多糖贮积症I型',
'检测手段'=>'Sanger 测序',
'基因型'=>'TCG/-',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现黏多糖贮积症症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。黏多糖贮积症症状严重',
]
],
'黏多糖贮积症VI型'=>[
'检测项目'=>'黏多糖贮积症VI型',
'检测手段'=>'Sanger 测序',
'基因型'=>'T/C',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现黏多糖贮积症症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。黏多糖贮积症症状严重',
]
],
'黏多糖贮积症VII型'=>[
'检测项目'=>'黏多糖贮积症VII型',
'检测手段'=>'Sanger 测序',
'基因型'=>'G/Ac.1051G>A
C/Tc.C1424T
T/Gc.1421T>G',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现黏多糖贮积症症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。黏多糖贮积症症状严重',
]
],
'先天性肌强直'=>[
'检测项目'=>'先天性肌强直',
'检测手段'=>'Sanger 测序',
'基因型'=>'G/T',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。有可能出现先天性肌强直症状,会传递给一半的后代',
'F/F'=>'携带两份突变基因。先天性肌强直症状严重',
]
],
'C1型尼曼匹克氏病'=>[
'检测项目'=>'C1型尼曼匹克氏病',
'检测手段'=>'Sanger 测序',
'基因型'=>'C/G',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现尼曼-匹克式 C1病症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。尼曼-匹克式 C1病症状严重',
]
],
'C2型尼曼匹克氏病'=>[
'检测项目'=>'C2型尼曼匹克氏病',
'检测手段'=>'Sanger 测序',
'基因型'=>'C/T',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现尼曼-匹克式C2病症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。尼曼-匹克式C2病症状严重',
]
],
'维生素D依赖性佝偻病'=>[
'检测项目'=>'维生素D依赖性佝偻病',
'检测手段'=>'Sanger 测序',
'基因型'=>'C/A',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现维生素D依赖性佝偻病症状,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。维生素D依赖性佝偻病症状严重',
]
],
'渐进性视网膜萎缩'=>[
'检测项目'=>'渐进性视网膜萎缩',
'检测手段'=>'Sanger 测序',
'基因型'=>'AG/-',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会出现渐进性视网膜萎缩,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。渐进性视网膜萎缩严重',
]
],
'白细胞粘附缺陷症Ⅰ型'=>[
'检测项目'=>'白细胞粘附缺陷症Ⅰ型',
'检测手段'=>'Sanger 测序',
'基因型'=>'GCCCTCTGGTCCGGTGAGTTCCGC/-',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。不会患白细胞黏附缺陷症Ⅰ型,但会传递给一半的后代',
'F/F'=>'携带两份突变基因。白细胞黏附缺陷症症状严重',
]
],
'炎性线性疣状表皮痣'=>[
'检测项目'=>'炎性线性疣状表皮痣',
'检测手段'=>'Sanger 测序',
'基因型'=>'A/G',
'检测结果'=>[
'N/N'=>'无目标突变导致的遗传患病风险',
'N/F'=>'杂合突变',
'F/F'=>'纯合突变',
],
'结果说明'=>[
'N/N'=>'不携带突变基因。不会患病,也不会传递给下一代',
'N/F'=>'携带一份突变基因。会炎性线性疣状表皮痣,也会传递给一半的后代',
'F/F'=>'携带两份突变基因。炎性线性疣状表皮痣症状严重',
]
]
];
function breeding_single_detail($name)
{
if(!isset($this->list[$name])){
return [];
}
return $this->list[$name];
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* User_model class.
*
* @extends CI_Model
*/
class Customer_model extends MY_Model
{
CONST SESSION_KEY = 'user';
CONST SESSION_KEY_WX_OPEN_ID = 'wx_open_id';
protected $table = 'user';
protected $join = [];
protected $keyword_field = ['nickname'];
//微信用户处理
public function weixin_users($data)
{
try {
$data = array(
'openid' => $data['openid'],
'unionid' => $data['unionid'],
'nickname' => $data['nickname'],
'sex' => $data['sex'],
'language' => $data['language'],
'city' => $data['city'],
'province' => $data['province'],
'country' => $data['country'],
'headimgurl' => $data['headimgurl'],
'is_server' => isset($data['is_server'])?$data['is_server']:0,
'update_time' => time()
);
$row = $this->get($data['unionid'], 'unionid');
if ($row) {
// 更新操作
$data['update_time'] = time();
$this->db->where('id', $row['id']);
$this->db->update('user', $data);
return $row['id'];
} else {
//新增操作
$data['create_time'] = $data['update_time'] = time();
$this->db->insert('user', $data);
return $this->db->insert_id();
}
} catch (Exception $ex) {
return FALSE;
}
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Dept_model extends CI_Model
{
/**
* 机构模型部分
*/
function __construct()
{
parent::__construct();
$this->load->database();
}
/**
* 获取所有机构列表
*/
function getDeptList()
{
$sql = "SELECT
d.id,
d.pid,
d.name,
d.aliasname,
d.listorder,
d.status
FROM
sys_dept d
ORDER BY
d.listorder";
$query = $this->db->query($sql);
return $query->result_array();
}
/**
* @param $Id
* @return bool
* 含有子节点返回真
*/
function hasChildDept($Id){
$sql ="SELECT * FROM `sys_dept` where pid=" . $Id;
$query = $this->db->query($sql);
if(empty($query->result_array())) {
return FALSE;
} else {
return TRUE;
}
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* User_model class.
*
* @extends CI_Model
*/
class Disease_model extends MY_Model {
protected $table = 'disease';
protected $keyword_field = ['base.name'];
}
+8
View File
@@ -0,0 +1,8 @@
<?php
class Package_model extends MY_Model
{
protected $table = 'package';
protected $unique_field = 'name';
protected $keyword_field = ['base.name'];
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More