Passed
Pull Request — 5.1 (#1327)
by
unknown
08:41 queued 03:50
created

transfer_slash()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
// +----------------------------------------------------------------------
3
// | shuguo constant
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2018~2050 上海数果科技有限公司 All rights reserved.
6
// +----------------------------------------------------------------------
7
// +----------------------------------------------------------------------
8
// | Website: http://chinashuguo.com
9
// +----------------------------------------------------------------------
10
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
11
// +----------------------------------------------------------------------
12
// | Author: opensmarty <[email protected]>
13
// +----------------------------------------------------------------------
14
15
// +----------------------------------------------------------------------
16
// | 定义系统常量
17
// +----------------------------------------------------------------------
18
19
//记录开始运行时间
20
$GLOBALS['_beginTime'] = microtime(true);
21
22
// 记录内存初始使用
23
define('MEMORY_LIMIT_ON', function_exists('memory_get_usage'));
24
25
// 开启或关闭调试模式
26
sgdefine('SITE_DEBUG', false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $value of sgdefine(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

26
sgdefine('SITE_DEBUG', /** @scrutinizer ignore-type */ false);
Loading history...
27
28
// 设置全局变量sg
29
$sg['_debug']  = false;  // 调试模式
30
$sg['_define'] = [];    // 全局常量
31
$sg['_config'] = [];    // 全局配置
32
$sg['_env']    = [];    // 环境配置
33
$sg['_access'] = [];    // 访问配置
34
$sg['_router'] = [];    // 路由配置
35
36
// 初始化环境变量
37
sgenv();
38
39
if (isset($sg['_env']['app']['debug'])) {
40
    sgdefine('SITE_DEBUG', $sg['_env']['app']['debug']);
41
    $sg['_debug'] = $sg['_env']['app']['debug'];
42
}
43
44
//Think框架常量的基本配置
45
sgdefine('THINK_VERSION', '5.1.18');
46
sgdefine('THINK_START_TIME', microtime(true));
47
sgdefine('THINK_START_MEM', memory_get_usage());
48
sgdefine('EXT', '.php');
49
sgdefine('DS', transfer_slash(DIRECTORY_SEPARATOR));
50
51
// 环境常量
52
sgdefine('IS_CLI', PHP_SAPI == 'cli' ? true : false);
53
sgdefine('IS_WIN', strpos(PHP_OS, 'WIN') !== false);
54
sgdefine('IS_HTTPS', 0);
55
sgdefine('API_VERSION', 'v1');
56
sgdefine('_PHP_FILE_', getScriptName());
57
sgdefine('__ROOT__', getRootPath());
58
59
//基本常量定义
60
sgdefine('GROUP_NAME', 'shuguo');
61
sgdefine('GROUP_CORE_MODE', 'core');
62
sgdefine('SITE_NAME', 'sgs-api');
63
sgdefine('SITE_PATH', dirname($_SERVER['SCRIPT_FILENAME']) . DS);
0 ignored issues
show
Bug introduced by
The constant DS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
64
sgdefine('SITE_DOMAIN', getSiteHost());
65
sgdefine('SITE_URL', (IS_HTTPS ? 'https:' : 'http:') . '//' . SITE_DOMAIN . __ROOT__);
0 ignored issues
show
Bug introduced by
The constant SITE_DOMAIN was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant IS_HTTPS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant __ROOT__ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
66
67
// 新系统需要的一些配置
68
sgdefine('SG_ROOT', SITE_PATH);   // SG根
0 ignored issues
show
Bug introduced by
The constant SITE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
69
sgdefine('SG_APPLICATION', SG_ROOT . 'application'); // 应用存在的目录
0 ignored issues
show
Bug introduced by
The constant SG_ROOT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
70
sgdefine('SG_CONFIGURE', SG_ROOT . 'config'); // 配置文件存在的目录
71
sgdefine('SG_STORAGE', DS . 'storage');            // 储存目录,需要可以公开访问,相对于域名根
72
73
sgdefine('ROOT_PATH', SITE_PATH);
74
sgdefine('ROOT_FILE', basename(_PHP_FILE_));
0 ignored issues
show
Bug introduced by
The constant _PHP_FILE_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
75
76
sgdefine('THINK_PATH', ROOT_PATH . 'thinkphp' . DS);
0 ignored issues
show
Bug introduced by
The constant ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
77
sgdefine('LIB_PATH', THINK_PATH . 'library' . DS);
0 ignored issues
show
Bug introduced by
The constant THINK_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
78
sgdefine('CORE_PATH', LIB_PATH . 'think' . DS);
0 ignored issues
show
Bug introduced by
The constant LIB_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
79
sgdefine('TRAIT_PATH', LIB_PATH . 'traits' . DS);
80
sgdefine('ROUTE_PATH', ROOT_PATH . 'route' . DS);
81
sgdefine('EXTEND_PATH', ROOT_PATH . 'extend' . DS);
82
sgdefine('RUNTIME_PATH', ROOT_PATH . 'runtime' . DS);
83
sgdefine('LOG_PATH', RUNTIME_PATH . 'log' . DS);
0 ignored issues
show
Bug introduced by
The constant RUNTIME_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
84
sgdefine('CACHE_PATH', RUNTIME_PATH . 'cache' . DS);
85
sgdefine('SESSION_PATH', RUNTIME_PATH . 'session' . DS);
86
sgdefine('TEMP_PATH', RUNTIME_PATH . 'temp' . DS);
87
sgdefine('CONF_PATH', ROOT_PATH . 'config' . DS); // 配置文件目录
88
sgdefine('VENDOR_PATH', ROOT_PATH . 'vendor' . DS);
89
90
sgdefine('GROUP_PATH', VENDOR_PATH . GROUP_NAME . DS);
0 ignored issues
show
Bug introduced by
The constant GROUP_NAME was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant VENDOR_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
91
sgdefine('GROUP_URL', SITE_URL . DS . 'vendor' . DS . GROUP_NAME);
0 ignored issues
show
Bug introduced by
The constant SITE_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
92
sgdefine('GROUP_CORE_PATH', GROUP_PATH . GROUP_CORE_MODE . DS . 'src' . DS);
0 ignored issues
show
Bug introduced by
The constant GROUP_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant GROUP_CORE_MODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
93
94
sgdefine('CONF_EXT', EXT); // 配置文件后缀
0 ignored issues
show
Bug introduced by
The constant EXT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
95
sgdefine('ENV_PREFIX', 'PHP_'); // 环境变量的配置前缀
96
97
sgdefine('APPS_PATH', ROOT_PATH . 'application' . DS);
98
sgdefine('APPS_URL', SITE_URL . DS . 'application');    # 应用内部图标 等元素
99
100
sgdefine('ADDON_PATH', ROOT_PATH . 'addons' . DS);
101
sgdefine('ADDON_URL', SITE_URL . DS . 'addons');
102
103
sgdefine('DATA_PATH', ROOT_PATH . 'data' . DS);
104
sgdefine('DATA_URL', SITE_URL . DS . 'data');
105
106
sgdefine('UPLOAD_PATH', DATA_PATH . 'uploads' . DS);
0 ignored issues
show
Bug introduced by
The constant DATA_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
107
sgdefine('UPLOAD_URL', DATA_URL . DS . 'uploads');
0 ignored issues
show
Bug introduced by
The constant DATA_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
108
109
// 公共资源目录常量
110
sgdefine('PUBLIC_PATH', ROOT_PATH . 'public' . DS);
111
sgdefine('PUBLIC_URL', SITE_URL . DS . 'public');
112
113
// 前端资源目录常量
114
sgdefine('STATIC_PATH', PUBLIC_PATH . 'static' . DS);
0 ignored issues
show
Bug introduced by
The constant PUBLIC_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
115
sgdefine('STATIC_URL', PUBLIC_URL . DS . 'static');
0 ignored issues
show
Bug introduced by
The constant PUBLIC_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
116
117
sgdefine('NOW_TIME', $_SERVER ['REQUEST_TIME']);
118
sgdefine('REQUEST_METHOD', $_SERVER ['REQUEST_METHOD']);
119
sgdefine('IS_GET', REQUEST_METHOD == 'GET' ? true : false);
0 ignored issues
show
Bug introduced by
The constant REQUEST_METHOD was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
120
sgdefine('IS_POST', REQUEST_METHOD == 'POST' ? true : false);
121
122
// 自定义核心方法
123
/**
124
 * 判断是否为调试模式
125
 * @return bool
126
 */
127
function isDebug()
128
{
129
    // TODO
130
}
131
132
/**
133
 * @titile定义常量,判断是否未定义.
134
 * @param  string $name 常量名
135
 * @param  string $value 常量值
136
 * @return string $str 返回常量的值
137
 */
138
function sgdefine($name, $value)
139
{
140
    global $sg;
141
    // 定义未定义的常量
142
    if (!defined($name)) {
143
        // 定义新常量
144
        define($name, $value);
145
    } else {
146
        // 返回已定义的值
147
        $value = constant($name);
148
    }
149
    // 缓存已定义常量列表
150
    $sg['_define'][$name] = $value;
151
152
    return $value;
153
}
154
155
/**
156
 * @title 转义反斜杠为正斜杠
157
 * @param $slash
158
 * @return mixed
159
 */
160
function transfer_slash($slash)
161
{
162
    return str_replace('\\', '/', $slash);
163
}
164
165
/**
166
 * 获取当前脚本
167
 * @return string
168
 */
169
function getScriptName()
170
{
171
    $scriptName = '';
172
    if (IS_CLI) {
0 ignored issues
show
Bug introduced by
The constant IS_CLI was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
173
        $scriptName = explode(EXT, $_SERVER['PHP_SELF']);
0 ignored issues
show
Bug introduced by
The constant EXT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
174
        $scriptName = rtrim(str_replace($_SERVER['HTTP_HOST'], '', $scriptName[0] . '.php'), '/');
175
    } else {
176
        $scriptName = rtrim($_SERVER['SCRIPT_NAME'], '/');
177
    }
178
179
    return $scriptName;
180
}
181
182
/**
183
 * 获取当前主机
184
 * @return string
185
 */
186
function getSiteHost()
187
{
188
    $host = '';
189
    if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
190
        $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
191
    } elseif (isset($_SERVER['HTTP_HOST'])) {
192
        $host = $_SERVER['HTTP_HOST'];
193
    }
194
195
    $host = strip_tags($host);
196
197
    return $host;
198
}
199
200
/**
201
 * 获取应用根目录
202
 * @return string
203
 */
204
function getRootPath()
205
{
206
    $root = dirname(_PHP_FILE_);
0 ignored issues
show
Bug introduced by
The constant _PHP_FILE_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
207
    if ($root == '/' || $root == '\\') {
208
        $root = '';
209
    } else {
210
        $root = rtrim($root, '/');
211
    }
212
213
    return $root;
214
}
215
216
/**
217
 * @title 获取环境配置
218
 * @param null $name
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $name is correct as it would always require null to be passed?
Loading history...
219
 * @return array|bool
220
 */
221
function sgenv($name = null)
222
{
223
    global $sg;
224
225
    if (is_null($name)) {
226
        // 环境配置文件
227
        $file = dirname($_SERVER['SCRIPT_FILENAME']) . DIRECTORY_SEPARATOR . '.env';
228
        if (is_file($file)) {
229
            $sg['_env'] = parse_ini_file($file, true);
230
        }
231
232
        return $sg['_env'];
233
    }
234
235
    if (false !== strpos($name, '.')) {
236
        $names = explode('.', $name);
237
        $arr   = $sg['_env'];
238
        for ($i = 0; $i < count($names); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
239
            if (isset($arr[strval($names[$i])])) {
240
                $arr = $arr[strval($names[$i])];
241
            } else {
242
                return null;
243
            }
244
        }
245
246
        if (!is_null($arr)) {
247
            return $arr;
248
        }
249
    } else {
250
        return $sg['_env'][$name];
251
    }
252
}
253
254
/**
255
 * 纯request请求
256
 */
257
function raw_request()
258
{
259
    $request['server_name']     = $_SERVER['SERVER_NAME'];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$request was never initialized. Although not strictly required by PHP, it is generally a good practice to add $request = array(); before regardless.
Loading history...
260
    $request['server_port']     = $_SERVER['SERVER_PORT'];
261
    $request['server_protocol'] = $_SERVER['SERVER_PROTOCOL'];
262
    $request['script_name']     = $_SERVER['SCRIPT_NAME'];
263
    $request['requet_scheme']   = $_SERVER['REQUEST_SCHEME'];
264
    $request['request_method']  = $_SERVER['REQUEST_METHOD'];
265
    $request['request_time']    = $_SERVER['REQUEST_TIME'];
266
    $request['query_string']    = $_SERVER['QUERY_STRING'];
267
268
    $request['url'] = $_SERVER['REQUEST_URI'];
269
    $url            = parse_url($request['url']);
270
    if (!isset($url['query'])) {
271
        $url['query'] = '';
272
    }
273
    $request            = array_merge($request, $url);
274
    $pathinfo           = explode(DS, ltrim($request['path'], DS));
0 ignored issues
show
Bug introduced by
The constant DS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
275
    $request['project'] = $pathinfo[0];
276
277
    return $request;
278
}
279
280
/**
281
 * 载入配置 修改自ThinkPHP:C函数 为了不与tp冲突
282
 * @param  string              $name 配置名/文件名.
283
 * @param  string|array|object $value 配置赋值
284
 * @return void|null
285
 */
286
function sgconfig($name = null, $value = null)
287
{
288
    global $sg;
289
    // 无参数时获取所有
290
    if (empty($name)) {
291
        return $sg['_config'];
292
    }
293
    // 优先执行设置获取或赋值
294
    if (is_string($name)) {
0 ignored issues
show
introduced by
The condition is_string($name) is always true.
Loading history...
295
        if (!strpos($name, '.')) {
296
            $name = strtolower($name);
297
            if (is_null($value)) {
298
                return isset($sg['_config'][$name]) ? $sg['_config'][$name] : null;
299
            }
300
            $sg['_config'][$name] = $value;
301
302
            return;
303
        }
304
        // 二维数组设置和获取支持
305
        $name    = explode('.', $name);
306
        $name[0] = strtolower($name[0]);
307
        if (is_null($value)) {
308
            return isset($sg['_config'][$name[0]][$name[1]]) ? $sg['_config'][$name[0]][$name[1]] : null;
309
        }
310
        $sg['_config'][$name[0]][$name[1]] = $value;
311
312
        return;
313
    }
314
    // 批量设置
315
    if (is_array($name)) {
316
        return $sg['_config'] = array_merge((array)$sg['_config'], array_change_key_case($name));
317
    }
318
319
    return null;// 避免非法参数
320
}
321
322
/**
323
 * @title 载入全局配置
324
 * @param $path
325
 */
326
function load_sys_config($path)
327
{
328
    if (is_dir($path)) {
329
        $files = isset($path) ? scandir($path) : [];
330
        foreach ($files as $file) {
331
            if ($file != '.' && $file != '..' && '.' . pathinfo($file, PATHINFO_EXTENSION) == EXT) {
0 ignored issues
show
Bug introduced by
The constant EXT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
332
                $filename = $path . $file;
333
                if (file_exists($filename)) {
334
                    sgconfig(include $filename);
335
                }
336
            }
337
        }
338
    }
339
}
340
341
/**
342
 * 执行钩子方法
343
 * @param  string $name 钩子方法名.
344
 * @param  array  $params 钩子参数数组.
345
 * @return array|string Stripped array (or string in the callback).
346
 */
347
function sghook($name, $params = array())
348
{
349
    global $sg;
350
    $hooks = $sg['_config']['hooks'][$name];
351
    if ($hooks) {
352
        foreach ($hooks as $call) {
353
            if (is_callable($call)) {
354
                $result = call_user_func_array($call, $params);
355
            }
356
        }
357
358
        return $result;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.
Loading history...
359
    }
360
361
    return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string|array.
Loading history...
362
}
363
364
/**
365
 * Navigates through an array and removes slashes from the values.
366
 * If an array is passed, the array_map() function causes a callback to pass the
367
 * value back to the function. The slashes from this value will removed.
368
 * @param  array|string $value The array or string to be striped.
369
 * @return array|string Stripped array (or string in the callback).
370
 */
371
function stripslashes_deep($value)
372
{
373
    if (is_array($value)) {
374
        $value = array_map('stripslashes_deep', $value);
375
    } elseif (is_object($value)) {
0 ignored issues
show
introduced by
The condition is_object($value) is always false.
Loading history...
376
        $vars = get_object_vars($value);
377
        foreach ($vars as $key => $data) {
378
            $value->{$key} = stripslashes_deep($data);
379
        }
380
    } else {
381
        $value = stripslashes($value);
382
    }
383
384
    return $value;
385
}
386
387
/**
388
 * GPC参数过滤
389
 * @param  array|string $value The array or string to be striped.
390
 * @return array|string Stripped array (or string in the callback).
391
 */
392
function check_gpc($value = array())
393
{
394
    if (!is_array($value)) {
395
        return;
396
    }
397
    foreach ($value as $key => $data) {
398
        //对get、post的key值做限制,只允许数字、字母、及部分符号_-[]#@~
399
        // if(!preg_match('/^[a-zA-Z0-9,_\;\-\/\*\.#!@~\[\]]+$/i',$key)){
400
        // 	die('wrong_parameter: not safe get/post/cookie key.');
401
        // }
402
        //如果key值为app\mod\act,value只允许数字、字母下划线
403
        if (($key == 'app' || $key == 'mod' || $key == 'act') && !empty($data)) {
404
            if (!preg_match('/^[a-zA-Z0-9_]+$/i', $data)) {
405
                die('wrong_parameter: not safe app/mod/act value.');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
406
            }
407
        }
408
    }
409
}
410
411
/**
412
 * 返回16位md5值
413
 * @param  string $str 字符串
414
 * @return string $str 返回16位的字符串
415
 */
416
function sgmd5($str)
417
{
418
    return substr(md5($str), 8, 16);
419
}
420
421
/**
422
 * 全站静态缓存,替换之前每个model类中使用的静态缓存
423
 * 类似于s和f函数的使用
424
 * @param      $cache_id
425
 * @param null $value
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $value is correct as it would always require null to be passed?
Loading history...
426
 * @param bool $clean
427
 * @return array|bool|mixed
428
 */
429
function static_cache($cache_id, $value = null, $clean = false)
430
{
431
    static $cacheHash = array();
432
    if ($clean) { //清空缓存 其实是清不了的 程序执行结束才会自动清理
433
        unset($cacheHash);
434
        $cacheHash = array(0);
435
436
        return $cacheHash;
437
    }
438
    if (empty($cache_id)) {
439
        return false;
440
    }
441
    if ($value === null) {
442
        //获取缓存数据
443
        return isset($cacheHash[$cache_id]) ? $cacheHash[$cache_id] : false;
444
    } else {
445
        //设置缓存数据
446
        $cacheHash[$cache_id] = $value;
447
448
        return $cacheHash[$cache_id];
449
    }
450
}