common.php 78KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376
  1. <?php
  2. error_reporting(E_ERROR | E_PARSE);
  3. /**
  4. * 行为绑定
  5. */
  6. \think\Hook::add('app_init', 'app\\common\\behavior\\InitConfigBehavior');
  7. use app\common\adapter\AuthAdapter;
  8. use app\admin\model\User as UserModel;
  9. use app\admin\model\Field as FieldModel;
  10. use think\Request;
  11. use think\Db;
  12. use extend\email\Email;
  13. use think\Lang;
  14. use think\helper\Time;
  15. use com\IpLocation;
  16. use app\crm\traits\DataTime;
  17. /**
  18. * 对象 转 数组
  19. *
  20. * @param object $obj 对象
  21. * @return array
  22. */
  23. function object_to_array($obj)
  24. {
  25. $obj = (array)$obj;
  26. foreach ($obj as $k => $v) {
  27. if (gettype($v) == 'resource') {
  28. return;
  29. }
  30. if (gettype($v) == 'object' || gettype($v) == 'array') {
  31. $obj[$k] = (array)object_to_array($v);
  32. }
  33. }
  34. return $obj;
  35. }
  36. /**
  37. * 数组 转 对象
  38. *
  39. * @param array $arr 数组
  40. * @return object
  41. */
  42. function array_to_object($arr)
  43. {
  44. if (gettype($arr) != 'array') {
  45. return;
  46. }
  47. foreach ($arr as $k => $v) {
  48. if (gettype($v) == 'array' || getType($v) == 'object') {
  49. $arr[$k] = (object)array_to_object($v);
  50. }
  51. }
  52. return (object)$arr;
  53. }
  54. /**
  55. * 返回对象
  56. * @param $array 响应数据
  57. */
  58. function resultArray($array)
  59. {
  60. if (isset($array['data'])) {
  61. $array['error'] = '';
  62. $code = 200;
  63. } elseif (is_array($array['error'])) {
  64. $code = 402; //返回数组格式
  65. $array['data'] = '';
  66. } elseif (isset($array['error'])) {
  67. $code = 400;
  68. $array['data'] = '';
  69. }
  70. return json([
  71. 'code' => $code,
  72. 'data' => $array['data'],
  73. 'error' => $array['error']
  74. ]);
  75. }
  76. /**
  77. * 调试方法
  78. * @param array $data [description]
  79. */
  80. function p($data, $die = 1)
  81. {
  82. echo "<pre>";
  83. print_r($data);
  84. echo "</pre>";
  85. if ($die) die;
  86. }
  87. /**
  88. * 用户密码加密方法
  89. * @param string $str 加密的字符串
  90. * @param [type] $auth_key 加密符
  91. * @param [string] $username 用户名
  92. * @return string 加密后长度为32的字符串
  93. */
  94. function user_md5($str, $auth_key = '', $username = '')
  95. {
  96. return '' === $str ? '' : md5(sha1($str) . md5($str . $auth_key));
  97. }
  98. /**
  99. * 金额展示规则,超过1万时以万为单位,低于1万时以千为单位,低于1千时以元为单位
  100. * @param string $money 金额
  101. * @return string
  102. * @author Michael_xu
  103. */
  104. function money_view($money)
  105. {
  106. $data = '0元';
  107. if (($money / 10000) > 1) {
  108. $data = is_int($money / 10000) ? ($money / 10000) . '万' : rand(($money / 10000), 2) . '万';
  109. } elseif (($money / 1000) > 1) {
  110. $data = is_int($money / 1000) ? ($money / 1000) . '千' : rand(($money / 1000), 2) . '千';
  111. } else {
  112. $data = $money . '元';
  113. }
  114. return $data;
  115. }
  116. /**
  117. * 高级筛选条件
  118. * @param $array 条件数组
  119. * @param $module 相关模块
  120. * @return string
  121. * @author Michael_xu
  122. */
  123. function where_arr($array = [], $m = '', $c = '', $a = '')
  124. {
  125. $userModel = new UserModel();
  126. $checkStatusList = ['待审核', '审核中', '审核通过', '审核失败', '已撤回', '未提交', '已作废'];
  127. $checkStatusArray = ['待审核' => 0, '审核中' => 1, '审核通过' => 2, '审核失败' => 3, '已撤回' => 4, '未提交' => 5, '已作废' => 6];
  128. //查询自定义字段模块多选字段类型
  129. $check_field_arr = [];
  130. //特殊字段
  131. //过滤系统参数
  132. $unset_arr = ['page', 'limit', 'order_type', 'order_field'];
  133. if (!is_array($array)) {
  134. return [];
  135. }
  136. $types = $c;
  137. foreach ($array as $k => $v) {
  138. if (!in_array($k, $unset_arr)) {
  139. $c = $types . '.';
  140. if ($k == 'customer_name') {
  141. $k = 'name';
  142. $c = 'customer.';
  143. }
  144. if ($k == 'contract_name') {
  145. $k = 'name';
  146. $c = 'contract.';
  147. }
  148. if ($k == 'business_name') {
  149. $k = 'name';
  150. $c = 'business.';
  151. }
  152. if ($k == 'contacts_name') {
  153. $k = 'name';
  154. $c = 'contacts.';
  155. }
  156. if ($v['form_type'] == 'date') {
  157. if (!empty($v['start'])) $v['start'] = date('Y-m-d', $v['start']);
  158. if (!empty($v['end'])) $v['end'] = date('Y-m-d', $v['end']);
  159. }
  160. # 创建人、负责人、回访人(非自定义字段)
  161. if ($v['form_type'] == 'user' && in_array($k, ['create_user_id', 'owner_user_id'])) {
  162. if ($v['condition'] == 'is') $v['condition'] = 'contains';
  163. }
  164. # 自定义字段的user、structure类型
  165. if (($v['form_type'] == 'user' && !in_array($k, ['create_user_id', 'owner_user_id'])) || $v['form_type'] == 'structure') {
  166. if ($v['condition'] == 'is') $v['condition'] = 'contains';
  167. if ($v['condition'] == 'isNot') {
  168. return "(".$c.$k." not like '%".$v['value'][0]."%' OR ".$c.$k." is null)";
  169. }
  170. }
  171. # 处理多选字段的精确搜索
  172. if ($v['form_type'] == 'checkbox' && !empty($v['value'])) {
  173. if ($v['condition'] == 'is' && count($v['value']) == 1) $v['value'][0] = ',' . $v['value'][0] . ',';
  174. if ($v['condition'] == 'is' && count($v['value']) > 1) {
  175. $checkboxLike = '';
  176. foreach ($v['value'] AS $kk => $vv) {
  177. $checkboxLike .= $c.$k." like "."'%".$vv."%' AND ";
  178. }
  179. return "(".$checkboxLike."LENGTH(".$c.$k.") = LENGTH('".arrayToString($v['value'])."'))";
  180. }
  181. }
  182. if ($types == 'contract' && !empty($v['value'])) {
  183. switch ($k) {
  184. case 'business_id' :
  185. $k = 'name';
  186. $c = 'business.';
  187. break;
  188. case 'contacts_id' :
  189. $contactsIds = [];
  190. foreach ($v['value'] AS $kk => $vv) {
  191. $contactsIdArray = db('crm_contacts')->whereLike('name', '%' . $vv . '%')->column('contacts_id');
  192. foreach ($contactsIdArray AS $kkk => $vvv) {
  193. $contactsIds[] = $vvv;
  194. }
  195. }
  196. $v['value'] = array_unique($contactsIds);
  197. break;
  198. }
  199. }
  200. if ($types == 'receivables' && $v['name'] == '合同编号' && !empty($v['value'])) {
  201. $k = 'num';
  202. $c = 'contract.';
  203. }
  204. if ($types == 'receivables' && $k == 'plan_id' && !empty($v['value'])) {
  205. $planIds = [];
  206. foreach ($v['value'] AS $kk => $vv) {
  207. $planIdArray = db('crm_receivables_plan')->whereLike('num', '%' . $vv . '%')->column('plan_id');
  208. foreach ($planIdArray AS $kkk => $vvv) {
  209. $planIds[] = $vvv;
  210. }
  211. }
  212. $v['value'] = array_unique($planIds);
  213. }
  214. if ($types == 'invoice' && $v['type'] == 'invoice_status' && !empty($v['value'])) {
  215. foreach ($v['value'] AS $kk => $vv) {
  216. if ($vv == '已开票') $v['value'][$kk] = 1;
  217. if ($vv == '未开票') $v['value'][$kk] = 0;
  218. }
  219. }
  220. if ($types == 'visit' && $v['type'] == 'contract_name' && !empty($v['value'])) {
  221. $k = 'num';
  222. $c = 'contract.';
  223. }
  224. if ($types == 'visit' && $v['type'] == 'contacts_name' && !empty($v['value'])) {
  225. $k = 'name';
  226. $c = 'contacts.';
  227. }
  228. if ($k == 'check_status' && is_array($v) && in_array($v['value'][0], $checkStatusList) && !empty($v['value'])) {
  229. $v['value'] = $checkStatusArray[$v['value'][0]] ?: '0';
  230. }
  231. if (is_array($v)) {
  232. if ($v['state']) {
  233. $address_where[] = '%' . $v['state'] . '%';
  234. if ($v['city']) {
  235. $address_where[] = '%' . $v['city'] . '%';
  236. if ($v['area']) {
  237. $address_where[] = '%' . $v['area'] . '%';
  238. }
  239. }
  240. if ($v['condition'] == 'not_contain') {
  241. $where[$c . $k] = ['notlike', $address_where, 'OR'];
  242. } else {
  243. $where[$c . $k] = ['like', $address_where, 'AND'];
  244. }
  245. } elseif (!empty($v['value']['state'])) {
  246. $addressWhere[] = '%' . $v['value']['state'] . '%';
  247. if (!empty($v['value']['city'])) $addressWhere[] = '%' . $v['value']['city'] . '%';
  248. if (!empty($v['value']['area'])) $addressWhere[] = '%' . $v['value']['area'] . '%';
  249. if ($v['condition'] == 'is') {
  250. $where[$c . $k] = ['like', $addressWhere, 'AND'];
  251. } else {
  252. $where[$c . $k] = ['notlike', $addressWhere, 'OR'];
  253. }
  254. } elseif (!empty($v['start']) || !empty($v['end'])) {
  255. if ($v['start'] && $v['end']) {
  256. $where[$c . $k] = ['between', [$v['start'], $v['end']]];
  257. } elseif ($v['start']) {
  258. $where[$c . $k] = ['egt', $v['start']];
  259. } else {
  260. $where[$c . $k] = ['elt', $v['end']];
  261. }
  262. } elseif (!empty($v['start_date']) || !empty($v['end_date'])) {
  263. if ($v['start_date'] && $v['end_date']) {
  264. $where[$c . $k] = ['between', [$v['start_date'], $v['end_date']]];
  265. } elseif ($v['start_date']) {
  266. $where[$c . $k] = ['egt', $v['start_date']];
  267. } else {
  268. $where[$c . $k] = ['elt', $v['end_date']];
  269. }
  270. } elseif (!empty($v['value']) || $v['value'] === '0') {
  271. if (in_array($k, $check_field_arr)) {
  272. $where[$c . $k] = field($v['value'], 'contains');
  273. } else {
  274. $where[$c . $k] = field($v['value'], $v['condition'], $k);
  275. }
  276. } elseif (in_array($v['condition'], ['isNull', 'isNotNull', 'in'])) {
  277. $where[$c . $k] = field($v['value'], $v['condition']);
  278. } else {
  279. $where[$c . $k] = $v;
  280. }
  281. } elseif (!empty($v)) {
  282. $where[$c . $k] = field($v);
  283. } else {
  284. $where[$c . $k] = $v;
  285. }
  286. }
  287. }
  288. # 商机阶段为赢单、输单、无效的值保存在is_end中,将status_id改为is_end;
  289. if (!empty($where['business.status_id']) && in_array($where['business.status_id'][1], [1,2,3])) {
  290. $where['business.is_end'] = $where['business.status_id'];
  291. unset($where['business.status_id']);
  292. }
  293. return $where ?: [];
  294. }
  295. /**
  296. * 根据搜索生成where条件
  297. *
  298. * @param string $search 搜索内容
  299. * @param $condition 搜索条件
  300. * @param $k 搜索字段
  301. * @return array|Closure|string[]
  302. */
  303. function field($search, $condition = '', $k = '')
  304. {
  305. switch (trim($condition)) {
  306. case "is" :
  307. $where = ['in', $search];
  308. break;
  309. case "isNot" :
  310. $where = ['notin', $search];
  311. break;
  312. case "contains" :
  313. $containsWhere = [];
  314. foreach ((array)$search AS $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
  315. $where = ['like', $containsWhere, 'OR'];
  316. break;
  317. case "notContains" :
  318. $containsWhere = [];
  319. foreach ((array)$search AS $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
  320. $where = ['notlike', $containsWhere, 'AND'];
  321. break;
  322. case "startWith" :
  323. $startWithWhere = [];
  324. foreach ((array)$search AS $key1 => $value1) $startWithWhere[] = $value1 . '%';
  325. $where = ['like', $startWithWhere, 'OR'];
  326. break;
  327. case "endWith" :
  328. $endWithWhere = [];
  329. foreach ((array)$search AS $key1 => $value1) $endWithWhere[] = '%' . $value1;
  330. $where = ['like', $endWithWhere, 'OR'];
  331. break;
  332. case "isNull" :
  333. $where = ['eq', ''];
  334. break;
  335. case "isNotNull" :
  336. $where = ['neq', ''];
  337. break;
  338. case "eq" :
  339. $where = function ($query) use ($search, $k) {
  340. foreach ((array)$search AS $key1 => $value1) {
  341. $query->whereOr($k, $value1);
  342. }
  343. };
  344. break;
  345. case "neq" :
  346. $where = function ($query) use ($search, $k) {
  347. foreach ((array)$search AS $key1 => $value1) {
  348. $query->whereOr($k, '<>', $value1);
  349. }
  350. };
  351. break;
  352. case "gt" :
  353. $where = function ($query) use ($search, $k) {
  354. foreach ((array)$search AS $key1 => $value1) {
  355. $query->whereOr($k, '>', $value1);
  356. }
  357. };
  358. break;
  359. case "egt" :
  360. $where = function ($query) use ($search, $k) {
  361. foreach ((array)$search AS $key1 => $value1) {
  362. $query->whereOr($k, '>=', $value1);
  363. }
  364. };
  365. break;
  366. case "lt" :
  367. $where = function ($query) use ($search, $k) {
  368. foreach ((array)$search AS $key1 => $value1) {
  369. $query->whereOr($k, '<', $value1);
  370. }
  371. };
  372. break;
  373. case "elt" :
  374. $where = function ($query) use ($search, $k) {
  375. foreach ((array)$search AS $key1 => $value1) {
  376. $query->whereOr($k, '<=', $value1);
  377. }
  378. };
  379. break;
  380. case "in" :
  381. $where = ['in', $search];
  382. break;
  383. default :
  384. $where = ['eq', $search];
  385. break;
  386. }
  387. return $where;
  388. }
  389. /**
  390. * 将单个搜索转换为高级搜索格式
  391. * @param string $value 搜索内容
  392. * @param $condition 搜索条件
  393. * @return array
  394. * @author Michael_xu
  395. */
  396. function field_arr($value, $condition = '')
  397. {
  398. if (is_array($value)) {
  399. } else {
  400. $condition = $condition ?: 'eq';
  401. $where_arr = ['value' => $value, 'condition' => $condition];
  402. }
  403. return $where_arr;
  404. }
  405. /**
  406. * 记录操作日志
  407. * @param $id array 操作对象id数组
  408. * @return
  409. * @author Michael_xu
  410. */
  411. function actionLog($id, $join_user_ids = '', $structure_ids = '', $content = '')
  412. {
  413. if (!is_array($id)) {
  414. $idArr[] = $id;
  415. } else {
  416. $idArr = $id;
  417. }
  418. $header = Request::instance()->header();
  419. $authKey = $header['authkey'];
  420. $cache = cache('Auth_'.$authKey);
  421. if (!$cache) {
  422. return false;
  423. }
  424. $userInfo = $cache['userInfo'];
  425. $category = $userInfo['id'] == 1 ? '管理员' : '员工';
  426. $request = request();
  427. $m = strtolower($request->module());
  428. $c = strtolower($request->controller());
  429. $a = strtolower($request->action());
  430. $res_action = true;
  431. foreach ($idArr as $v) {
  432. $data = [];
  433. $data['user_id'] = $userInfo['id'];
  434. $data['module_name'] = $module_name = $m;
  435. $data['controller_name'] = $controller_name = $c;
  436. $data['action_name'] = $action_name = $a;
  437. $data['action_id'] = $v;
  438. $data['create_time'] = time();
  439. $data['client_ip'] = request()->ip();
  440. $data['content'] = $content ? : lang('ACTIONLOG', [$category, $userInfo['realname'], date('Y-m-d H:i:s'), lang($action_name), $v, lang($controller_name)]);
  441. $data['join_user_ids'] = $join_user_ids ? : ''; //抄送人
  442. $data['structure_ids'] = $structure_ids ? : ''; //抄送部门
  443. if ($action_name == 'delete' || $action_name == 'commentdel') {
  444. $data['action_delete'] = 1;
  445. }
  446. if (!db('admin_action_log')->insert($data)) {
  447. $res_action = false;
  448. }
  449. # 数据操作日志
  450. db('admin_operation_log')->insert([
  451. 'user_id' => $userInfo['id'],
  452. 'client_ip' => request()->ip(),
  453. 'module' => $m . '_' . $c,
  454. 'action_id' => $v,
  455. 'content' => $content,
  456. 'create_time' => time()
  457. ]);
  458. }
  459. if ($res_action) {
  460. return true;
  461. } else {
  462. return false;
  463. }
  464. }
  465. /**
  466. * 判断操作权限
  467. * @param
  468. * @return
  469. * @author Michael_xu
  470. */
  471. function checkPerByAction($m, $c, $a)
  472. {
  473. /*获取头部信息*/
  474. $header = Request::instance()->header();
  475. $authKey = $header['authkey'];
  476. $cache = cache('Auth_' . $authKey);
  477. if (!$cache) {
  478. return false;
  479. }
  480. $userInfo = $cache['userInfo'];
  481. $adminTypes = adminGroupTypes($userInfo['id']);
  482. if (in_array(1, $adminTypes)) {
  483. return true;
  484. }
  485. if (empty($m) && empty($c) && empty($a)) {
  486. $request = Request::instance();
  487. $m = strtolower($request->module());
  488. $c = strtolower($request->controller());
  489. $a = strtolower($request->action());
  490. }
  491. $authAdapter = new AuthAdapter($authKey);
  492. $ruleName = $m . '-' . $c . '-' . $a;
  493. if (!$authAdapter->checkIntime($ruleName, $userInfo['id'])) {
  494. return false;
  495. }
  496. return true;
  497. }
  498. /**
  499. * 给树状菜单添加level并去掉没有子菜单的菜单项
  500. * @param array $data [description]
  501. * @param integer $root [description]
  502. * @param string $child [description]
  503. * @param string $level [description]
  504. */
  505. function memuLevelClear($data, $root = 1, $child = 'children', $level = 'level')
  506. {
  507. if (is_array($data)) {
  508. foreach ($data as $key => $val) {
  509. // $data[$key]['selected'] = false;
  510. $data[$key]['level'] = $root;
  511. if (!empty($val[$child]) && is_array($val[$child])) {
  512. $data[$key][$child] = memuLevelClear($val[$child], $root + 1);
  513. } else if ($root < 3 && $data[$key]['menu_type'] == 1) {
  514. unset($data[$key]);
  515. }
  516. if (empty($data[$key][$child]) && ($data[$key]['level'] == 1) && ($data[$key]['menu_type'] == 1)) {
  517. unset($data[$key]);
  518. }
  519. }
  520. return array_values($data);
  521. }
  522. return array();
  523. }
  524. /**
  525. * [rulesDeal 给树状规则表处理成 module-controller-action ]
  526. * @AuthorHTL
  527. * @DateTime
  528. * @param [array] $data [树状规则数组]
  529. * @return [array] [返回数组]
  530. */
  531. function rulesDeal($data)
  532. {
  533. if (is_array($data)) {
  534. $ret = [];
  535. foreach ($data as $k1 => $v1) {
  536. $str1 = $v1['name'];
  537. if (is_array($v1['children'])) {
  538. foreach ($v1['children'] as $k2 => $v2) {
  539. $str2 = $str1 . '-' . $v2['name'];
  540. if (is_array($v2['children'])) {
  541. foreach ($v2['children'] as $k3 => $v3) {
  542. $str3 = $str2 . '-' . $v3['name'];
  543. $ret[] = $str3;
  544. }
  545. } else {
  546. $ret[] = $str2;
  547. }
  548. }
  549. } else {
  550. $ret[] = $str1;
  551. }
  552. }
  553. return $ret;
  554. }
  555. return [];
  556. }
  557. /**
  558. * 获取下属userId
  559. * @param $self == true 包含自己
  560. * @param $type == 0 下属userid
  561. * @param $type == 1 全部userid
  562. * @param $user_id 需要查询的user_id
  563. * @author Michael_xu
  564. */
  565. function getSubUserId($self = true, $type = 0, $user_id = '')
  566. {
  567. $request = Request::instance();
  568. $header = $request->header();
  569. $authKey = $header['authkey'];
  570. $cache = cache('Auth_' . $authKey);
  571. if (!$user_id) {
  572. if (!$cache) {
  573. return false;
  574. }
  575. $userInfo = $cache['userInfo'];
  576. $user_id = $userInfo['id'];
  577. $adminTypes = adminGroupTypes($user_id);
  578. if (in_array(1, $adminTypes)) {
  579. $type = 1;
  580. }
  581. }
  582. $belowIds = [];
  583. if (empty($type)) {
  584. if ($user_id) {
  585. $belowIds = getSubUser($user_id);
  586. }
  587. } else {
  588. $belowIds = getSubUser(0);
  589. }
  590. if ($self == true) {
  591. $belowIds[] = $user_id;
  592. } else {
  593. $belowIds = $belowIds ? array_diff($belowIds, array($user_id)) : [];
  594. }
  595. return array_unique($belowIds);
  596. }
  597. /**
  598. * 获取下属userId
  599. * @author Michael_xu
  600. */
  601. function getSubUser($userId, $queried = [], $allUserList = [])
  602. {
  603. if (empty($allUserList)) {
  604. $allUserList = db('admin_user')->field('id,parent_id')->select();
  605. }
  606. foreach ($allUserList as $k=>$v) {
  607. if ($v['parent_id'] == $userId) {
  608. $sub_user[] = $v['id'];
  609. }
  610. }
  611. if ($sub_user) {
  612. foreach ($sub_user as $v) {
  613. if (in_array($v, $queried)) {
  614. continue;
  615. }
  616. $queried[] = $v;
  617. $son_user = [];
  618. $son_user = getSubUser($v, $queried, $allUserList);
  619. if (!empty($son_user)) {
  620. $sub_user = array_merge($sub_user, $son_user);
  621. }
  622. }
  623. }
  624. return $sub_user;
  625. }
  626. /**
  627. * 阿里大于短信发送
  628. * @param unknown $appkey
  629. * @param unknown $secret
  630. * @param unknown $signName 短信签名
  631. * @param unknown $smsParam
  632. * @param unknown $templateCode 短信模板
  633. * @param unknown $send_mobile 接收手机号
  634. * @param unknown $code 短信验证码
  635. * @param unknown $template_code 模板参数
  636. */
  637. function aliSmsSend($send_mobile, $code, $signName, $templateCode)
  638. {
  639. $appkey = '';
  640. $secret = '';
  641. import('alimsg.api.Sms', EXTEND_PATH);
  642. header('Content-Type: text/plain; charset=utf-8');
  643. $sms = new Sms($appkey, $secret);
  644. $template_code = array("code" => $code);
  645. $response = $sms->sendSms($signName, $templateCode, $send_mobile, $template_code);
  646. $data = object_to_array($response);
  647. if ($data['Message'] == 'OK' && $data['Code'] == "OK") {
  648. return true;
  649. } else {
  650. return false;
  651. }
  652. }
  653. /**
  654. * 发送邮件
  655. * @param unknown $toemail
  656. * @param unknown $title
  657. * @param unknown $content
  658. * @return boolean
  659. */
  660. function emailSend($email_host, $email_id, $email_pass, $email_addr, $toemail, $title, $content)
  661. {
  662. $result = false;
  663. try {
  664. $mail = new Email();
  665. $mail->setServer($email_host, $email_id, $email_pass);
  666. $mail->setFrom($email_addr);
  667. $mail->setReceiver($toemail);
  668. $mail->setMailInfo($title, $content);
  669. $result = $mail->sendMail();
  670. } catch (\Exception $e) {
  671. $result = false;
  672. }
  673. return $result;
  674. }
  675. /**
  676. * 发送站内信
  677. * @param $user_id 接收人user_id
  678. * @param $action_id 操作id
  679. * @param $sysMessage 1为系统消息
  680. * @param $content 消息内容
  681. * @return
  682. * @author Michael_xu
  683. */
  684. function sendMessage($user_id, $content, $action_id, $sysMessage = 0)
  685. {
  686. $content = trim($content);
  687. if (!$user_id) return false;
  688. if (!$content) return false;
  689. if (!is_array($user_id)) {
  690. $user_ids[] = $user_id;
  691. } else {
  692. $user_ids = $user_id;
  693. }
  694. $user_ids = array_unique(array_filter($user_ids));
  695. $request = request();
  696. $m = strtolower($request->module());
  697. $c = strtolower($request->controller());
  698. $a = strtolower($request->action());
  699. $userInfo = [];
  700. if ($sysMessage == 0) {
  701. $header = $request->header();
  702. $authkey = $header['authkey'];
  703. $cache = cache('Auth_' . $authkey);
  704. if (!$cache) {
  705. return false;
  706. }
  707. $userInfo = $cache['userInfo'];
  708. }
  709. foreach ($user_ids as $v) {
  710. $data = [];
  711. $data['content'] = $content;
  712. $data['from_user_id'] = $userInfo['id'] ? : 0;
  713. $data['to_user_id'] = $v;
  714. $data['read_time'] = 0;
  715. $data['send_time'] = time();
  716. $data['module_name'] = $m;
  717. $data['controller_name'] = $c;
  718. $data['action_name'] = $a;
  719. $data['action_id'] = $action_id;
  720. db('admin_message')->insert($data);
  721. }
  722. return true;
  723. }
  724. /**
  725. * 格式化字节大小
  726. * @param number $size 字节数
  727. * @param string $delimiter 数字和单位分隔符
  728. * @return string 格式化后的带单位的大小
  729. * @author
  730. */
  731. function format_bytes($size, $delimiter = '')
  732. {
  733. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  734. for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
  735. return round($size, 2) . $delimiter . $units[$i];
  736. }
  737. /**
  738. * 数据修改日志
  739. * @param $types 类型
  740. * @param $action_id 操作ID
  741. * @param $newData 新数据
  742. * @param $newData 新数据
  743. * @return
  744. * @author Michael_xu
  745. */
  746. function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData = [], $content = '')
  747. {
  748. if (is_array($oldData) && is_array($newData) && $user_id) {
  749. $differentData = array_diff_assoc($newData, $oldData);
  750. $fieldModel = new FieldModel();
  751. $userModel = new UserModel();
  752. $structureModel = new \app\admin\model\Structure();
  753. $field_arr = $fieldModel->getField(['types' => $types, 'unFormType' => ['file', 'form']]); //获取字段属性
  754. $newFieldArr = array();
  755. foreach ($field_arr as $k => $v) {
  756. $newFieldArr[$v['field']] = $v;
  757. }
  758. $unField = ['update_time','create_time']; //定义过滤字段
  759. $message = [];
  760. $un_form_type = ['file', 'form'];
  761. foreach ($differentData as $k => $v) {
  762. if ($newFieldArr[$k] && !in_array($newFieldArr[$k]['form_type'], $un_form_type)) {
  763. $field_name = '';
  764. $field_name = $newFieldArr[$k]['name'];
  765. $new_value = $v;
  766. $old_value = $oldData[$k] ?: '空';
  767. if ($newFieldArr[$k]['form_type'] == 'datetime') {
  768. $new_value = $v ? date('Y-m-d', $v) : '';
  769. $old_value = date('Y-m-d', $oldData[$k]);
  770. if (empty($v) && empty($oldData[$k])) continue;
  771. } elseif ($newFieldArr[$k]['form_type'] == 'user') {
  772. $new_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($v))) : '';
  773. $old_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($oldData[$k]))) : '';
  774. } elseif ($newFieldArr[$k]['form_type'] == 'structure') {
  775. $new_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($v))) : '';
  776. $old_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($oldData[$k]))) : '';
  777. } elseif ($newFieldArr[$k]['form_type'] == 'business_status') {
  778. $new_value = $v ? db('crm_business_status')->where(['status_id' => $v])->value('name') : '';
  779. $old_value = $v ? db('crm_business_status')->where(['status_id' => $oldData[$k]])->value('name') : '';
  780. } elseif ($newFieldArr[$k]['form_type'] == 'business_type') {
  781. $new_value = $v ? db('crm_business_type')->where(['type_id' => $v])->value('name') : '';
  782. $old_value = $v ? db('crm_business_type')->where(['type_id' => $oldData[$k]])->value('name') : '';
  783. } elseif ($newFieldArr[$k]['form_type'] == 'customer') {
  784. $new_value = $v ? db('crm_customer')->where(['customer_id' => $v])->value('name') : '';
  785. $old_value = $v ? db('crm_customer')->where(['customer_id' => $oldData[$k]])->value('name') : '';
  786. } elseif ($newFieldArr[$k]['form_type'] == 'category') {
  787. $new_value = $v ? db('crm_product_category')->where(['category_id' => $v])->value('name') : '';
  788. $old_value = $v ? db('crm_product_category')->where(['category_id' => $oldData[$k]])->value('name') : '';
  789. } elseif ($newFieldArr[$k]['form_type'] == 'business') {
  790. $new_value = $v ? db('crm_business')->where(['business_id' => $v])->value('name') : '';
  791. $old_value = $v ? db('crm_business')->where(['business_id' => $oldData[$k]])->value('name') : '';
  792. } elseif ($newFieldArr[$k]['field'] == 'check_status') {
  793. $statusArr = ['0' => '待审核', '1' => '审核中', '2' => '审核通过', '3' => '已拒绝', '4' => '已撤回', '5' => '未提交'];
  794. $new_value = $statusArr[$v];
  795. $old_value = $statusArr[$oldData[$k]];
  796. } elseif ($newFieldArr[$k]['form_type'] == 'visit') {
  797. $new_value = $v ? db('crm_visit')->where(['visit_id' => $v])->value('number') : '';
  798. $old_value = $v ? db('crm_visit')->where(['visit_id' => $oldData[$k]])->value('number') : '';
  799. }
  800. $message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
  801. }
  802. }
  803. if ($message) {
  804. $data = [];
  805. $data['user_id'] = $user_id;
  806. $data['create_time'] = time();
  807. $data['types'] = $types;
  808. $data['action_id'] = $action_id;
  809. $data['content'] = implode('.|.', $message);
  810. db('admin_action_record')->insert($data);
  811. # 数据操作日志
  812. db('admin_operation_log')->insert([
  813. 'user_id' => $user_id,
  814. 'client_ip' => request()->ip(),
  815. 'module' => $types,
  816. 'action_id' => $action_id,
  817. 'content' => implode('.|.', $message),
  818. 'create_time' => time()
  819. ]);
  820. }
  821. } elseif ($content) {
  822. $data = [];
  823. $data['user_id'] = $user_id;
  824. $data['create_time'] = time();
  825. $data['types'] = $types;
  826. $data['action_id'] = $action_id;
  827. $data['content'] = $content;
  828. db('admin_action_record')->insert($data);
  829. # 数据操作日志
  830. db('admin_operation_log')->insert([
  831. 'user_id' => $user_id,
  832. 'client_ip' => request()->ip(),
  833. 'module' => $types,
  834. 'action_id' => $action_id,
  835. 'content' => $content,
  836. 'create_time' => time()
  837. ]);
  838. }
  839. }
  840. /**
  841. * 截取字符串
  842. * @param $start 开始截取位置
  843. * @param $length 截取长度
  844. * @return
  845. * @author Michael_xu
  846. */
  847. function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
  848. {
  849. if (function_exists("mb_substr")) {
  850. $slice = mb_substr($str, $start, $length, $charset);
  851. } elseif (function_exists('iconv_substr')) {
  852. $slice = iconv_substr($str, $start, $length, $charset);
  853. if (false === $slice) {
  854. $slice = '';
  855. }
  856. } else {
  857. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  858. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  859. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  860. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  861. preg_match_all($re[$charset], $str, $match);
  862. $slice = join("", array_slice($match[0], $start, $length));
  863. }
  864. if (utf8_strlen($str) < $length) $suffix = false;
  865. return $suffix ? $slice . '...' : $slice;
  866. }
  867. function utf8_strlen($string = null)
  868. {
  869. preg_match_all("/./us", $string, $match);
  870. return count($match[0]);
  871. }
  872. /**
  873. * 合法性验证
  874. * @param client_sign 签名参数值,使用相同规则对提交参数进行加密验证
  875. * @return
  876. * @author Michael_xu
  877. */
  878. function checkVerify($saftCode = '5kcrm@')
  879. {
  880. $parmList = Request::instance()->post();
  881. $header = $request->header();
  882. $parmList['sessionId'] = $header['sessionId'];
  883. $authkey = $header['authKey'];
  884. $clientSign = $parmList['client_sign'];
  885. if ($clientSign) {
  886. unset($parmList['client_sign']);
  887. if (count($parmList) > 0) {
  888. // 对要签名参数按照签名格式组合
  889. foreach ($parmList as $key => $value) {
  890. if (isset($_POST[$key])) {
  891. $parame[$key] = $key . '=' . trim($_POST[$key]);
  892. } else {
  893. return false;
  894. }
  895. }
  896. ksort($parame); //参数排序
  897. $returnValue = implode("&", $parame); //拼接字符串
  898. if ($returnValue) {
  899. //base64加密
  900. $signCalc = base64_encode(hash_hmac("sha1", $returnValue, $saftCode . $authkey, $raw_output = false));
  901. // 检查参数签名是否一致
  902. if (trim($clientSign) != trim($signCalc)) {
  903. return false;
  904. } else {
  905. return true;
  906. }
  907. } else {
  908. return false;
  909. }
  910. } else {
  911. return false;
  912. }
  913. } else {
  914. //签名认证错误
  915. return false;
  916. }
  917. }
  918. /**
  919. * 数组转换字符串(以逗号隔开)
  920. * @param
  921. * @return
  922. * @author Michael_xu
  923. */
  924. function arrayToString($array)
  925. {
  926. if (!is_array($array)) {
  927. $data_arr[] = $array;
  928. } else {
  929. $data_arr = $array;
  930. }
  931. $data_arr = array_filter($data_arr); //数组去空
  932. $data_arr = array_unique($data_arr); //数组去重
  933. $data_arr = array_merge($data_arr);
  934. $string = $data_arr ? ',' . implode(',', $data_arr) . ',' : '';
  935. return $string ?: '';
  936. }
  937. /**
  938. * 字符串转换数组(以逗号隔开)
  939. * @param
  940. * @return
  941. * @author Michael_xu
  942. */
  943. function stringToArray($string)
  944. {
  945. if (is_array($string)) {
  946. $data_arr = array_unique(array_filter($string));
  947. } else {
  948. $data_arr = $string ? array_unique(array_filter(explode(',', $string))) : [];
  949. }
  950. $data_arr = $data_arr ? array_merge($data_arr) : [];
  951. return $data_arr ?: [];
  952. }
  953. /**
  954. * 根据时间戳获取星期几
  955. * @param $time 要转换的时间戳
  956. */
  957. function getTimeWeek($time, $i = 0)
  958. {
  959. $weekarray = array("日", "一", "二", "三", "四", "五", "六");
  960. $oneD = 24 * 60 * 60;
  961. return "星期" . $weekarray[date("w", $time + $oneD * $i)];
  962. }
  963. /**
  964. * 二维数组排序(选择)
  965. * @param $select 要进行排序的select结果集
  966. * @param $field 排序的字段
  967. * @param $order 排序方式1降序2升序
  968. */
  969. function sort_select($select = array(), $field, $order = 1)
  970. {
  971. $count = count($select);
  972. if ($order == 1) {
  973. for ($i = 0; $i < $count; $i++) {
  974. $k = $i;
  975. for ($j = $i; $j < $count; $j++) {
  976. if ($select[$k][$field] < $select[$j][$field]) {
  977. $k = $j;
  978. }
  979. }
  980. $temp = $select[$i];
  981. $select[$i] = $select[$k];
  982. $select[$k] = $temp;
  983. }
  984. return $select;
  985. } else {
  986. for ($i = 0; $i < $count; $i++) {
  987. $k = $i;
  988. for ($j = $i; $j < $count; $j++) {
  989. if ($select[$k][$field] > $select[$j][$field]) {
  990. $k = $j;
  991. }
  992. }
  993. $temp = $select[$i];
  994. $select[$i] = $select[$k];
  995. $select[$k] = $temp;
  996. }
  997. return $select;
  998. }
  999. }
  1000. /**
  1001. * 将秒数转换为时间 (年、天、小时、分、秒)
  1002. * @param
  1003. */
  1004. function getTimeBySec($time)
  1005. {
  1006. if (is_numeric($time)) {
  1007. $value = array(
  1008. "years" => 0, "days" => 0, "hours" => 0,
  1009. "minutes" => 0, "seconds" => 0,
  1010. );
  1011. if ($time >= 31556926) {
  1012. $value["years"] = floor($time / 31556926);
  1013. $time = ($time % 31556926);
  1014. $t .= $value["years"] . "年";
  1015. }
  1016. if ($time >= 86400) {
  1017. $value["days"] = floor($time / 86400);
  1018. $time = ($time % 86400);
  1019. $t .= $value["days"] . "天";
  1020. }
  1021. if ($time >= 3600) {
  1022. $value["hours"] = floor($time / 3600);
  1023. $time = ($time % 3600);
  1024. $t .= $value["hours"] . "小时";
  1025. }
  1026. if ($time >= 60) {
  1027. $value["minutes"] = floor($time / 60);
  1028. $time = ($time % 60);
  1029. $t .= $value["minutes"] . "分钟";
  1030. }
  1031. if ($time < 60) {
  1032. $value["seconds"] = floor($time);
  1033. $t .= $value["seconds"] . "秒";
  1034. }
  1035. return $t;
  1036. } else {
  1037. return (bool)FALSE;
  1038. }
  1039. }
  1040. /*
  1041. *根据年月计算有几天
  1042. */
  1043. function getmonthByYM($param)
  1044. {
  1045. $month = $param['month'] ? $param['month'] : date('m', time());
  1046. $year = $param['year'] ? $param['year'] : date('Y', time());
  1047. if (in_array($month, array('1', '3', '5', '7', '8', '01', '03', '05', '07', '08', '10', '12'))) {
  1048. $days = '31';
  1049. } elseif ($month == 2) {
  1050. if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 !== 0)) {
  1051. //判断是否是闰年
  1052. $days = '29';
  1053. } else {
  1054. $days = '28';
  1055. }
  1056. } else {
  1057. $days = '30';
  1058. }
  1059. return $days;
  1060. }
  1061. /**
  1062. * 根据时间戳计算当月天数
  1063. * @param
  1064. */
  1065. function getmonthdays($time)
  1066. {
  1067. $month = date('m', $time);
  1068. $year = date('Y', $time);
  1069. if (in_array($month, array('1', '3', '5', '7', '8', '01', '03', '05', '07', '08', '10', '12'))) {
  1070. $days = '31';
  1071. } elseif ($month == 2) {
  1072. if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 !== 0)) {
  1073. //判断是否是闰年
  1074. $days = '29';
  1075. } else {
  1076. $days = '28';
  1077. }
  1078. } else {
  1079. $days = '30';
  1080. }
  1081. return $days;
  1082. }
  1083. /**
  1084. * 生成从开始时间到结束时间的日期数组
  1085. * @param type,默认时间戳格式
  1086. * @param type = 1 时,date格式
  1087. * @param type = 2 时,获取每日开始、结束时间
  1088. */
  1089. function dateList($start, $end, $type = 0)
  1090. {
  1091. if (!is_numeric($start) || !is_numeric($end) || ($end <= $start)) return '';
  1092. $i = 0;
  1093. //从开始日期到结束日期的每日时间戳数组
  1094. $d = array();
  1095. if ($type == 1) {
  1096. while ($start <= $end) {
  1097. $d[$i] = date('Y-m-d', $start);
  1098. $start = $start + 86400;
  1099. $i++;
  1100. }
  1101. } else {
  1102. while ($start <= $end) {
  1103. $d[$i] = $start;
  1104. $start = $start + 86400;
  1105. $i++;
  1106. }
  1107. }
  1108. if ($type == 2) {
  1109. $list = array();
  1110. foreach ($d as $k => $v) {
  1111. $list[$k] = getDateRange($v);
  1112. }
  1113. return $list;
  1114. } else {
  1115. return $d;
  1116. }
  1117. }
  1118. /**
  1119. * 获取指定日期开始时间与结束时间
  1120. */
  1121. function getDateRange($timestamp)
  1122. {
  1123. $ret = array();
  1124. $ret['sdate'] = strtotime(date('Y-m-d', $timestamp));
  1125. $ret['edate'] = strtotime(date('Y-m-d', $timestamp)) + 86400;
  1126. return $ret;
  1127. }
  1128. /**
  1129. * 生成从开始月份到结束月份的月份数组
  1130. * @param int $start 开始时间戳
  1131. * @param int $end 结束时间戳
  1132. */
  1133. function monthList($start, $end)
  1134. {
  1135. if (!is_numeric($start) || !is_numeric($end) || ($end <= $start)) return '';
  1136. $start = date('Y-m', $start);
  1137. $end = date('Y-m', $end);
  1138. //转为时间戳
  1139. $start = strtotime($start . '-01');
  1140. $end = strtotime($end . '-01');
  1141. $i = 0;
  1142. $d = array();
  1143. while ($start <= $end) {
  1144. //这里累加每个月的的总秒数 计算公式:上一月1号的时间戳秒数减去当前月的时间戳秒数
  1145. $d[$i] = $start;
  1146. $start += strtotime('+1 month', $start) - $start;
  1147. $i++;
  1148. }
  1149. return $d;
  1150. }
  1151. /**
  1152. * 人民币转大写
  1153. * @param
  1154. */
  1155. function cny($ns)
  1156. {
  1157. static $cnums = array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"),
  1158. $cnyunits = array("圆", "角", "分"),
  1159. $grees = array("拾", "佰", "仟", "万", "拾", "佰", "仟", "亿");
  1160. list($ns1, $ns2) = explode(".", $ns, 2);
  1161. $ns2 = array_filter(array($ns2[1], $ns2[0]));
  1162. $ret = array_merge($ns2, array(implode("", _cny_map_unit(str_split($ns1), $grees)), ""));
  1163. $ret = implode("", array_reverse(_cny_map_unit($ret, $cnyunits)));
  1164. return str_replace(array_keys($cnums), $cnums, $ret);
  1165. }
  1166. function _cny_map_unit($list, $units)
  1167. {
  1168. $ul = count($units);
  1169. $xs = array();
  1170. foreach (array_reverse($list) as $x) {
  1171. $l = count($xs);
  1172. if ($x != "0" || !($l % 4)) {
  1173. $n = ($x == '0' ? '' : $x) . ($units[($l - 1) % $ul]);
  1174. } else {
  1175. $n = is_numeric($xs[0][0]) ? $x : '';
  1176. }
  1177. array_unshift($xs, $n);
  1178. }
  1179. return $xs;
  1180. }
  1181. /**
  1182. * 根据类型获取上一类型时间戳数组
  1183. */
  1184. function getLstTimeByType($type = 'today')
  1185. {
  1186. switch ($type) {
  1187. case 'yesterday' :
  1188. $timeArr = Time::yesterday();
  1189. break;
  1190. case 'week' :
  1191. $timeArr = Time::week();
  1192. break;
  1193. case 'lastWeek' :
  1194. $timeArr = Time::lastWeek();
  1195. break;
  1196. case 'month' :
  1197. $timeArr = Time::month();
  1198. break;
  1199. case 'lastMonth' :
  1200. $timeArr = Time::lastMonth();
  1201. break;
  1202. case 'quarter' :
  1203. //本季度
  1204. $month = date('m');
  1205. if ($month == 1 || $month == 2 || $month == 3) {
  1206. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1207. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1208. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1209. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1210. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1211. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1212. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1213. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1214. } else {
  1215. $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
  1216. $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
  1217. }
  1218. $timeArr = array($daterange_start_time, $daterange_end_time);
  1219. break;
  1220. case 'lastQuarter' :
  1221. //上季度
  1222. $month = date('m');
  1223. if ($month == 1 || $month == 2 || $month == 3) {
  1224. $year = date('Y') - 1;
  1225. $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
  1226. $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
  1227. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1228. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1229. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1230. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1231. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1232. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1233. } else {
  1234. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1235. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1236. }
  1237. $timeArr = array($daterange_start_time, $daterange_end_time);
  1238. break;
  1239. case 'year' :
  1240. $timeArr = Time::year();
  1241. break;
  1242. case 'lastYear' :
  1243. $timeArr = Time::lastYear();
  1244. break;
  1245. default :
  1246. $timeArr = Time::today();
  1247. break;
  1248. }
  1249. return $timeArr;
  1250. }
  1251. /**
  1252. * 根据类型获取开始结束时间戳数组
  1253. * @param
  1254. */
  1255. function getTimeByType($type = 'today', $is_last = false)
  1256. {
  1257. $lastArr = [];
  1258. switch ($type) {
  1259. case 'yesterday' :
  1260. $timeArr = Time::yesterday();
  1261. $lastArr = Time::yesterday(1);
  1262. break;
  1263. case 'week' :
  1264. $timeArr = Time::week();
  1265. $lastArr = Time::lastWeek();
  1266. break;
  1267. case 'lastWeek' :
  1268. $timeArr = Time::lastWeek();
  1269. break;
  1270. case 'month' :
  1271. $timeArr = Time::month();
  1272. $lastArr = Time::lastMonth();
  1273. break;
  1274. case 'lastMonth' :
  1275. $timeArr = Time::lastMonth();
  1276. $lastArr = Time::lastMonth(1);
  1277. break;
  1278. case 'quarter' :
  1279. //本季度
  1280. $month = date('m');
  1281. if ($month == 1 || $month == 2 || $month == 3) {
  1282. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1283. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1284. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1285. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1286. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1287. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1288. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1289. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1290. } else {
  1291. $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
  1292. $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
  1293. }
  1294. //上季度
  1295. $month = date('m');
  1296. if ($month == 1 || $month == 2 || $month == 3) {
  1297. $year = date('Y') - 1;
  1298. $daterange_start_time_last_time = strtotime(date($year . '-10-01 00:00:00'));
  1299. $daterange_end_time_last_time = strtotime(date($year . '-12-31 23:59:59'));
  1300. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1301. $daterange_start_time_last_time = strtotime(date('Y-01-01 00:00:00'));
  1302. $daterange_end_time_last_time = strtotime(date("Y-03-31 23:59:59"));
  1303. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1304. $daterange_start_time_last_time = strtotime(date('Y-04-01 00:00:00'));
  1305. $daterange_end_time_last_time = strtotime(date("Y-06-30 23:59:59"));
  1306. } else {
  1307. $daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
  1308. $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
  1309. }
  1310. $timeArr = array($daterange_start_time, $daterange_end_time);
  1311. $lastArr = array($daterange_start_time_last_time, $daterange_end_time_last_time);
  1312. break;
  1313. case 'lastQuarter' :
  1314. //上季度
  1315. $month = date('m');
  1316. if ($month == 1 || $month == 2 || $month == 3) {
  1317. $year = date('Y') - 1;
  1318. $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
  1319. $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
  1320. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1321. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1322. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1323. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1324. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1325. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1326. } else {
  1327. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1328. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1329. }
  1330. $timeArr = array($daterange_start_time, $daterange_end_time);
  1331. $lastArr = array($daterange_start_time_last_time, $daterange_end_time_last_time);
  1332. break;
  1333. case 'year' :
  1334. $timeArr = Time::year();
  1335. $lastArr = Time::lastYear();
  1336. break;
  1337. case 'lastYear' :
  1338. $timeArr = Time::lastYear();
  1339. $lastArr = Time::lastYear(1);
  1340. break;
  1341. default :
  1342. $timeArr = Time::today();
  1343. $lastArr = Time::yesterday();
  1344. break;
  1345. }
  1346. if ($is_last) {
  1347. return $lastArr;
  1348. } else {
  1349. return $timeArr;
  1350. }
  1351. }
  1352. /**
  1353. * 服务器附件完整路径处理
  1354. * @param
  1355. */
  1356. function getFullPath($path)
  1357. {
  1358. if ($path) {
  1359. $protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https';
  1360. return $protocol . '://' . $_SERVER['HTTP_HOST'] . substr($_SERVER["SCRIPT_NAME"], 0, -10) . substr(str_replace(DS, '/', $path), 1);
  1361. } else {
  1362. return '';
  1363. }
  1364. }
  1365. /*取得文件后缀*/
  1366. function getExtension($filename)
  1367. {
  1368. $mytext = substr($filename, strrpos($filename, '.') + 1);
  1369. return $mytext;
  1370. }
  1371. /**
  1372. * 生成编号
  1373. * @param prefix 前缀
  1374. * @return
  1375. * @author Michael_xu
  1376. */
  1377. function prefixNumber($prefix, $number_id = 0, $str = 5)
  1378. {
  1379. return $prefixNumber = $prefix . str_pad($number_id, $str, 0, STR_PAD_LEFT); //填充字符串的左侧(将字符串填充为新的长度)
  1380. }
  1381. /**
  1382. * curl 模拟GET请求
  1383. * @author lee
  1384. ***/
  1385. function curl_get($url)
  1386. {
  1387. //初始化
  1388. $ch = curl_init();
  1389. //设置抓取的url
  1390. curl_setopt($ch, CURLOPT_URL, $url);
  1391. //设置获取的信息以文件流的形式返回,而不是直接输出。
  1392. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1393. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书
  1394. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // https请求 不验证hosts
  1395. //执行命令
  1396. $output = curl_exec($ch);
  1397. curl_close($ch); //释放curl句柄
  1398. return $output;
  1399. }
  1400. /**
  1401. * 地址坐标转换
  1402. * @param prefix 前缀
  1403. * @return
  1404. * @author Michael_xu
  1405. */
  1406. function get_lng_lat($address)
  1407. {
  1408. $map_ak = config('map_ak');
  1409. $url = "http://api.map.baidu.com/geocoder/v2/?address=$address&output=json&ak=$map_ak&callback=showLocation";
  1410. $ret_script = curl_get($url);
  1411. preg_match_all("/\{.*?\}}/is", $ret_script, $matches);
  1412. $ret_arr = json_decode($matches[0][0], true);
  1413. if ($ret_arr['status'] == 0) { //成功
  1414. $location['lng'] = $ret_arr['result']['location']['lng'];
  1415. $location['lat'] = $ret_arr['result']['location']['lat'];
  1416. return $location;
  1417. } else {
  1418. return false;
  1419. }
  1420. }
  1421. /**
  1422. * 导出数据为excel表格
  1423. * @param $data 一个二维数组,结构如同从数据库查出来的数组
  1424. * @param $title excel的第一行标题,一个数组,如果为空则没有标题
  1425. * @param $filename 下载的文件名
  1426. * @param exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
  1427. */
  1428. function exportexcel($data = array(), $title = array(), $filename = 'report')
  1429. {
  1430. header("Content-type:application/octet-stream");
  1431. header("Accept-Ranges:bytes");
  1432. header("Content-type:application/vnd.ms-excel");
  1433. header("Content-Disposition:attachment;filename=" . $filename . ".xls");
  1434. header("Pragma: no-cache");
  1435. header("Expires: 0");
  1436. //导出xls 开始
  1437. if (!empty($title)) {
  1438. foreach ($title as $k => $v) {
  1439. $title[$k] = iconv("UTF-8", "GB2312", $v);
  1440. }
  1441. $title = implode("\t", $title);
  1442. echo "$title\n";
  1443. }
  1444. if (!empty($data)) {
  1445. foreach ($data as $key => $val) {
  1446. foreach ($val as $ck => $cv) {
  1447. $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
  1448. }
  1449. $data[$key] = implode("\t", $data[$key]);
  1450. }
  1451. echo implode("\n", $data);
  1452. }
  1453. }
  1454. //根据数据库查询出来数组获取某个字段拼接字符串
  1455. function getFieldArray($array = array(), $field = '')
  1456. {
  1457. if (is_array($array) && $field) {
  1458. $ary = array();
  1459. foreach ($array as $value) {
  1460. $ary[] = $value[$field];
  1461. }
  1462. $str = implode(',', $ary);
  1463. return $str;
  1464. } else {
  1465. return false;
  1466. }
  1467. }
  1468. /**
  1469. * 检查该字段若必填,加上"*"
  1470. * @param is_null 是否为空 0否 1是
  1471. * @param name 字段名称
  1472. **/
  1473. function sign_required($is_null, $name)
  1474. {
  1475. if ($is_null == 1) {
  1476. return '*' . $name;
  1477. } else {
  1478. return $name;
  1479. }
  1480. }
  1481. /**
  1482. * [获取是否有管理员角色 adminGroupTypes]
  1483. * @param user_id 当前人ID
  1484. * @return
  1485. */
  1486. function adminGroupTypes($user_id)
  1487. {
  1488. $userModel = new UserModel();
  1489. $groupsArr = $userModel->get($user_id)->groups;
  1490. $groupids = [];
  1491. if ($groupsArr) {
  1492. foreach ($groupsArr as $key => $val) {
  1493. $groupids[] = $val['id'];
  1494. }
  1495. }
  1496. $types = db('admin_group')->where(['id' => ['in', $groupids]])->group('types')->column('types');
  1497. if ($user_id == 1) {
  1498. $types[] = 1;
  1499. }
  1500. return $types ?: [];
  1501. }
  1502. /**
  1503. * [权限数组]
  1504. * @param ruleIds 当前人权限id
  1505. * @return
  1506. */
  1507. function rulesListToArray($rulesList, $ruleIds = [])
  1508. {
  1509. $newList = [];
  1510. if (!is_array($rulesList)) {
  1511. return array();
  1512. } else {
  1513. foreach ($rulesList as $k => $v) {
  1514. if (!is_array($v['children'])) continue;
  1515. foreach ($v['children'] as $k1 => $v1) {
  1516. if (!is_array($v1['children'])) continue;
  1517. foreach ($v1['children'] as $k2 => $v2) {
  1518. $check = false;
  1519. if (in_array($v2['id'], $ruleIds)) {
  1520. $check = true;
  1521. }
  1522. $newList[$v['name']][$v1['name']][$v2['name']] = $check;
  1523. }
  1524. }
  1525. }
  1526. }
  1527. return $newList ?: [];
  1528. }
  1529. /**
  1530. * [获取下一审批信息 nextCheckData]
  1531. * @param user_id 审批申请人ID
  1532. * @param flow_id 审批流ID
  1533. * @param types 关联对象
  1534. * @param types_id 联对象ID
  1535. * @param order_id 审批排序ID
  1536. * @return
  1537. */
  1538. function nextCheckData($user_id, $flow_id, $types, $types_id, $order_id, $check_user_id)
  1539. {
  1540. $new_order_id = $order_id;
  1541. $max_order_id = db('admin_examine_step')->where(['flow_id' => $flow_id])->max('order_id'); //审批流最大排序ID
  1542. $examineStepModel = new \app\admin\model\ExamineStep();
  1543. $stepInfo = $examineStepModel->getStepByOrder($flow_id, $new_order_id); //审批步骤
  1544. $next_user_ids = [];
  1545. $is_end = 0; //审批结束
  1546. //固定流程(status 1负责人主管,2指定用户(任意一人),3指定用户(多人会签),4上一级审批人主管)
  1547. //当前步骤审批人user_id
  1548. $step_user_ids = $examineStepModel->getUserByStep($stepInfo['step_id'], $user_id);
  1549. if ($step_user_ids) {
  1550. if (!$order_id) {
  1551. //创建时使用
  1552. $sub_user_ids = stringToArray($step_user_ids);
  1553. } else {
  1554. if ($stepInfo['status'] == 3) {
  1555. //会签(并关系)
  1556. //当前步骤已审批user_id
  1557. $check_user_ids = $examineStepModel->getUserByCheck($types, $types_id, $new_order_id);
  1558. $user_ids[] = $check_user_id;
  1559. $check_user_ids = $check_user_ids ? array_merge($check_user_ids, $user_ids) : $user_ids;
  1560. //剩余审批人user_id
  1561. $sub_user_ids = $check_user_ids ? array_diff(explode(',', $step_user_ids), $check_user_ids) : $step_user_ids;
  1562. $sub_user_ids = array_unique(array_filter($sub_user_ids));
  1563. if (!$sub_user_ids) {
  1564. $is_end = 1;
  1565. }
  1566. } else {
  1567. $is_end = 1;
  1568. }
  1569. }
  1570. } else {
  1571. $is_end = 1;
  1572. }
  1573. if ($is_end == 1) {
  1574. $next_order_id = $new_order_id + 1;
  1575. } else {
  1576. $next_order_id = $new_order_id;
  1577. }
  1578. //当前审批步骤已结束
  1579. if ($is_end == 1) {
  1580. //当前审批流程是否结束
  1581. $stepInfo = $examineStepModel->getStepByOrder($flow_id, $next_order_id); //审批步骤
  1582. $next_step_user_ids = $examineStepModel->getUserByStep($stepInfo['step_id'], $user_id);
  1583. $next_user_ids = stringToArray($next_step_user_ids);
  1584. } else {
  1585. $next_user_ids = array_unique(array_filter($sub_user_ids));
  1586. }
  1587. if (!$next_user_ids && $next_order_id <= $max_order_id) {
  1588. $newRes = [];
  1589. $newRes = nextCheckData($user_id, $flow_id, $types, $types_id, $next_order_id, $check_user_id);
  1590. $next_user_ids = $newRes['next_user_ids'];
  1591. }
  1592. $data = [];
  1593. $data['order_id'] = ($next_order_id <= $max_order_id) ? $next_order_id : $max_order_id;
  1594. $data['next_user_ids'] = $next_user_ids ?: '';
  1595. return $data;
  1596. }
  1597. /**
  1598. * 解析获取php.ini 的upload_max_filesize(单位:byte)
  1599. * @param $dec int 小数位数
  1600. * @return float (单位:byte)
  1601. * */
  1602. function get_upload_max_filesize_byte($dec = 2)
  1603. {
  1604. $max_size = ini_get('upload_max_filesize');
  1605. preg_match('/(^[0-9\.]+)(\w+)/', $max_size, $info);
  1606. $size = $info[1];
  1607. $suffix = strtoupper($info[2]);
  1608. $a = array_flip(array("B", "KB", "MB", "GB", "TB", "PB"));
  1609. $b = array_flip(array("B", "K", "M", "G", "T", "P"));
  1610. $pos = $a[$suffix] && $a[$suffix] !== 0 ? $a[$suffix] : $b[$suffix];
  1611. return round($size * pow(1024, $pos), $dec);
  1612. }
  1613. /**
  1614. * 模拟post进行url请求
  1615. * @param string $url
  1616. * @param string $param
  1617. */
  1618. function curl_post($url = '', $post = array())
  1619. {
  1620. $curl = curl_init(); // 启动一个CURL会话
  1621. curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
  1622. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
  1623. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
  1624. curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
  1625. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
  1626. curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
  1627. curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
  1628. curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
  1629. curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
  1630. curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
  1631. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
  1632. $res = curl_exec($curl); // 执行操作
  1633. if (curl_errno($curl)) {
  1634. echo 'Errno' . curl_error($curl);//捕抓异常
  1635. }
  1636. curl_close($curl); // 关闭CURL会话
  1637. return $res; // 返回数据,json格式
  1638. }
  1639. /**
  1640. * 输出json字符串,用于接口调试
  1641. *
  1642. * @return void
  1643. * @author ymob
  1644. */
  1645. function vdd()
  1646. {
  1647. header('Content-Type: text/json; charset=utf-8');
  1648. $args = func_get_args();
  1649. foreach ($args as &$val) {
  1650. if ($val instanceof think\Model) {
  1651. $val = $val->getLastSql();
  1652. }
  1653. }
  1654. if (count($args) < 2) {
  1655. $args = array_shift($args);
  1656. }
  1657. die(json_encode($args));
  1658. }
  1659. /**
  1660. * 根据时间查询参数返回时间条件 (用于统计分析模块)
  1661. *
  1662. * @param array $where
  1663. * @param string $field
  1664. * @return void
  1665. * @author ymob
  1666. */
  1667. function getWhereTimeByParam(&$where, $field = 'create_time')
  1668. {
  1669. $param = request()->param();
  1670. if (empty($param['type']) && empty($param['start_time'])) {
  1671. $param['type'] = 'month';
  1672. }
  1673. if (!empty($param['start_time'])) {
  1674. $where[$field] = ['between', [$param['start_time'], $param['end_time']]];
  1675. } else {
  1676. $timeRange = getTimeByType($param['type']);
  1677. if ($timeRange) {
  1678. $where[$field] = ['between', [$timeRange[0], $timeRange[1]]];
  1679. }
  1680. }
  1681. }
  1682. /**
  1683. * 根据员工、部门查询参数返回员工、部门条件 (用于统计分析模块)
  1684. *
  1685. * @param array $where
  1686. * @param string $field
  1687. * @param string $m
  1688. * @param string $c
  1689. * @param string $a
  1690. * @return void
  1691. * @author ymob
  1692. */
  1693. function getWhereUserByParam(&$where, $field = 'owner_user_id', $m = '', $c = '', $a = '')
  1694. {
  1695. $param = request()->param();
  1696. $userModel = new UserModel();
  1697. $map_user_ids = [];
  1698. if ($param['user_id']) {
  1699. $map_user_ids = array($param['user_id']);
  1700. } elseif ($param['structure_id']) {
  1701. $map_user_ids = $userModel->getSubUserByStr($param['structure_id'], 2);
  1702. } else {
  1703. $map_user_ids = $userModel->getUserByPer($m, $c, $a);
  1704. $where[$field] = array('in', $map_user_ids);
  1705. return;
  1706. }
  1707. $perUserIds = $userModel->getUserByPer($m, $c, $a); //权限范围内userIds
  1708. $userIds = array_intersect($map_user_ids, $perUserIds); //数组交集
  1709. $where[$field] = array('in', $userIds);
  1710. }
  1711. /**
  1712. * 获取客户浏览器类型
  1713. */
  1714. function getBrowser()
  1715. {
  1716. $Browser = $_SERVER['HTTP_USER_AGENT'];
  1717. if (preg_match('/MSIE/i', $Browser)) {
  1718. $Browser = 'MSIE';
  1719. } elseif (preg_match('/Firefox/i', $Browser)) {
  1720. $Browser = 'Firefox';
  1721. } elseif (preg_match('/Chrome/i', $Browser)) {
  1722. $Browser = 'Chrome';
  1723. } elseif (preg_match('/Safari/i', $Browser)) {
  1724. $Browser = 'Safari';
  1725. } elseif (preg_match('/Opera/i', $Browser)) {
  1726. $Browser = 'Opera';
  1727. } else {
  1728. $Browser = 'Other';
  1729. }
  1730. return $Browser;
  1731. }
  1732. /**
  1733. * 获取客户端系统
  1734. */
  1735. function getOS()
  1736. {
  1737. $agent = $_SERVER['HTTP_USER_AGENT'];
  1738. if (preg_match('/win/i', $agent)) {
  1739. if (preg_match('/nt 6.1/i', $agent)) {
  1740. $OS = 'Windows 7';
  1741. } else if (preg_match('/nt 6.2/i', $agent)) {
  1742. $OS = 'Windows 8';
  1743. } else if (preg_match('/nt 10.0/i', $agent)) {
  1744. $OS = 'Windows 10';
  1745. } else {
  1746. $OS = 'Windows';
  1747. }
  1748. } elseif (preg_match('/mac/i', $agent)) {
  1749. $OS = 'MAC';
  1750. } elseif (preg_match('/linux/i', $agent)) {
  1751. $OS = 'Linux';
  1752. } elseif (preg_match('/unix/i', $agent)) {
  1753. $OS = 'Unix';
  1754. } elseif (preg_match('/bsd/i', $agent)) {
  1755. $OS = 'BSD';
  1756. } else {
  1757. $OS = 'Other';
  1758. }
  1759. return $OS;
  1760. }
  1761. /**
  1762. * 根据IP获取地址
  1763. */
  1764. function getAddress($ip)
  1765. {
  1766. $res = file_get_contents("http://ip.360.cn/IPQuery/ipquery?ip=" . $ip);
  1767. $res = json_decode($res, 1);
  1768. if ($res && $res['errno'] == 0) {
  1769. return explode("\t", $res['data'])[0];
  1770. } else {
  1771. return '';
  1772. }
  1773. }
  1774. /**
  1775. * 下载服务器文件
  1776. *
  1777. * @param string $file 文件路径
  1778. * @param string $name 下载名称
  1779. * @param boolean $del 下载后删除
  1780. * @return void
  1781. * @author Ymob
  1782. */
  1783. function download($file, $name = '', $del = false)
  1784. {
  1785. if (!file_exists($file)) {
  1786. return resultArray([
  1787. 'error' => '文件不存在',
  1788. ]);
  1789. }
  1790. // 仅允许下载 public 目录下文件
  1791. $res = strpos(realpath($file), realpath('./public'));
  1792. if ($res !== 0) {
  1793. return resultArray([
  1794. 'error' => '文件路径错误',
  1795. ]);
  1796. }
  1797. $fp = fopen($file, 'r');
  1798. $size = filesize($file);
  1799. //下载文件需要的头
  1800. header("Content-type: application/octet-stream");
  1801. header("Accept-Ranges: bytes");
  1802. header('ResponseType: blob');
  1803. header("Accept-Length: $size");
  1804. $file_name = $name != '' ? $name : pathinfo($file, PATHINFO_BASENAME);
  1805. // urlencode 处理中文乱码
  1806. header("Content-Disposition:attachment; filename=" . urlencode($file_name));
  1807. // 导出数据时 csv office Excel 需要添加bom头
  1808. if (pathinfo($file, PATHINFO_EXTENSION) == 'csv') {
  1809. echo "\xEF\xBB\xBF"; // UTF-8 BOM
  1810. }
  1811. $fileCount = 0;
  1812. $fileUnit = 1024;
  1813. while (!feof($fp) && $size - $fileCount > 0) {
  1814. $fileContent = fread($fp, $fileUnit);
  1815. echo $fileContent;
  1816. $fileCount += $fileUnit;
  1817. }
  1818. fclose($fp);
  1819. // 删除
  1820. if ($del) @unlink($file);
  1821. die();
  1822. }
  1823. /**
  1824. * 临时目录生成文件名,并返回绝对路径
  1825. *
  1826. * @param string $ext 文件类型后缀
  1827. * @param string $path 临时文件目录 默认 ./public/temp/
  1828. * @return string $file_path 文件名称绝对路径
  1829. * @author ymob
  1830. */
  1831. function tempFileName($ext = '')
  1832. {
  1833. // 临时目录
  1834. $path = TEMP_DIR . date('Ymd') . DS;
  1835. if (!file_exists($path)) {
  1836. mkdir($path, 0777, true);
  1837. }
  1838. $ext = trim($ext, '.');
  1839. do {
  1840. $temp_file = md5(time() . rand(1000, 9999));
  1841. $file_path = $path . $temp_file . '.' . $ext;
  1842. } while (file_exists($file_path));
  1843. return $file_path;
  1844. }
  1845. /**
  1846. * 递归删除目录
  1847. *
  1848. * @param string $dir
  1849. * @return void
  1850. * @author Ymob
  1851. */
  1852. function delDir($dir)
  1853. {
  1854. $dh = opendir($dir);
  1855. while ($file = readdir($dh)) {
  1856. if ($file != "." && $file != "..") {
  1857. $fullpath = $dir . "/" . $file;
  1858. if (!is_dir($fullpath)) {
  1859. @unlink($fullpath);
  1860. } else {
  1861. deldir($fullpath);
  1862. }
  1863. }
  1864. }
  1865. closedir($dh);
  1866. //删除当前文件夹:
  1867. @rmdir($dir);
  1868. }
  1869. /**
  1870. * 商业智能 查询缓存
  1871. *
  1872. * @param string $sql Sql语句
  1873. * @param int $bi_slow_query_time 慢查询时间(毫秒),默认读取Config(bi_slow_query_time)
  1874. * @return mixed
  1875. * @author Ymob
  1876. * @datetime 2019-11-21 17:36:50
  1877. */
  1878. function queryCache($sql = '', $bi_slow_query_time = null)
  1879. {
  1880. $key = 'BI_queryCache' . md5($sql);
  1881. $val = cache($key);
  1882. if (!$val) {
  1883. $start_time = microtime(true) * 1000;
  1884. $val = Db::query($sql);
  1885. $end_time = microtime(true) * 1000;
  1886. $slow_query = true;
  1887. // 是否使用系统默认设置-慢查询时间
  1888. if ($bi_slow_query_time === null) {
  1889. $bi_slow_query_time = config('bi_slow_query_time');
  1890. }
  1891. if ($bi_slow_query_time > 0) {
  1892. $slow_query = ($end_time - $start_time) > $bi_slow_query_time;
  1893. }
  1894. if ($slow_query && $val) {
  1895. cache($key, $val, config('bi_cache_time'));
  1896. }
  1897. }
  1898. return $val;
  1899. }
  1900. /**
  1901. * 图表时间范围处理,按月/天返回时间段数组
  1902. *
  1903. * @param int $start 开始时间(时间戳)
  1904. * @param int $end 结束时间(时间戳)
  1905. * @return array
  1906. * @author Ymob
  1907. * @datetime 2019-11-18 09:25:09
  1908. */
  1909. function getTimeArray($start = null, $end = null)
  1910. {
  1911. if ($start == null || $end == null) {
  1912. $param = request()->param();
  1913. switch ($param['type']) {
  1914. // 本年
  1915. case 'year':
  1916. $start = strtotime(date('Y-01-01'));
  1917. $end = strtotime('+1 year', $start) - 1;
  1918. break;
  1919. // 去年
  1920. case 'lastYear':
  1921. $start = strtotime(date(date('Y') - 1 . '-01-01'));
  1922. $end = strtotime('+1 year', $start) - 1;
  1923. break;
  1924. // 本季度、上季度
  1925. case 'quarter':
  1926. case 'lastQuarter':
  1927. $t = intval((date('m') - 1) / 3);
  1928. $start_y = ($t * 3) + 1;
  1929. $start = strtotime(date("Y-{$start_y}-01"));
  1930. if ($param['type'] == 'lastQuarter') { // 上季度
  1931. $start = strtotime('-3 month', $start);
  1932. }
  1933. $end = strtotime('+3 month', $start) - 1;
  1934. break;
  1935. // 本月、上月
  1936. case 'month':
  1937. case 'lastMonth':
  1938. $start = strtotime(date('Y-m-01'));
  1939. if ($param['type'] == 'lastMonth') {
  1940. $start = strtotime('-1 month', $start);
  1941. }
  1942. $end = strtotime('+1 month', $start) - 1;
  1943. break;
  1944. // 本周、上周
  1945. case 'week':
  1946. case 'lastWeek':
  1947. $start = strtotime('-' . (date('w') - 1) . 'day', strtotime(date('Y-m-d')));
  1948. if ($param['type'] == 'lastWeek') {
  1949. $start = strtotime('-7 day', $start);
  1950. }
  1951. $end = strtotime('+7 day', $start) - 1;
  1952. break;
  1953. // 今天、昨天
  1954. case 'today':
  1955. case 'yesterday':
  1956. $start = strtotime(date('Y-m-d'));
  1957. if ($param['type'] == 'yesterday') {
  1958. $start = strtotime('-1 day', $start);
  1959. }
  1960. $end = strtotime('+1 day', $start) - 1;
  1961. break;
  1962. default:
  1963. if ($param['start_time'] && $param['end_time']) {
  1964. $start = $param['start_time'];
  1965. $end = $param['end_time'];
  1966. } else {
  1967. // 本年
  1968. $start = strtotime(date('Y-01-01'));
  1969. $end = strtotime('+1 year', $start) - 1;
  1970. }
  1971. break;
  1972. }
  1973. }
  1974. $between = [$start, $end];
  1975. $list = [];
  1976. $len = ($end - $start) / 86400;
  1977. // 大于30天 按月统计、小于按天统计
  1978. if ($len > 31) {
  1979. $time_format = '%Y-%m';
  1980. while (true) {
  1981. $start = strtotime(date('Y-m-01', $start));
  1982. $item = [];
  1983. $item['type'] = date('Y-m', $start);
  1984. $item['start_time'] = $start;
  1985. $item['end_time'] = strtotime('+1 month', $start) - 1;
  1986. $list[] = $item;
  1987. if ($item['end_time'] >= $end) break;
  1988. $start = $item['end_time'] + 1;
  1989. }
  1990. } else {
  1991. $time_format = '%Y-%m-%d';
  1992. while (true) {
  1993. $item = [];
  1994. $item['type'] = date('Y-m-d', $start);
  1995. $item['start_time'] = $start;
  1996. $item['end_time'] = strtotime('+1 day', $start) - 1;
  1997. $list[] = $item;
  1998. if ($item['end_time'] >= $end) break;
  1999. $start = $item['end_time'] + 1;
  2000. }
  2001. }
  2002. return [
  2003. 'list' => $list, // 时间段列表
  2004. 'time_format' => $time_format, // 时间格式 mysql 格式化时间戳
  2005. 'between' => $between // 开始结束时间
  2006. ];
  2007. }
  2008. /**
  2009. * 打印程序执行时间
  2010. *
  2011. * @param integer $s
  2012. * @return void
  2013. * @author Ymob
  2014. * @datetime 2019-11-28 09:31:45
  2015. */
  2016. function tt($s = 0)
  2017. {
  2018. die((string)round(microtime(1) - ($s ?: THINK_START_TIME), 3));
  2019. }
  2020. /**
  2021. * 数据库备份
  2022. */
  2023. function DBBackup($file = '', $path = '')
  2024. {
  2025. $type = config('database.type');
  2026. $host = config('database.hostname');
  2027. $port = config('database.hostport');
  2028. $dbname = config('database.database');
  2029. $username = config('database.username');
  2030. $password = config('database.password');
  2031. $dsn = "{$type}:host={$host};dbname={$dbname};port={$port}";
  2032. if ($file == '') {
  2033. $save_path = dirname(APP_PATH) . DS . 'data' . DS . date('Ym') . DS;
  2034. if (!file_exists($save_path) && !mkdir($save_path, '0777', true)) {
  2035. return 'data目录无写入权限';
  2036. }
  2037. $file = $save_path . date('d_H_i') . '_db_backup' . '.sql';
  2038. }
  2039. if (file_exists($file)) {
  2040. return '数据库备份文件已存在(自动备份时间间隔需大于1分钟)。';
  2041. }
  2042. try {
  2043. $backup = new \com\Mysqldump($dsn, $username, $password);
  2044. $backup->start($file);
  2045. return true;
  2046. } catch (\Exception $e) {
  2047. return '备份失败,请手动备份。错误原因:' . $e->getMessage();
  2048. }
  2049. }
  2050. /**
  2051. * 根据ip获取地址
  2052. */
  2053. function getAddressById($data)
  2054. {
  2055. $ip = new IpLocation();
  2056. $ip_address = $ip->getlocation($data);
  2057. return $ip_address;
  2058. }
  2059. if (!function_exists('isSuperAdministrators')) {
  2060. /**
  2061. * 判断是否是超级管理员
  2062. *
  2063. * @param $userId
  2064. * @return bool
  2065. */
  2066. function isSuperAdministrators($userId)
  2067. {
  2068. $status = false;
  2069. $apiCommon = new \app\admin\controller\ApiCommon();
  2070. $userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
  2071. $data = db('admin_access')->where('user_id', $userId)->column('group_id');
  2072. if ($userId == 1 || in_array(1, $data)) {
  2073. $status = true;
  2074. }
  2075. return $status;
  2076. }
  2077. }
  2078. if (!function_exists('getFieldGrantData')) {
  2079. /**
  2080. * 获取自动授权数据
  2081. *
  2082. * @return array
  2083. */
  2084. function getFieldGrantData($userId)
  2085. {
  2086. $result = [];
  2087. $apiCommon = new \app\admin\controller\ApiCommon();
  2088. $userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
  2089. $grantData = Db::query("
  2090. SELECT
  2091. `grant`.`module`, `grant`.`column`, `grant`.`content`
  2092. FROM
  2093. `5kcrm_admin_access` AS `access`
  2094. LEFT JOIN
  2095. `5kcrm_admin_group` AS `group` ON `access`.`group_id` = `group`.`id`
  2096. LEFT JOIN
  2097. `5kcrm_admin_field_grant` AS `grant` ON `group`.`id` = `grant`.`role_id`
  2098. WHERE
  2099. `access`.`user_id` =
  2100. " . $userId);
  2101. # 存在多角色多授权的情况
  2102. foreach ($grantData AS $key => $value) {
  2103. $result[$value['module'] . '_' . $value['column']][] = !empty($value['content']) ? unserialize($value['content']) : [];
  2104. }
  2105. return $result;
  2106. }
  2107. }
  2108. if (!function_exists('getFieldGrantStatus')) {
  2109. /**
  2110. * 获取字段授权状态
  2111. *
  2112. * @param $field
  2113. * @param $grantData
  2114. * @return int[]
  2115. */
  2116. function getFieldGrantStatus($field, $grantData)
  2117. {
  2118. # 默认状态都是不能查看、不能编辑,通过配置来取最大权限。
  2119. $result = ['read' => 0, 'write' => 0];
  2120. foreach ($grantData AS $key => $value) {
  2121. # 对于不在权限控制之内的字段,将状态都改为1。
  2122. $fieldBool = false;
  2123. foreach ($value AS $ke => $va) {
  2124. if ($va['field'] == $field) {
  2125. $result['read'] = $va['read'] > $result['read'] ? $va['read'] : $result['read'];
  2126. $result['write'] = $va['write'] > $result['write'] ? $va['write'] : $result['write'];
  2127. $fieldBool = true;
  2128. }
  2129. }
  2130. if (!$fieldBool) {
  2131. $result['read'] = 1;
  2132. $result['write'] = 1;
  2133. }
  2134. }
  2135. return $result;
  2136. }
  2137. /**
  2138. * 仪表盘日志使用
  2139. * 根据类型获取开始结束时间戳数组
  2140. * @param
  2141. */
  2142. function ByDateTime($type = 'today')
  2143. {
  2144. switch ($type) {
  2145. case 'yesterday' :
  2146. $timeArr = DataTime::yesterday();
  2147. $timeArr['last_time'] = DataTime::yesterday(1);
  2148. break;
  2149. case 'week' :
  2150. $timeArr = DataTime::week();
  2151. $timeArr['last_time'] = DataTime::lastWeek(1);
  2152. break;
  2153. case 'lastWeek' :
  2154. $timeArr = DataTime::lastWeek();
  2155. $timeArr['last_time'] = DataTime::lastWeek(1);
  2156. break;
  2157. case 'month' :
  2158. $timeArr = DataTime::month();
  2159. $timeArr['last_time'] = DataTime::lastMonth(1);
  2160. break;
  2161. case 'lastMonth' :
  2162. $timeArr = DataTime::lastMonth();
  2163. $timeArr['last_time'] = DataTime::lastMonth(1);
  2164. break;
  2165. case 'quarter' :
  2166. //本季度
  2167. $month = date('m');
  2168. if ($month == 1 || $month == 2 || $month == 3) {
  2169. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  2170. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  2171. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2172. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  2173. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  2174. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2175. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  2176. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  2177. } else {
  2178. $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
  2179. $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
  2180. }
  2181. //上季度
  2182. $month = date('m');
  2183. if ($month == 1 || $month == 2 || $month == 3) {
  2184. $year = date('Y') - 1;
  2185. $daterange_start_time_last_time = strtotime(date($year . '-10-01 00:00:00'));
  2186. $daterange_end_time_last_time = strtotime(date($year . '-12-31 23:59:59'));
  2187. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2188. $daterange_start_time_last_time = strtotime(date('Y-01-01 00:00:00'));
  2189. $daterange_end_time_last_time = strtotime(date("Y-03-31 23:59:59"));
  2190. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2191. $daterange_start_time_last_time = strtotime(date('Y-04-01 00:00:00'));
  2192. $daterange_end_time_last_time = strtotime(date("Y-06-30 23:59:59"));
  2193. } else {
  2194. $daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
  2195. $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
  2196. }
  2197. $timeArr['last_time'] = array($daterange_start_time_last_time, $daterange_end_time_last_time);
  2198. $timeArr = array($daterange_start_time, $daterange_end_time);
  2199. break;
  2200. case 'lastQuarter' :
  2201. //上季度
  2202. $month = date('m');
  2203. if ($month == 1 || $month == 2 || $month == 3) {
  2204. $year = date('Y') - 1;
  2205. $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
  2206. $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
  2207. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2208. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  2209. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  2210. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2211. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  2212. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  2213. } else {
  2214. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  2215. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  2216. }
  2217. //上季度
  2218. $month = date('m');
  2219. if ($month == 1 || $month == 2 || $month == 3) {
  2220. $year = date('Y') - 2;
  2221. $daterange_start_time_last_time = strtotime(date($year . '-10-01 00:00:00'));
  2222. $daterange_end_time_last_time = strtotime(date($year . '-12-31 23:59:59'));
  2223. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2224. $daterange_start_time_last_time = strtotime(date('Y-01-01 00:00:00'));
  2225. $daterange_end_time_last_time = strtotime(date("Y-03-31 23:59:59"));
  2226. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2227. $daterange_start_time_last_time = strtotime(date('Y-04-01 00:00:00'));
  2228. $daterange_end_time_last_time = strtotime(date("Y-06-30 23:59:59"));
  2229. } else {
  2230. $daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
  2231. $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
  2232. }
  2233. $timeArr = array($daterange_start_time, $daterange_end_time);
  2234. $timeArr['last_time'] = array($daterange_start_time_last_time, $daterange_end_time_last_time);
  2235. break;
  2236. case 'year' :
  2237. $timeArr = DataTime::year();
  2238. $timeArr['last_time'] = DataTime::lastYear(1);
  2239. break;
  2240. case 'lastYear' :
  2241. $timeArr = DataTime::lastYear();
  2242. $timeArr['last_time'] = DataTime::lastYear(1);
  2243. break;
  2244. case 'recent60' :
  2245. $timeArr = DataTime::recent60();
  2246. break;
  2247. case 'recent30' :
  2248. $timeArr = DataTime::recent30();
  2249. break;
  2250. default :
  2251. $timeArr = DataTime::today();
  2252. $timeArr['last_time'] = DataTime::yesterday(1);
  2253. break;
  2254. }
  2255. return $timeArr;
  2256. }
  2257. }