12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381
  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. } elseif ($newFieldArr[$k]['form_type'] == 'single_user'){
  800. $new_value = $v ? db('admin_user')->where(['id' => $v])->value('realname') : '';
  801. $old_value = $v ? db('admin_user')->where(['id' => $oldData['owner_user_id']])->value('realname') : '';
  802. }elseif($newFieldArr[$k]['form_type'] == 'floatnumber'){
  803. $new_value = $v ? number_format($v,2) : '';
  804. }
  805. $message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
  806. }
  807. }
  808. if ($message) {
  809. $data = [];
  810. $data['user_id'] = $user_id;
  811. $data['create_time'] = time();
  812. $data['types'] = $types;
  813. $data['action_id'] = $action_id;
  814. $data['content'] = implode('.|.', $message);
  815. db('admin_action_record')->insert($data);
  816. # 数据操作日志
  817. db('admin_operation_log')->insert([
  818. 'user_id' => $user_id,
  819. 'client_ip' => request()->ip(),
  820. 'module' => $types,
  821. 'action_id' => $action_id,
  822. 'content' => implode('.|.', $message),
  823. 'create_time' => time()
  824. ]);
  825. }
  826. } elseif ($content) {
  827. $data = [];
  828. $data['user_id'] = $user_id;
  829. $data['create_time'] = time();
  830. $data['types'] = $types;
  831. $data['action_id'] = $action_id;
  832. $data['content'] = $content;
  833. db('admin_action_record')->insert($data);
  834. # 数据操作日志
  835. db('admin_operation_log')->insert([
  836. 'user_id' => $user_id,
  837. 'client_ip' => request()->ip(),
  838. 'module' => $types,
  839. 'action_id' => $action_id,
  840. 'content' => $content,
  841. 'create_time' => time()
  842. ]);
  843. }
  844. }
  845. /**
  846. * 截取字符串
  847. * @param $start 开始截取位置
  848. * @param $length 截取长度
  849. * @return
  850. * @author Michael_xu
  851. */
  852. function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
  853. {
  854. if (function_exists("mb_substr")) {
  855. $slice = mb_substr($str, $start, $length, $charset);
  856. } elseif (function_exists('iconv_substr')) {
  857. $slice = iconv_substr($str, $start, $length, $charset);
  858. if (false === $slice) {
  859. $slice = '';
  860. }
  861. } else {
  862. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  863. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  864. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  865. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  866. preg_match_all($re[$charset], $str, $match);
  867. $slice = join("", array_slice($match[0], $start, $length));
  868. }
  869. if (utf8_strlen($str) < $length) $suffix = false;
  870. return $suffix ? $slice . '...' : $slice;
  871. }
  872. function utf8_strlen($string = null)
  873. {
  874. preg_match_all("/./us", $string, $match);
  875. return count($match[0]);
  876. }
  877. /**
  878. * 合法性验证
  879. * @param client_sign 签名参数值,使用相同规则对提交参数进行加密验证
  880. * @return
  881. * @author Michael_xu
  882. */
  883. function checkVerify($saftCode = '5kcrm@')
  884. {
  885. $parmList = Request::instance()->post();
  886. $header = $request->header();
  887. $parmList['sessionId'] = $header['sessionId'];
  888. $authkey = $header['authKey'];
  889. $clientSign = $parmList['client_sign'];
  890. if ($clientSign) {
  891. unset($parmList['client_sign']);
  892. if (count($parmList) > 0) {
  893. // 对要签名参数按照签名格式组合
  894. foreach ($parmList as $key => $value) {
  895. if (isset($_POST[$key])) {
  896. $parame[$key] = $key . '=' . trim($_POST[$key]);
  897. } else {
  898. return false;
  899. }
  900. }
  901. ksort($parame); //参数排序
  902. $returnValue = implode("&", $parame); //拼接字符串
  903. if ($returnValue) {
  904. //base64加密
  905. $signCalc = base64_encode(hash_hmac("sha1", $returnValue, $saftCode . $authkey, $raw_output = false));
  906. // 检查参数签名是否一致
  907. if (trim($clientSign) != trim($signCalc)) {
  908. return false;
  909. } else {
  910. return true;
  911. }
  912. } else {
  913. return false;
  914. }
  915. } else {
  916. return false;
  917. }
  918. } else {
  919. //签名认证错误
  920. return false;
  921. }
  922. }
  923. /**
  924. * 数组转换字符串(以逗号隔开)
  925. * @param
  926. * @return
  927. * @author Michael_xu
  928. */
  929. function arrayToString($array)
  930. {
  931. if (!is_array($array)) {
  932. $data_arr[] = $array;
  933. } else {
  934. $data_arr = $array;
  935. }
  936. $data_arr = array_filter($data_arr); //数组去空
  937. $data_arr = array_unique($data_arr); //数组去重
  938. $data_arr = array_merge($data_arr);
  939. $string = $data_arr ? ',' . implode(',', $data_arr) . ',' : '';
  940. return $string ?: '';
  941. }
  942. /**
  943. * 字符串转换数组(以逗号隔开)
  944. * @param
  945. * @return
  946. * @author Michael_xu
  947. */
  948. function stringToArray($string)
  949. {
  950. if (is_array($string)) {
  951. $data_arr = array_unique(array_filter($string));
  952. } else {
  953. $data_arr = $string ? array_unique(array_filter(explode(',', $string))) : [];
  954. }
  955. $data_arr = $data_arr ? array_merge($data_arr) : [];
  956. return $data_arr ?: [];
  957. }
  958. /**
  959. * 根据时间戳获取星期几
  960. * @param $time 要转换的时间戳
  961. */
  962. function getTimeWeek($time, $i = 0)
  963. {
  964. $weekarray = array("日", "一", "二", "三", "四", "五", "六");
  965. $oneD = 24 * 60 * 60;
  966. return "星期" . $weekarray[date("w", $time + $oneD * $i)];
  967. }
  968. /**
  969. * 二维数组排序(选择)
  970. * @param $select 要进行排序的select结果集
  971. * @param $field 排序的字段
  972. * @param $order 排序方式1降序2升序
  973. */
  974. function sort_select($select = array(), $field, $order = 1)
  975. {
  976. $count = count($select);
  977. if ($order == 1) {
  978. for ($i = 0; $i < $count; $i++) {
  979. $k = $i;
  980. for ($j = $i; $j < $count; $j++) {
  981. if ($select[$k][$field] < $select[$j][$field]) {
  982. $k = $j;
  983. }
  984. }
  985. $temp = $select[$i];
  986. $select[$i] = $select[$k];
  987. $select[$k] = $temp;
  988. }
  989. return $select;
  990. } else {
  991. for ($i = 0; $i < $count; $i++) {
  992. $k = $i;
  993. for ($j = $i; $j < $count; $j++) {
  994. if ($select[$k][$field] > $select[$j][$field]) {
  995. $k = $j;
  996. }
  997. }
  998. $temp = $select[$i];
  999. $select[$i] = $select[$k];
  1000. $select[$k] = $temp;
  1001. }
  1002. return $select;
  1003. }
  1004. }
  1005. /**
  1006. * 将秒数转换为时间 (年、天、小时、分、秒)
  1007. * @param
  1008. */
  1009. function getTimeBySec($time)
  1010. {
  1011. if (is_numeric($time)) {
  1012. $value = array(
  1013. "years" => 0, "days" => 0, "hours" => 0,
  1014. "minutes" => 0, "seconds" => 0,
  1015. );
  1016. if ($time >= 31556926) {
  1017. $value["years"] = floor($time / 31556926);
  1018. $time = ($time % 31556926);
  1019. $t .= $value["years"] . "年";
  1020. }
  1021. if ($time >= 86400) {
  1022. $value["days"] = floor($time / 86400);
  1023. $time = ($time % 86400);
  1024. $t .= $value["days"] . "天";
  1025. }
  1026. if ($time >= 3600) {
  1027. $value["hours"] = floor($time / 3600);
  1028. $time = ($time % 3600);
  1029. $t .= $value["hours"] . "小时";
  1030. }
  1031. if ($time >= 60) {
  1032. $value["minutes"] = floor($time / 60);
  1033. $time = ($time % 60);
  1034. $t .= $value["minutes"] . "分钟";
  1035. }
  1036. if ($time < 60) {
  1037. $value["seconds"] = floor($time);
  1038. $t .= $value["seconds"] . "秒";
  1039. }
  1040. return $t;
  1041. } else {
  1042. return (bool)FALSE;
  1043. }
  1044. }
  1045. /*
  1046. *根据年月计算有几天
  1047. */
  1048. function getmonthByYM($param)
  1049. {
  1050. $month = $param['month'] ? $param['month'] : date('m', time());
  1051. $year = $param['year'] ? $param['year'] : date('Y', time());
  1052. if (in_array($month, array('1', '3', '5', '7', '8', '01', '03', '05', '07', '08', '10', '12'))) {
  1053. $days = '31';
  1054. } elseif ($month == 2) {
  1055. if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 !== 0)) {
  1056. //判断是否是闰年
  1057. $days = '29';
  1058. } else {
  1059. $days = '28';
  1060. }
  1061. } else {
  1062. $days = '30';
  1063. }
  1064. return $days;
  1065. }
  1066. /**
  1067. * 根据时间戳计算当月天数
  1068. * @param
  1069. */
  1070. function getmonthdays($time)
  1071. {
  1072. $month = date('m', $time);
  1073. $year = date('Y', $time);
  1074. if (in_array($month, array('1', '3', '5', '7', '8', '01', '03', '05', '07', '08', '10', '12'))) {
  1075. $days = '31';
  1076. } elseif ($month == 2) {
  1077. if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 !== 0)) {
  1078. //判断是否是闰年
  1079. $days = '29';
  1080. } else {
  1081. $days = '28';
  1082. }
  1083. } else {
  1084. $days = '30';
  1085. }
  1086. return $days;
  1087. }
  1088. /**
  1089. * 生成从开始时间到结束时间的日期数组
  1090. * @param type,默认时间戳格式
  1091. * @param type = 1 时,date格式
  1092. * @param type = 2 时,获取每日开始、结束时间
  1093. */
  1094. function dateList($start, $end, $type = 0)
  1095. {
  1096. if (!is_numeric($start) || !is_numeric($end) || ($end <= $start)) return '';
  1097. $i = 0;
  1098. //从开始日期到结束日期的每日时间戳数组
  1099. $d = array();
  1100. if ($type == 1) {
  1101. while ($start <= $end) {
  1102. $d[$i] = date('Y-m-d', $start);
  1103. $start = $start + 86400;
  1104. $i++;
  1105. }
  1106. } else {
  1107. while ($start <= $end) {
  1108. $d[$i] = $start;
  1109. $start = $start + 86400;
  1110. $i++;
  1111. }
  1112. }
  1113. if ($type == 2) {
  1114. $list = array();
  1115. foreach ($d as $k => $v) {
  1116. $list[$k] = getDateRange($v);
  1117. }
  1118. return $list;
  1119. } else {
  1120. return $d;
  1121. }
  1122. }
  1123. /**
  1124. * 获取指定日期开始时间与结束时间
  1125. */
  1126. function getDateRange($timestamp)
  1127. {
  1128. $ret = array();
  1129. $ret['sdate'] = strtotime(date('Y-m-d', $timestamp));
  1130. $ret['edate'] = strtotime(date('Y-m-d', $timestamp)) + 86400;
  1131. return $ret;
  1132. }
  1133. /**
  1134. * 生成从开始月份到结束月份的月份数组
  1135. * @param int $start 开始时间戳
  1136. * @param int $end 结束时间戳
  1137. */
  1138. function monthList($start, $end)
  1139. {
  1140. if (!is_numeric($start) || !is_numeric($end) || ($end <= $start)) return '';
  1141. $start = date('Y-m', $start);
  1142. $end = date('Y-m', $end);
  1143. //转为时间戳
  1144. $start = strtotime($start . '-01');
  1145. $end = strtotime($end . '-01');
  1146. $i = 0;
  1147. $d = array();
  1148. while ($start <= $end) {
  1149. //这里累加每个月的的总秒数 计算公式:上一月1号的时间戳秒数减去当前月的时间戳秒数
  1150. $d[$i] = $start;
  1151. $start += strtotime('+1 month', $start) - $start;
  1152. $i++;
  1153. }
  1154. return $d;
  1155. }
  1156. /**
  1157. * 人民币转大写
  1158. * @param
  1159. */
  1160. function cny($ns)
  1161. {
  1162. static $cnums = array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"),
  1163. $cnyunits = array("圆", "角", "分"),
  1164. $grees = array("拾", "佰", "仟", "万", "拾", "佰", "仟", "亿");
  1165. list($ns1, $ns2) = explode(".", $ns, 2);
  1166. $ns2 = array_filter(array($ns2[1], $ns2[0]));
  1167. $ret = array_merge($ns2, array(implode("", _cny_map_unit(str_split($ns1), $grees)), ""));
  1168. $ret = implode("", array_reverse(_cny_map_unit($ret, $cnyunits)));
  1169. return str_replace(array_keys($cnums), $cnums, $ret);
  1170. }
  1171. function _cny_map_unit($list, $units)
  1172. {
  1173. $ul = count($units);
  1174. $xs = array();
  1175. foreach (array_reverse($list) as $x) {
  1176. $l = count($xs);
  1177. if ($x != "0" || !($l % 4)) {
  1178. $n = ($x == '0' ? '' : $x) . ($units[($l - 1) % $ul]);
  1179. } else {
  1180. $n = is_numeric($xs[0][0]) ? $x : '';
  1181. }
  1182. array_unshift($xs, $n);
  1183. }
  1184. return $xs;
  1185. }
  1186. /**
  1187. * 根据类型获取上一类型时间戳数组
  1188. */
  1189. function getLstTimeByType($type = 'today')
  1190. {
  1191. switch ($type) {
  1192. case 'yesterday' :
  1193. $timeArr = Time::yesterday();
  1194. break;
  1195. case 'week' :
  1196. $timeArr = Time::week();
  1197. break;
  1198. case 'lastWeek' :
  1199. $timeArr = Time::lastWeek();
  1200. break;
  1201. case 'month' :
  1202. $timeArr = Time::month();
  1203. break;
  1204. case 'lastMonth' :
  1205. $timeArr = Time::lastMonth();
  1206. break;
  1207. case 'quarter' :
  1208. //本季度
  1209. $month = date('m');
  1210. if ($month == 1 || $month == 2 || $month == 3) {
  1211. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1212. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1213. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1214. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1215. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1216. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1217. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1218. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1219. } else {
  1220. $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
  1221. $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
  1222. }
  1223. $timeArr = array($daterange_start_time, $daterange_end_time);
  1224. break;
  1225. case 'lastQuarter' :
  1226. //上季度
  1227. $month = date('m');
  1228. if ($month == 1 || $month == 2 || $month == 3) {
  1229. $year = date('Y') - 1;
  1230. $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
  1231. $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
  1232. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1233. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1234. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1235. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1236. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1237. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1238. } else {
  1239. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1240. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1241. }
  1242. $timeArr = array($daterange_start_time, $daterange_end_time);
  1243. break;
  1244. case 'year' :
  1245. $timeArr = Time::year();
  1246. break;
  1247. case 'lastYear' :
  1248. $timeArr = Time::lastYear();
  1249. break;
  1250. default :
  1251. $timeArr = Time::today();
  1252. break;
  1253. }
  1254. return $timeArr;
  1255. }
  1256. /**
  1257. * 根据类型获取开始结束时间戳数组
  1258. * @param
  1259. */
  1260. function getTimeByType($type = 'today', $is_last = false)
  1261. {
  1262. $lastArr = [];
  1263. switch ($type) {
  1264. case 'yesterday' :
  1265. $timeArr = Time::yesterday();
  1266. $lastArr = Time::yesterday(1);
  1267. break;
  1268. case 'week' :
  1269. $timeArr = Time::week();
  1270. $lastArr = Time::lastWeek();
  1271. break;
  1272. case 'lastWeek' :
  1273. $timeArr = Time::lastWeek();
  1274. break;
  1275. case 'month' :
  1276. $timeArr = Time::month();
  1277. $lastArr = Time::lastMonth();
  1278. break;
  1279. case 'lastMonth' :
  1280. $timeArr = Time::lastMonth();
  1281. $lastArr = Time::lastMonth(1);
  1282. break;
  1283. case 'quarter' :
  1284. //本季度
  1285. $month = date('m');
  1286. if ($month == 1 || $month == 2 || $month == 3) {
  1287. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1288. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1289. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1290. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1291. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1292. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1293. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1294. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1295. } else {
  1296. $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
  1297. $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
  1298. }
  1299. //上季度
  1300. $month = date('m');
  1301. if ($month == 1 || $month == 2 || $month == 3) {
  1302. $year = date('Y') - 1;
  1303. $daterange_start_time_last_time = strtotime(date($year . '-10-01 00:00:00'));
  1304. $daterange_end_time_last_time = strtotime(date($year . '-12-31 23:59:59'));
  1305. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1306. $daterange_start_time_last_time = strtotime(date('Y-01-01 00:00:00'));
  1307. $daterange_end_time_last_time = strtotime(date("Y-03-31 23:59:59"));
  1308. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1309. $daterange_start_time_last_time = strtotime(date('Y-04-01 00:00:00'));
  1310. $daterange_end_time_last_time = strtotime(date("Y-06-30 23:59:59"));
  1311. } else {
  1312. $daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
  1313. $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
  1314. }
  1315. $timeArr = array($daterange_start_time, $daterange_end_time);
  1316. $lastArr = array($daterange_start_time_last_time, $daterange_end_time_last_time);
  1317. break;
  1318. case 'lastQuarter' :
  1319. //上季度
  1320. $month = date('m');
  1321. if ($month == 1 || $month == 2 || $month == 3) {
  1322. $year = date('Y') - 1;
  1323. $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
  1324. $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
  1325. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1326. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1327. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1328. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1329. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1330. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1331. } else {
  1332. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1333. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1334. }
  1335. $timeArr = array($daterange_start_time, $daterange_end_time);
  1336. $lastArr = array($daterange_start_time_last_time, $daterange_end_time_last_time);
  1337. break;
  1338. case 'year' :
  1339. $timeArr = Time::year();
  1340. $lastArr = Time::lastYear();
  1341. break;
  1342. case 'lastYear' :
  1343. $timeArr = Time::lastYear();
  1344. $lastArr = Time::lastYear(1);
  1345. break;
  1346. default :
  1347. $timeArr = Time::today();
  1348. $lastArr = Time::yesterday();
  1349. break;
  1350. }
  1351. if ($is_last) {
  1352. return $lastArr;
  1353. } else {
  1354. return $timeArr;
  1355. }
  1356. }
  1357. /**
  1358. * 服务器附件完整路径处理
  1359. * @param
  1360. */
  1361. function getFullPath($path)
  1362. {
  1363. if ($path) {
  1364. $protocol = strpos(strtolower($_SERVER['server_protocol']), 'https') === false ? 'http' : 'https';
  1365. return $protocol . '://' . $_SERVER['HTTP_HOST'] . substr($_SERVER["SCRIPT_NAME"], 0, -10) . substr(str_replace(DS, '/', $path), 1);
  1366. } else {
  1367. return '';
  1368. }
  1369. }
  1370. /*取得文件后缀*/
  1371. function getExtension($filename)
  1372. {
  1373. $mytext = substr($filename, strrpos($filename, '.') + 1);
  1374. return $mytext;
  1375. }
  1376. /**
  1377. * 生成编号
  1378. * @param prefix 前缀
  1379. * @return
  1380. * @author Michael_xu
  1381. */
  1382. function prefixNumber($prefix, $number_id = 0, $str = 5)
  1383. {
  1384. return $prefixNumber = $prefix . str_pad($number_id, $str, 0, STR_PAD_LEFT); //填充字符串的左侧(将字符串填充为新的长度)
  1385. }
  1386. /**
  1387. * curl 模拟GET请求
  1388. * @author lee
  1389. ***/
  1390. function curl_get($url)
  1391. {
  1392. //初始化
  1393. $ch = curl_init();
  1394. //设置抓取的url
  1395. curl_setopt($ch, CURLOPT_URL, $url);
  1396. //设置获取的信息以文件流的形式返回,而不是直接输出。
  1397. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1398. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书
  1399. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // https请求 不验证hosts
  1400. //执行命令
  1401. $output = curl_exec($ch);
  1402. curl_close($ch); //释放curl句柄
  1403. return $output;
  1404. }
  1405. /**
  1406. * 地址坐标转换
  1407. * @param prefix 前缀
  1408. * @return
  1409. * @author Michael_xu
  1410. */
  1411. function get_lng_lat($address)
  1412. {
  1413. $map_ak = config('map_ak');
  1414. $url = "http://api.map.baidu.com/geocoder/v2/?address=$address&output=json&ak=$map_ak&callback=showLocation";
  1415. $ret_script = curl_get($url);
  1416. preg_match_all("/\{.*?\}}/is", $ret_script, $matches);
  1417. $ret_arr = json_decode($matches[0][0], true);
  1418. if ($ret_arr['status'] == 0) { //成功
  1419. $location['lng'] = $ret_arr['result']['location']['lng'];
  1420. $location['lat'] = $ret_arr['result']['location']['lat'];
  1421. return $location;
  1422. } else {
  1423. return false;
  1424. }
  1425. }
  1426. /**
  1427. * 导出数据为excel表格
  1428. * @param $data 一个二维数组,结构如同从数据库查出来的数组
  1429. * @param $title excel的第一行标题,一个数组,如果为空则没有标题
  1430. * @param $filename 下载的文件名
  1431. * @param exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
  1432. */
  1433. function exportexcel($data = array(), $title = array(), $filename = 'report')
  1434. {
  1435. header("Content-type:application/octet-stream");
  1436. header("Accept-Ranges:bytes");
  1437. header("Content-type:application/vnd.ms-excel");
  1438. header("Content-Disposition:attachment;filename=" . $filename . ".xls");
  1439. header("Pragma: no-cache");
  1440. header("Expires: 0");
  1441. //导出xls 开始
  1442. if (!empty($title)) {
  1443. foreach ($title as $k => $v) {
  1444. $title[$k] = iconv("UTF-8", "GB2312", $v);
  1445. }
  1446. $title = implode("\t", $title);
  1447. echo "$title\n";
  1448. }
  1449. if (!empty($data)) {
  1450. foreach ($data as $key => $val) {
  1451. foreach ($val as $ck => $cv) {
  1452. $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
  1453. }
  1454. $data[$key] = implode("\t", $data[$key]);
  1455. }
  1456. echo implode("\n", $data);
  1457. }
  1458. }
  1459. //根据数据库查询出来数组获取某个字段拼接字符串
  1460. function getFieldArray($array = array(), $field = '')
  1461. {
  1462. if (is_array($array) && $field) {
  1463. $ary = array();
  1464. foreach ($array as $value) {
  1465. $ary[] = $value[$field];
  1466. }
  1467. $str = implode(',', $ary);
  1468. return $str;
  1469. } else {
  1470. return false;
  1471. }
  1472. }
  1473. /**
  1474. * 检查该字段若必填,加上"*"
  1475. * @param is_null 是否为空 0否 1是
  1476. * @param name 字段名称
  1477. **/
  1478. function sign_required($is_null, $name)
  1479. {
  1480. if ($is_null == 1) {
  1481. return '*' . $name;
  1482. } else {
  1483. return $name;
  1484. }
  1485. }
  1486. /**
  1487. * [获取是否有管理员角色 adminGroupTypes]
  1488. * @param user_id 当前人ID
  1489. * @return
  1490. */
  1491. function adminGroupTypes($user_id)
  1492. {
  1493. $userModel = new UserModel();
  1494. $groupsArr = $userModel->get($user_id)->groups;
  1495. $groupids = [];
  1496. if ($groupsArr) {
  1497. foreach ($groupsArr as $key => $val) {
  1498. $groupids[] = $val['id'];
  1499. }
  1500. }
  1501. $types = db('admin_group')->where(['id' => ['in', $groupids]])->group('types')->column('types');
  1502. if ($user_id == 1) {
  1503. $types[] = 1;
  1504. }
  1505. return $types ?: [];
  1506. }
  1507. /**
  1508. * [权限数组]
  1509. * @param ruleIds 当前人权限id
  1510. * @return
  1511. */
  1512. function rulesListToArray($rulesList, $ruleIds = [])
  1513. {
  1514. $newList = [];
  1515. if (!is_array($rulesList)) {
  1516. return array();
  1517. } else {
  1518. foreach ($rulesList as $k => $v) {
  1519. if (!is_array($v['children'])) continue;
  1520. foreach ($v['children'] as $k1 => $v1) {
  1521. if (!is_array($v1['children'])) continue;
  1522. foreach ($v1['children'] as $k2 => $v2) {
  1523. $check = false;
  1524. if (in_array($v2['id'], $ruleIds)) {
  1525. $check = true;
  1526. }
  1527. $newList[$v['name']][$v1['name']][$v2['name']] = $check;
  1528. }
  1529. }
  1530. }
  1531. }
  1532. return $newList ?: [];
  1533. }
  1534. /**
  1535. * [获取下一审批信息 nextCheckData]
  1536. * @param user_id 审批申请人ID
  1537. * @param flow_id 审批流ID
  1538. * @param types 关联对象
  1539. * @param types_id 联对象ID
  1540. * @param order_id 审批排序ID
  1541. * @return
  1542. */
  1543. function nextCheckData($user_id, $flow_id, $types, $types_id, $order_id, $check_user_id)
  1544. {
  1545. $new_order_id = $order_id;
  1546. $max_order_id = db('admin_examine_step')->where(['flow_id' => $flow_id])->max('order_id'); //审批流最大排序ID
  1547. $examineStepModel = new \app\admin\model\ExamineStep();
  1548. $stepInfo = $examineStepModel->getStepByOrder($flow_id, $new_order_id); //审批步骤
  1549. $next_user_ids = [];
  1550. $is_end = 0; //审批结束
  1551. //固定流程(status 1负责人主管,2指定用户(任意一人),3指定用户(多人会签),4上一级审批人主管)
  1552. //当前步骤审批人user_id
  1553. $step_user_ids = $examineStepModel->getUserByStep($stepInfo['step_id'], $user_id);
  1554. if ($step_user_ids) {
  1555. if (!$order_id) {
  1556. //创建时使用
  1557. $sub_user_ids = stringToArray($step_user_ids);
  1558. } else {
  1559. if ($stepInfo['status'] == 3) {
  1560. //会签(并关系)
  1561. //当前步骤已审批user_id
  1562. $check_user_ids = $examineStepModel->getUserByCheck($types, $types_id, $new_order_id);
  1563. $user_ids[] = $check_user_id;
  1564. $check_user_ids = $check_user_ids ? array_merge($check_user_ids, $user_ids) : $user_ids;
  1565. //剩余审批人user_id
  1566. $sub_user_ids = $check_user_ids ? array_diff(explode(',', $step_user_ids), $check_user_ids) : $step_user_ids;
  1567. $sub_user_ids = array_unique(array_filter($sub_user_ids));
  1568. if (!$sub_user_ids) {
  1569. $is_end = 1;
  1570. }
  1571. } else {
  1572. $is_end = 1;
  1573. }
  1574. }
  1575. } else {
  1576. $is_end = 1;
  1577. }
  1578. if ($is_end == 1) {
  1579. $next_order_id = $new_order_id + 1;
  1580. } else {
  1581. $next_order_id = $new_order_id;
  1582. }
  1583. //当前审批步骤已结束
  1584. if ($is_end == 1) {
  1585. //当前审批流程是否结束
  1586. $stepInfo = $examineStepModel->getStepByOrder($flow_id, $next_order_id); //审批步骤
  1587. $next_step_user_ids = $examineStepModel->getUserByStep($stepInfo['step_id'], $user_id);
  1588. $next_user_ids = stringToArray($next_step_user_ids);
  1589. } else {
  1590. $next_user_ids = array_unique(array_filter($sub_user_ids));
  1591. }
  1592. if (!$next_user_ids && $next_order_id <= $max_order_id) {
  1593. $newRes = [];
  1594. $newRes = nextCheckData($user_id, $flow_id, $types, $types_id, $next_order_id, $check_user_id);
  1595. $next_user_ids = $newRes['next_user_ids'];
  1596. }
  1597. $data = [];
  1598. $data['order_id'] = ($next_order_id <= $max_order_id) ? $next_order_id : $max_order_id;
  1599. $data['next_user_ids'] = $next_user_ids ?: '';
  1600. return $data;
  1601. }
  1602. /**
  1603. * 解析获取php.ini 的upload_max_filesize(单位:byte)
  1604. * @param $dec int 小数位数
  1605. * @return float (单位:byte)
  1606. * */
  1607. function get_upload_max_filesize_byte($dec = 2)
  1608. {
  1609. $max_size = ini_get('upload_max_filesize');
  1610. preg_match('/(^[0-9\.]+)(\w+)/', $max_size, $info);
  1611. $size = $info[1];
  1612. $suffix = strtoupper($info[2]);
  1613. $a = array_flip(array("B", "KB", "MB", "GB", "TB", "PB"));
  1614. $b = array_flip(array("B", "K", "M", "G", "T", "P"));
  1615. $pos = $a[$suffix] && $a[$suffix] !== 0 ? $a[$suffix] : $b[$suffix];
  1616. return round($size * pow(1024, $pos), $dec);
  1617. }
  1618. /**
  1619. * 模拟post进行url请求
  1620. * @param string $url
  1621. * @param string $param
  1622. */
  1623. function curl_post($url = '', $post = array())
  1624. {
  1625. $curl = curl_init(); // 启动一个CURL会话
  1626. curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
  1627. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
  1628. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
  1629. curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
  1630. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
  1631. curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
  1632. curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
  1633. curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
  1634. curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
  1635. curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
  1636. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
  1637. $res = curl_exec($curl); // 执行操作
  1638. if (curl_errno($curl)) {
  1639. echo 'Errno' . curl_error($curl);//捕抓异常
  1640. }
  1641. curl_close($curl); // 关闭CURL会话
  1642. return $res; // 返回数据,json格式
  1643. }
  1644. /**
  1645. * 输出json字符串,用于接口调试
  1646. *
  1647. * @return void
  1648. * @author ymob
  1649. */
  1650. function vdd()
  1651. {
  1652. header('Content-Type: text/json; charset=utf-8');
  1653. $args = func_get_args();
  1654. foreach ($args as &$val) {
  1655. if ($val instanceof think\Model) {
  1656. $val = $val->getLastSql();
  1657. }
  1658. }
  1659. if (count($args) < 2) {
  1660. $args = array_shift($args);
  1661. }
  1662. die(json_encode($args));
  1663. }
  1664. /**
  1665. * 根据时间查询参数返回时间条件 (用于统计分析模块)
  1666. *
  1667. * @param array $where
  1668. * @param string $field
  1669. * @return void
  1670. * @author ymob
  1671. */
  1672. function getWhereTimeByParam(&$where, $field = 'create_time')
  1673. {
  1674. $param = request()->param();
  1675. if (empty($param['type']) && empty($param['start_time'])) {
  1676. $param['type'] = 'month';
  1677. }
  1678. if (!empty($param['start_time'])) {
  1679. $where[$field] = ['between', [$param['start_time'], $param['end_time']]];
  1680. } else {
  1681. $timeRange = getTimeByType($param['type']);
  1682. if ($timeRange) {
  1683. $where[$field] = ['between', [$timeRange[0], $timeRange[1]]];
  1684. }
  1685. }
  1686. }
  1687. /**
  1688. * 根据员工、部门查询参数返回员工、部门条件 (用于统计分析模块)
  1689. *
  1690. * @param array $where
  1691. * @param string $field
  1692. * @param string $m
  1693. * @param string $c
  1694. * @param string $a
  1695. * @return void
  1696. * @author ymob
  1697. */
  1698. function getWhereUserByParam(&$where, $field = 'owner_user_id', $m = '', $c = '', $a = '')
  1699. {
  1700. $param = request()->param();
  1701. $userModel = new UserModel();
  1702. $map_user_ids = [];
  1703. if ($param['user_id']) {
  1704. $map_user_ids = array($param['user_id']);
  1705. } elseif ($param['structure_id']) {
  1706. $map_user_ids = $userModel->getSubUserByStr($param['structure_id'], 2);
  1707. } else {
  1708. $map_user_ids = $userModel->getUserByPer($m, $c, $a);
  1709. $where[$field] = array('in', $map_user_ids);
  1710. return;
  1711. }
  1712. $perUserIds = $userModel->getUserByPer($m, $c, $a); //权限范围内userIds
  1713. $userIds = array_intersect($map_user_ids, $perUserIds); //数组交集
  1714. $where[$field] = array('in', $userIds);
  1715. }
  1716. /**
  1717. * 获取客户浏览器类型
  1718. */
  1719. function getBrowser()
  1720. {
  1721. $Browser = $_SERVER['HTTP_USER_AGENT'];
  1722. if (preg_match('/MSIE/i', $Browser)) {
  1723. $Browser = 'MSIE';
  1724. } elseif (preg_match('/Firefox/i', $Browser)) {
  1725. $Browser = 'Firefox';
  1726. } elseif (preg_match('/Chrome/i', $Browser)) {
  1727. $Browser = 'Chrome';
  1728. } elseif (preg_match('/Safari/i', $Browser)) {
  1729. $Browser = 'Safari';
  1730. } elseif (preg_match('/Opera/i', $Browser)) {
  1731. $Browser = 'Opera';
  1732. } else {
  1733. $Browser = 'Other';
  1734. }
  1735. return $Browser;
  1736. }
  1737. /**
  1738. * 获取客户端系统
  1739. */
  1740. function getOS()
  1741. {
  1742. $agent = $_SERVER['HTTP_USER_AGENT'];
  1743. if (preg_match('/win/i', $agent)) {
  1744. if (preg_match('/nt 6.1/i', $agent)) {
  1745. $OS = 'Windows 7';
  1746. } else if (preg_match('/nt 6.2/i', $agent)) {
  1747. $OS = 'Windows 8';
  1748. } else if (preg_match('/nt 10.0/i', $agent)) {
  1749. $OS = 'Windows 10';
  1750. } else {
  1751. $OS = 'Windows';
  1752. }
  1753. } elseif (preg_match('/mac/i', $agent)) {
  1754. $OS = 'MAC';
  1755. } elseif (preg_match('/linux/i', $agent)) {
  1756. $OS = 'Linux';
  1757. } elseif (preg_match('/unix/i', $agent)) {
  1758. $OS = 'Unix';
  1759. } elseif (preg_match('/bsd/i', $agent)) {
  1760. $OS = 'BSD';
  1761. } else {
  1762. $OS = 'Other';
  1763. }
  1764. return $OS;
  1765. }
  1766. /**
  1767. * 根据IP获取地址
  1768. */
  1769. function getAddress($ip)
  1770. {
  1771. $res = file_get_contents("http://ip.360.cn/IPQuery/ipquery?ip=" . $ip);
  1772. $res = json_decode($res, 1);
  1773. if ($res && $res['errno'] == 0) {
  1774. return explode("\t", $res['data'])[0];
  1775. } else {
  1776. return '';
  1777. }
  1778. }
  1779. /**
  1780. * 下载服务器文件
  1781. *
  1782. * @param string $file 文件路径
  1783. * @param string $name 下载名称
  1784. * @param boolean $del 下载后删除
  1785. * @return void
  1786. * @author Ymob
  1787. */
  1788. function download($file, $name = '', $del = false)
  1789. {
  1790. if (!file_exists($file)) {
  1791. return resultArray([
  1792. 'error' => '文件不存在',
  1793. ]);
  1794. }
  1795. // 仅允许下载 public 目录下文件
  1796. $res = strpos(realpath($file), realpath('./public'));
  1797. if ($res !== 0) {
  1798. return resultArray([
  1799. 'error' => '文件路径错误',
  1800. ]);
  1801. }
  1802. $fp = fopen($file, 'r');
  1803. $size = filesize($file);
  1804. //下载文件需要的头
  1805. header("Content-type: application/octet-stream");
  1806. header("Accept-Ranges: bytes");
  1807. header('ResponseType: blob');
  1808. header("Accept-Length: $size");
  1809. $file_name = $name != '' ? $name : pathinfo($file, PATHINFO_BASENAME);
  1810. // urlencode 处理中文乱码
  1811. header("Content-Disposition:attachment; filename=" . urlencode($file_name));
  1812. // 导出数据时 csv office Excel 需要添加bom头
  1813. if (pathinfo($file, PATHINFO_EXTENSION) == 'csv') {
  1814. echo "\xEF\xBB\xBF"; // UTF-8 BOM
  1815. }
  1816. $fileCount = 0;
  1817. $fileUnit = 1024;
  1818. while (!feof($fp) && $size - $fileCount > 0) {
  1819. $fileContent = fread($fp, $fileUnit);
  1820. echo $fileContent;
  1821. $fileCount += $fileUnit;
  1822. }
  1823. fclose($fp);
  1824. // 删除
  1825. if ($del) @unlink($file);
  1826. die();
  1827. }
  1828. /**
  1829. * 临时目录生成文件名,并返回绝对路径
  1830. *
  1831. * @param string $ext 文件类型后缀
  1832. * @param string $path 临时文件目录 默认 ./public/temp/
  1833. * @return string $file_path 文件名称绝对路径
  1834. * @author ymob
  1835. */
  1836. function tempFileName($ext = '')
  1837. {
  1838. // 临时目录
  1839. $path = TEMP_DIR . date('Ymd') . DS;
  1840. if (!file_exists($path)) {
  1841. mkdir($path, 0777, true);
  1842. }
  1843. $ext = trim($ext, '.');
  1844. do {
  1845. $temp_file = md5(time() . rand(1000, 9999));
  1846. $file_path = $path . $temp_file . '.' . $ext;
  1847. } while (file_exists($file_path));
  1848. return $file_path;
  1849. }
  1850. /**
  1851. * 递归删除目录
  1852. *
  1853. * @param string $dir
  1854. * @return void
  1855. * @author Ymob
  1856. */
  1857. function delDir($dir)
  1858. {
  1859. $dh = opendir($dir);
  1860. while ($file = readdir($dh)) {
  1861. if ($file != "." && $file != "..") {
  1862. $fullpath = $dir . "/" . $file;
  1863. if (!is_dir($fullpath)) {
  1864. @unlink($fullpath);
  1865. } else {
  1866. deldir($fullpath);
  1867. }
  1868. }
  1869. }
  1870. closedir($dh);
  1871. //删除当前文件夹:
  1872. @rmdir($dir);
  1873. }
  1874. /**
  1875. * 商业智能 查询缓存
  1876. *
  1877. * @param string $sql Sql语句
  1878. * @param int $bi_slow_query_time 慢查询时间(毫秒),默认读取Config(bi_slow_query_time)
  1879. * @return mixed
  1880. * @author Ymob
  1881. * @datetime 2019-11-21 17:36:50
  1882. */
  1883. function queryCache($sql = '', $bi_slow_query_time = null)
  1884. {
  1885. $key = 'BI_queryCache' . md5($sql);
  1886. $val = cache($key);
  1887. if (!$val) {
  1888. $start_time = microtime(true) * 1000;
  1889. $val = Db::query($sql);
  1890. $end_time = microtime(true) * 1000;
  1891. $slow_query = true;
  1892. // 是否使用系统默认设置-慢查询时间
  1893. if ($bi_slow_query_time === null) {
  1894. $bi_slow_query_time = config('bi_slow_query_time');
  1895. }
  1896. if ($bi_slow_query_time > 0) {
  1897. $slow_query = ($end_time - $start_time) > $bi_slow_query_time;
  1898. }
  1899. if ($slow_query && $val) {
  1900. cache($key, $val, config('bi_cache_time'));
  1901. }
  1902. }
  1903. return $val;
  1904. }
  1905. /**
  1906. * 图表时间范围处理,按月/天返回时间段数组
  1907. *
  1908. * @param int $start 开始时间(时间戳)
  1909. * @param int $end 结束时间(时间戳)
  1910. * @return array
  1911. * @author Ymob
  1912. * @datetime 2019-11-18 09:25:09
  1913. */
  1914. function getTimeArray($start = null, $end = null)
  1915. {
  1916. if ($start == null || $end == null) {
  1917. $param = request()->param();
  1918. switch ($param['type']) {
  1919. // 本年
  1920. case 'year':
  1921. $start = strtotime(date('Y-01-01'));
  1922. $end = strtotime('+1 year', $start) - 1;
  1923. break;
  1924. // 去年
  1925. case 'lastYear':
  1926. $start = strtotime(date(date('Y') - 1 . '-01-01'));
  1927. $end = strtotime('+1 year', $start) - 1;
  1928. break;
  1929. // 本季度、上季度
  1930. case 'quarter':
  1931. case 'lastQuarter':
  1932. $t = intval((date('m') - 1) / 3);
  1933. $start_y = ($t * 3) + 1;
  1934. $start = strtotime(date("Y-{$start_y}-01"));
  1935. if ($param['type'] == 'lastQuarter') { // 上季度
  1936. $start = strtotime('-3 month', $start);
  1937. }
  1938. $end = strtotime('+3 month', $start) - 1;
  1939. break;
  1940. // 本月、上月
  1941. case 'month':
  1942. case 'lastMonth':
  1943. $start = strtotime(date('Y-m-01'));
  1944. if ($param['type'] == 'lastMonth') {
  1945. $start = strtotime('-1 month', $start);
  1946. }
  1947. $end = strtotime('+1 month', $start) - 1;
  1948. break;
  1949. // 本周、上周
  1950. case 'week':
  1951. case 'lastWeek':
  1952. $start = strtotime('-' . (date('w') - 1) . 'day', strtotime(date('Y-m-d')));
  1953. if ($param['type'] == 'lastWeek') {
  1954. $start = strtotime('-7 day', $start);
  1955. }
  1956. $end = strtotime('+7 day', $start) - 1;
  1957. break;
  1958. // 今天、昨天
  1959. case 'today':
  1960. case 'yesterday':
  1961. $start = strtotime(date('Y-m-d'));
  1962. if ($param['type'] == 'yesterday') {
  1963. $start = strtotime('-1 day', $start);
  1964. }
  1965. $end = strtotime('+1 day', $start) - 1;
  1966. break;
  1967. default:
  1968. if ($param['start_time'] && $param['end_time']) {
  1969. $start = $param['start_time'];
  1970. $end = $param['end_time'];
  1971. } else {
  1972. // 本年
  1973. $start = strtotime(date('Y-01-01'));
  1974. $end = strtotime('+1 year', $start) - 1;
  1975. }
  1976. break;
  1977. }
  1978. }
  1979. $between = [$start, $end];
  1980. $list = [];
  1981. $len = ($end - $start) / 86400;
  1982. // 大于30天 按月统计、小于按天统计
  1983. if ($len > 31) {
  1984. $time_format = '%Y-%m';
  1985. while (true) {
  1986. $start = strtotime(date('Y-m-01', $start));
  1987. $item = [];
  1988. $item['type'] = date('Y-m', $start);
  1989. $item['start_time'] = $start;
  1990. $item['end_time'] = strtotime('+1 month', $start) - 1;
  1991. $list[] = $item;
  1992. if ($item['end_time'] >= $end) break;
  1993. $start = $item['end_time'] + 1;
  1994. }
  1995. } else {
  1996. $time_format = '%Y-%m-%d';
  1997. while (true) {
  1998. $item = [];
  1999. $item['type'] = date('Y-m-d', $start);
  2000. $item['start_time'] = $start;
  2001. $item['end_time'] = strtotime('+1 day', $start) - 1;
  2002. $list[] = $item;
  2003. if ($item['end_time'] >= $end) break;
  2004. $start = $item['end_time'] + 1;
  2005. }
  2006. }
  2007. return [
  2008. 'list' => $list, // 时间段列表
  2009. 'time_format' => $time_format, // 时间格式 mysql 格式化时间戳
  2010. 'between' => $between // 开始结束时间
  2011. ];
  2012. }
  2013. /**
  2014. * 打印程序执行时间
  2015. *
  2016. * @param integer $s
  2017. * @return void
  2018. * @author Ymob
  2019. * @datetime 2019-11-28 09:31:45
  2020. */
  2021. function tt($s = 0)
  2022. {
  2023. die((string)round(microtime(1) - ($s ?: THINK_START_TIME), 3));
  2024. }
  2025. /**
  2026. * 数据库备份
  2027. */
  2028. function DBBackup($file = '', $path = '')
  2029. {
  2030. $type = config('database.type');
  2031. $host = config('database.hostname');
  2032. $port = config('database.hostport');
  2033. $dbname = config('database.database');
  2034. $username = config('database.username');
  2035. $password = config('database.password');
  2036. $dsn = "{$type}:host={$host};dbname={$dbname};port={$port}";
  2037. if ($file == '') {
  2038. $save_path = dirname(APP_PATH) . DS . 'data' . DS . date('Ym') . DS;
  2039. if (!file_exists($save_path) && !mkdir($save_path, '0777', true)) {
  2040. return 'data目录无写入权限';
  2041. }
  2042. $file = $save_path . date('d_H_i') . '_db_backup' . '.sql';
  2043. }
  2044. if (file_exists($file)) {
  2045. return '数据库备份文件已存在(自动备份时间间隔需大于1分钟)。';
  2046. }
  2047. try {
  2048. $backup = new \com\Mysqldump($dsn, $username, $password);
  2049. $backup->start($file);
  2050. return true;
  2051. } catch (\Exception $e) {
  2052. return '备份失败,请手动备份。错误原因:' . $e->getMessage();
  2053. }
  2054. }
  2055. /**
  2056. * 根据ip获取地址
  2057. */
  2058. function getAddressById($data)
  2059. {
  2060. $ip = new IpLocation();
  2061. $ip_address = $ip->getlocation($data);
  2062. return $ip_address;
  2063. }
  2064. if (!function_exists('isSuperAdministrators')) {
  2065. /**
  2066. * 判断是否是超级管理员
  2067. *
  2068. * @param $userId
  2069. * @return bool
  2070. */
  2071. function isSuperAdministrators($userId)
  2072. {
  2073. $status = false;
  2074. $apiCommon = new \app\admin\controller\ApiCommon();
  2075. $userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
  2076. $data = db('admin_access')->where('user_id', $userId)->column('group_id');
  2077. if ($userId == 1 || in_array(1, $data)) {
  2078. $status = true;
  2079. }
  2080. return $status;
  2081. }
  2082. }
  2083. if (!function_exists('getFieldGrantData')) {
  2084. /**
  2085. * 获取自动授权数据
  2086. *
  2087. * @return array
  2088. */
  2089. function getFieldGrantData($userId)
  2090. {
  2091. $result = [];
  2092. $apiCommon = new \app\admin\controller\ApiCommon();
  2093. $userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
  2094. $grantData = Db::query("
  2095. SELECT
  2096. `grant`.`module`, `grant`.`column`, `grant`.`content`
  2097. FROM
  2098. `5kcrm_admin_access` AS `access`
  2099. LEFT JOIN
  2100. `5kcrm_admin_group` AS `group` ON `access`.`group_id` = `group`.`id`
  2101. LEFT JOIN
  2102. `5kcrm_admin_field_grant` AS `grant` ON `group`.`id` = `grant`.`role_id`
  2103. WHERE
  2104. `access`.`user_id` =
  2105. " . $userId);
  2106. # 存在多角色多授权的情况
  2107. foreach ($grantData AS $key => $value) {
  2108. $result[$value['module'] . '_' . $value['column']][] = !empty($value['content']) ? unserialize($value['content']) : [];
  2109. }
  2110. return $result;
  2111. }
  2112. }
  2113. if (!function_exists('getFieldGrantStatus')) {
  2114. /**
  2115. * 获取字段授权状态
  2116. *
  2117. * @param $field
  2118. * @param $grantData
  2119. * @return int[]
  2120. */
  2121. function getFieldGrantStatus($field, $grantData)
  2122. {
  2123. # 默认状态都是不能查看、不能编辑,通过配置来取最大权限。
  2124. $result = ['read' => 0, 'write' => 0];
  2125. foreach ($grantData AS $key => $value) {
  2126. # 对于不在权限控制之内的字段,将状态都改为1。
  2127. $fieldBool = false;
  2128. foreach ($value AS $ke => $va) {
  2129. if ($va['field'] == $field) {
  2130. $result['read'] = $va['read'] > $result['read'] ? $va['read'] : $result['read'];
  2131. $result['write'] = $va['write'] > $result['write'] ? $va['write'] : $result['write'];
  2132. $fieldBool = true;
  2133. }
  2134. }
  2135. if (!$fieldBool) {
  2136. $result['read'] = 1;
  2137. $result['write'] = 1;
  2138. }
  2139. }
  2140. return $result;
  2141. }
  2142. /**
  2143. * 仪表盘日志使用
  2144. * 根据类型获取开始结束时间戳数组
  2145. * @param
  2146. */
  2147. function ByDateTime($type = 'today')
  2148. {
  2149. switch ($type) {
  2150. case 'yesterday' :
  2151. $timeArr = DataTime::yesterday();
  2152. $timeArr['last_time'] = DataTime::yesterday(1);
  2153. break;
  2154. case 'week' :
  2155. $timeArr = DataTime::week();
  2156. $timeArr['last_time'] = DataTime::lastWeek(1);
  2157. break;
  2158. case 'lastWeek' :
  2159. $timeArr = DataTime::lastWeek();
  2160. $timeArr['last_time'] = DataTime::lastWeek(1);
  2161. break;
  2162. case 'month' :
  2163. $timeArr = DataTime::month();
  2164. $timeArr['last_time'] = DataTime::lastMonth(1);
  2165. break;
  2166. case 'lastMonth' :
  2167. $timeArr = DataTime::lastMonth();
  2168. $timeArr['last_time'] = DataTime::lastMonth(1);
  2169. break;
  2170. case 'quarter' :
  2171. //本季度
  2172. $month = date('m');
  2173. if ($month == 1 || $month == 2 || $month == 3) {
  2174. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  2175. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  2176. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2177. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  2178. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  2179. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2180. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  2181. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  2182. } else {
  2183. $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
  2184. $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
  2185. }
  2186. //上季度
  2187. $month = date('m');
  2188. if ($month == 1 || $month == 2 || $month == 3) {
  2189. $year = date('Y') - 1;
  2190. $daterange_start_time_last_time = strtotime(date($year . '-10-01 00:00:00'));
  2191. $daterange_end_time_last_time = strtotime(date($year . '-12-31 23:59:59'));
  2192. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2193. $daterange_start_time_last_time = strtotime(date('Y-01-01 00:00:00'));
  2194. $daterange_end_time_last_time = strtotime(date("Y-03-31 23:59:59"));
  2195. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2196. $daterange_start_time_last_time = strtotime(date('Y-04-01 00:00:00'));
  2197. $daterange_end_time_last_time = strtotime(date("Y-06-30 23:59:59"));
  2198. } else {
  2199. $daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
  2200. $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
  2201. }
  2202. $timeArr['last_time'] = array($daterange_start_time_last_time, $daterange_end_time_last_time);
  2203. $timeArr = array($daterange_start_time, $daterange_end_time);
  2204. break;
  2205. case 'lastQuarter' :
  2206. //上季度
  2207. $month = date('m');
  2208. if ($month == 1 || $month == 2 || $month == 3) {
  2209. $year = date('Y') - 1;
  2210. $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
  2211. $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
  2212. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2213. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  2214. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  2215. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2216. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  2217. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  2218. } else {
  2219. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  2220. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  2221. }
  2222. //上季度
  2223. $month = date('m');
  2224. if ($month == 1 || $month == 2 || $month == 3) {
  2225. $year = date('Y') - 2;
  2226. $daterange_start_time_last_time = strtotime(date($year . '-10-01 00:00:00'));
  2227. $daterange_end_time_last_time = strtotime(date($year . '-12-31 23:59:59'));
  2228. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2229. $daterange_start_time_last_time = strtotime(date('Y-01-01 00:00:00'));
  2230. $daterange_end_time_last_time = strtotime(date("Y-03-31 23:59:59"));
  2231. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2232. $daterange_start_time_last_time = strtotime(date('Y-04-01 00:00:00'));
  2233. $daterange_end_time_last_time = strtotime(date("Y-06-30 23:59:59"));
  2234. } else {
  2235. $daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
  2236. $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
  2237. }
  2238. $timeArr = array($daterange_start_time, $daterange_end_time);
  2239. $timeArr['last_time'] = array($daterange_start_time_last_time, $daterange_end_time_last_time);
  2240. break;
  2241. case 'year' :
  2242. $timeArr = DataTime::year();
  2243. $timeArr['last_time'] = DataTime::lastYear(1);
  2244. break;
  2245. case 'lastYear' :
  2246. $timeArr = DataTime::lastYear();
  2247. $timeArr['last_time'] = DataTime::lastYear(1);
  2248. break;
  2249. case 'recent60' :
  2250. $timeArr = DataTime::recent60();
  2251. break;
  2252. case 'recent30' :
  2253. $timeArr = DataTime::recent30();
  2254. break;
  2255. default :
  2256. $timeArr = DataTime::today();
  2257. $timeArr['last_time'] = DataTime::yesterday(1);
  2258. break;
  2259. }
  2260. return $timeArr;
  2261. }
  2262. }