123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180
  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 $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. # 自定义字段的user team_id(非自定义字段)
  161. if ($v['form_type'] == 'user' && in_array($k, ['team_id'])) {
  162. // ro_user_id rw_user_id
  163. if ($v['condition'] == 'in') {
  164. return "(" . $c . 'ro_user_id' . " like ',%" . $v['value'] . "OR " . $c . 'rw_user_id' . " like ',%" . $v['value'] . ")";
  165. } elseif ($v['condition'] == 'not in') {
  166. return "(" . $c . $k . " not like ',%" . $v['value'][0] . "%,' OR " . $c . $k . " is null)";
  167. } elseif ($v['condition'] == 'isNull') {
  168. return "(" . $c . 'ro_user_id' . "eq" . $v['value'] . "OR " . $c . 'rw_user_id' . " eq" . $v['value'] . ")";
  169. } elseif ($v['condition'] == 'isNotNull') {
  170. return "(" . $c . 'ro_user_id' . "neq" . $v['value'] . "OR " . $c . 'rw_user_id' . " neq" . $v['value'] . ")";
  171. }
  172. }
  173. # 自定义字段的user、structure类型
  174. if (($v['form_type'] == 'user' && !in_array($k, ['create_user_id', 'owner_user_id'])) || $v['form_type'] == 'structure') {
  175. if ($v['condition'] == 'is') $v['condition'] = 'contains';
  176. if ($v['condition'] == 'isNot') {
  177. return "(" . $c . $k . " not like ',%" . $v['value'][0] . "%,' OR " . $c . $k . " is null)";
  178. }
  179. }
  180. # 处理多选字段的精确搜索
  181. if ($v['form_type'] == 'checkbox' && !empty($v['value'])) {
  182. if ($v['condition'] == 'is' && count($v['value']) == 1) $v['value'][0] = ',' . $v['value'][0] . ',';
  183. if ($v['condition'] == 'is' && count($v['value']) > 1) {
  184. $checkboxLike = '';
  185. foreach ($v['value'] as $kk => $vv) {
  186. $checkboxLike .= $c . $k . " like " . "',%" . $vv . "%,' AND ";
  187. }
  188. return "(" . $checkboxLike . "LENGTH(" . $c . $k . ") = LENGTH('" . arrayToString($v['value']) . "'))";
  189. }
  190. }
  191. if ($types == 'contract' && !empty($v['value'])) {
  192. switch ($k) {
  193. case 'business_id' :
  194. $k = 'name';
  195. $c = 'business.';
  196. break;
  197. case 'contacts_id' :
  198. $contactsIds = [];
  199. foreach ($v['value'] as $kk => $vv) {
  200. $contactsIdArray = db('crm_contacts')->whereLike('name', '%' . $vv . '%')->column('contacts_id');
  201. foreach ($contactsIdArray as $kkk => $vvv) {
  202. $contactsIds[] = $vvv;
  203. }
  204. }
  205. $v['value'] = array_unique($contactsIds);
  206. break;
  207. }
  208. }
  209. if ($types == 'receivables' && $v['name'] == '合同编号' && !empty($v['value'])) {
  210. $k = 'num';
  211. $c = 'contract.';
  212. }
  213. if ($types == 'receivables' && $k == 'plan_id' && !empty($v['value'])) {
  214. $planIds = [];
  215. foreach ($v['value'] as $kk => $vv) {
  216. $planIdArray = db('crm_receivables_plan')->whereLike('num', '%' . $vv . '%')->column('plan_id');
  217. foreach ($planIdArray as $kkk => $vvv) {
  218. $planIds[] = $vvv;
  219. }
  220. }
  221. $v['value'] = array_unique($planIds);
  222. }
  223. if ($types == 'invoice' && $v['type'] == 'invoice_status' && !empty($v['value'])) {
  224. foreach ($v['value'] as $kk => $vv) {
  225. if ($vv == '已开票') $v['value'][$kk] = 1;
  226. if ($vv == '未开票') $v['value'][$kk] = 0;
  227. }
  228. }
  229. if ($types == 'visit' && $v['type'] == 'contract_name' && !empty($v['value'])) {
  230. $k = 'num';
  231. $c = 'contract.';
  232. }
  233. if ($types == 'visit' && $v['type'] == 'contacts_name' && !empty($v['value'])) {
  234. $k = 'name';
  235. $c = 'contacts.';
  236. }
  237. if ($k == 'check_status' && is_array($v) && in_array($v['value'][0], $checkStatusList) && !empty($v['value'])) {
  238. $v['value'] = $checkStatusArray[$v['value'][0]] ?: '0';
  239. }
  240. if (is_array($v)) {
  241. if ($v['state']) {
  242. $address_where[] = '%' . $v['state'] . '%';
  243. if ($v['city']) {
  244. $address_where[] = '%' . $v['city'] . '%';
  245. if ($v['area']) {
  246. $address_where[] = '%' . $v['area'] . '%';
  247. }
  248. }
  249. if ($v['condition'] == 'not_contain') {
  250. $where[$c . $k] = ['notlike', $address_where, 'OR'];
  251. } else {
  252. $where[$c . $k] = ['like', $address_where, 'AND'];
  253. }
  254. } elseif (!empty($v['value']['state'])) {
  255. $addressWhere[] = '%' . $v['value']['state'] . '%';
  256. if (!empty($v['value']['city'])) $addressWhere[] = '%' . $v['value']['city'] . '%';
  257. if (!empty($v['value']['area'])) $addressWhere[] = '%' . $v['value']['area'] . '%';
  258. if ($v['condition'] == 'is') {
  259. $where[$c . $k] = ['like', $addressWhere, 'AND'];
  260. } else {
  261. $where[$c . $k] = ['notlike', $addressWhere, 'OR'];
  262. }
  263. } elseif (!empty($v['start']) || !empty($v['end'])) {
  264. if ($v['start'] && $v['end']) {
  265. $where[$c . $k] = ['between', [$v['start'], $v['end']]];
  266. } elseif ($v['start']) {
  267. $where[$c . $k] = ['egt', $v['start']];
  268. } else {
  269. $where[$c . $k] = ['elt', $v['end']];
  270. }
  271. } elseif (!empty($v['start_date']) || !empty($v['end_date'])) {
  272. if ($v['start_date'] && $v['end_date']) {
  273. $where[$c . $k] = ['between', [$v['start_date'], $v['end_date']]];
  274. } elseif ($v['start_date']) {
  275. $where[$c . $k] = ['egt', $v['start_date']];
  276. } else {
  277. $where[$c . $k] = ['elt', $v['end_date']];
  278. }
  279. } elseif (!empty($v['value']) || $v['value'] === '0') {
  280. if (in_array($k, $check_field_arr)) {
  281. $where[$c . $k] = field($v['value'], 'contains');
  282. } else {
  283. if ($v['condition'] == 'isNot' || $v['condition'] == 'notContains') {
  284. $where[$c . $k] = [field($v['value'], $v['condition'], $k), ['null'], 'or'];
  285. } else {
  286. $where[$c . $k] = field($v['value'], $v['condition'], $k);
  287. }
  288. }
  289. } elseif (in_array($v['condition'], ['isNull', 'isNotNull', 'in'])) {
  290. $where[$c . $k] = field($v['value'], $v['condition']);
  291. } else {
  292. $where[$c . $k] = $v;
  293. }
  294. } elseif (!empty($v)) {
  295. $where[$c . $k] = field($v);
  296. } else {
  297. $where[$c . $k] = $v;
  298. }
  299. }
  300. }
  301. # 商机阶段为赢单、输单、无效的值保存在is_end中,将status_id改为is_end;
  302. if (!empty($where['business.status_id']) && in_array($where['business.status_id'][1], [1, 2, 3])) {
  303. $where['business.is_end'] = $where['business.status_id'];
  304. unset($where['business.status_id']);
  305. }
  306. return $where ?: [];
  307. }
  308. /**
  309. * 高级筛选
  310. *
  311. * @param array $param 搜索参数
  312. * @param string $m 模块:crm log work ...
  313. * @param string $c 栏目:leads customer ...
  314. * @param string $a 方法:index save ...
  315. * @return array
  316. * @since 2021-05-20
  317. * @author fanqi
  318. */
  319. function advancedQuery($param, $m = '', $c = '', $a = '')
  320. {
  321. // 结果数据
  322. $result = [];
  323. // 原始前缀
  324. $prefix = $c . '.';
  325. // 等于(时间段)类型
  326. $betweenType = [
  327. 'year', 'lastYear', 'nextYear', 'firstHalfYear', 'nextHalfYear', 'quarter', 'lastQuarter',
  328. 'nextQuarter', 'month', 'lastMonth', 'nextMonth', 'week', 'lastWeek', 'nextWeek', 'today',
  329. 'yesterday', 'tomorrow', 'previous7day', 'previous30day', 'future7day', 'future30day'
  330. ];
  331. foreach ($param as $key => $value) {
  332. // 过滤不能参与搜索的字段类型
  333. if (!empty($value['form_type']) && in_array($value['form_type'], ['file', 'handwriting_sign', 'desc_text', 'detail_table', 'date_interval'])) continue;
  334. // 初始化前缀
  335. $c = $prefix;
  336. // 清除空格
  337. if (isset($value['condition'])) $value['condition'] = trim($value['condition']);
  338. // 处理表前缀和字段名称
  339. list($c, $key) = advancedQueryParam($c, $key, $value['name']);
  340. if ($key == 'check_status' && !is_array($value)) $result[$c . $key] = $value;
  341. if ($key == 'status_id' && !is_array($value)) $result[$c . $key] = $value;
  342. if ($key == 'customer_id' && !is_array($value)) $result['customer.' . $key] = $value;
  343. if ($key == 'contract_id' && !is_array($value)) $result['contract.' . $key] = $value;
  344. if ($key == 'business_id' && !is_array($value)) $result['business.' . $key] = $value;
  345. // 仪表盘参数
  346. if (!empty($value['value'][0]) && empty($value['condition'])) {
  347. $value['condition'] = 'is';
  348. $value['form_type'] = 'user';
  349. }
  350. if (!empty($value['start']) && !empty($value['end'])) {
  351. $value['value'][0] = date('Y-m-d H:i:s', $value['start']);
  352. $value['value'][1] = date('Y-m-d H:i:s', $value['end']);
  353. $value['form_type'] = 'datetime';
  354. $value['condition'] = 'between';
  355. }
  356. if ($key == 'check_status' && !is_array($value)) {
  357. unset($value);
  358. $value['value'][0] = '审核通过';
  359. $value['form_type'] = 'check_status';
  360. $value['name'] = '审核状态';
  361. $value['type'] = 'check_status';
  362. $value['condition'] = 'is';
  363. }
  364. // 代办事项
  365. if (isset($value) && !isset($value['condition']) && !isset($value['value']) && !isset($value['form_type'])) {
  366. $result[$c . $key] = is_array($value) ? $value : ['in', $value];
  367. continue;
  368. }
  369. // 等于(时间段)类型筛选
  370. if (!empty($value['value'][0]) && in_array($value['value'][0], $betweenType)) {
  371. $value = advancedQueryHandleDate($value);
  372. }
  373. // 创建人、负责人
  374. if (in_array($key, ['create_user_id', 'owner_user_id'])) {
  375. if($value['condition'] == 'contains'){
  376. $result[$c . $key] = ['in', $value['value']];
  377. }else if ($value['condition'] == 'notContains') {
  378. $result[$c . $key] = ['not in', $value['value']];
  379. }else if ($value['condition'] == 'isNull') {
  380. $result[$c . $key] = ['eq', ''];
  381. }else if ($value['condition'] == 'isNotNull') {
  382. $result[$c . $key] = ['neq', ''];
  383. }
  384. }
  385. // 模块、审核状态、成交状态、产品分类、单行文本、多行文本、网址、手机、邮箱、下拉框、布尔值、多选、定位、创建人、负责人
  386. if (isset($value['form_type']) && in_array($value['form_type'], ['module', 'check_status', 'deal_status', 'category', 'text', 'textarea', 'mobile', 'email', 'select', 'boolean_value', 'checkbox', 'location', 'website','user',])) {
  387. $result[$c . $key] = advancedQueryFormatForCommon($value['value'], $value['condition'], $value['form_type'], $key);
  388. }
  389. // 日期、日期时间、数字、货币、百分数、下次联系时间
  390. if (isset($value['form_type']) && in_array($value['form_type'], ['date', 'datetime', 'number', 'floatnumber', 'percent', 'next_time'])) {
  391. $result[$c . $key] = advancedQueryFormatForDate($value);
  392. }
  393. // 地址(固定字段)、地址(自定义字段)
  394. if (isset($value['form_type']) && in_array($value['form_type'], ['map_address', 'position'])) {
  395. $result[$c . $key] = advancedQueryFormatForAddress($value['value'], $value['form_type']);
  396. }
  397. // 人员、部门
  398. if (isset($value['form_type']) && in_array($value['form_type'], ['user', 'structure', 'single_user']) && !in_array($key, ['create_user_id', 'owner_user_id']) && $value['type'] != 'team_id') {
  399. if ($value['type'] == 'owner_structure') { # 所属部门
  400. $userIds = db('admin_user')->whereIn('structure_id', implode(',', $value['value']))->column('id');
  401. $result[$c . 'owner_user_id'] = ['in', $userIds];
  402. } else {
  403. $result[$c . $key] = advancedQueryFormatForPersonnel($value['value'], $value['condition']);
  404. }
  405. }
  406. // 商机状态组
  407. if (isset($value['form_type']) && $value['form_type'] == 'business_type') {
  408. if (!empty($value['type_id'])) $result[$c . 'type_id'] = ['eq', $value['type_id']];
  409. if (!empty($value['status_id']) && in_array($value['status_id'], [1, 2, 3])) $result[$c . 'is_end'] = ['eq', $value['status_id']];
  410. if (!empty($value['status_id']) && !in_array($value['status_id'], [1, 2, 3])) $result[$c . 'status_id'] = ['eq', $value['status_id']];
  411. }
  412. // 回款计划
  413. if (isset($value['form_type']) && $value['form_type'] == 'receivables_plan' && !empty($value['value'])) {
  414. $result[$c . 'plan_id'] = advancedQueryFormatForPlan($value['value']);
  415. }
  416. }
  417. return $result;
  418. }
  419. /**
  420. * 处理高级筛选查询前缀、字段名称
  421. *
  422. * @param string $prefix 表前缀
  423. * @param string $field 字段名
  424. * @param string $name 字段中文名
  425. * @return array
  426. * @since 2021-05-22
  427. * @author fanqi
  428. */
  429. function advancedQueryParam($prefix, $field, $name)
  430. {
  431. // 要变更的前缀
  432. $prefixChange = [
  433. 'customer_name' => 'customer.',
  434. 'contacts_name' => 'contacts.',
  435. 'business_name' => 'business.',
  436. 'contract_name' => 'contract.',
  437. 'business_id' => 'business.',
  438. 'contacts_id' => 'contacts.'
  439. ];
  440. // 处理客户名称、联系人名称、商机名称、合同名称字段
  441. if (in_array($field, ['customer_name', 'contacts_name', 'business_name', 'contract_name']) && $name != '合同编号') {
  442. $prefix = $prefixChange[$field];
  443. $field = 'name';
  444. }
  445. // 处理合同下的商机ID、客户ID字段
  446. if ($prefix == 'contract.' && in_array($field, ['business_id', 'contacts_id'])) {
  447. $prefix = $prefixChange[$field];
  448. $field = 'name';
  449. }
  450. // 处理回款、回访下的合同编号
  451. if (in_array($prefix, ['receivables.', 'visit.']) && $name == '合同编号') {
  452. $prefix = 'contract.';
  453. $field = 'num';
  454. }
  455. // 处理回访下的联系人
  456. if ($prefix == 'visit.' && $field == 'contacts_id') {
  457. $prefix = 'contacts.';
  458. $field = 'name';
  459. }
  460. return [$prefix, $field];
  461. }
  462. /**
  463. * 回款计划查询条件
  464. *
  465. * @param array $data 搜索参数
  466. * @return array
  467. * @since 2021-05-22
  468. * @author fanqi
  469. */
  470. function advancedQueryFormatForPlan($data)
  471. {
  472. $result = [];
  473. $planIds = db('crm_receivables_plan')->whereIn('num', $data)->column('plan_id');
  474. if (!empty($planIds)) $result = ['in', $planIds];
  475. return $result;
  476. }
  477. /**
  478. * 地址(固定字段)、地址(自定义字段)查询条件
  479. *
  480. * @param array $data 搜索参数
  481. * @param string $formType 字段类型
  482. * @return array
  483. * @since 2021-05-21
  484. * @author fanqi
  485. */
  486. function advancedQueryFormatForAddress($data, $formType)
  487. {
  488. if ($formType == 'map_address') $data = implode(chr(10), $data);
  489. if ($formType == 'position') {
  490. $data = array_filter(array_column($data[0], 'name'));
  491. $data = implode(',', $data);
  492. }
  493. return ['like', '%' . trim($data) . '%'];
  494. }
  495. /**
  496. * 人员、部门、回访人查询条件
  497. *
  498. * @param array $data 查询参数
  499. * @param string $condition 查询条件
  500. * @return array
  501. */
  502. function advancedQueryFormatForPersonnel($data, $condition)
  503. {
  504. // 处理查询条件
  505. if ($condition == 'is') $condition = 'contains';
  506. if ($condition == 'isNot') $condition = 'notContains';
  507. // 处理查询参数
  508. if (in_array($condition, ['contains', 'notContains'])) {
  509. array_walk($data, function ($value, $key) use (&$data) {
  510. $data[$key] = '%,' . $value . ',%';
  511. });
  512. }
  513. // 搜索条件
  514. return advancedQueryWhere($condition, $data);
  515. }
  516. /**
  517. * 日期、日期时间、数字、货币、百分数查询条件
  518. *
  519. * @param array $data 搜索参数、类型、条件
  520. * @return array
  521. * @since 2021-05-20
  522. * @author fanqi
  523. */
  524. function advancedQueryFormatForDate($data)
  525. {
  526. # 转换日期时间类型格式
  527. if (in_array($data['form_type'], ['datetime', 'next_time']) && !empty($data['value'][0])) $data['value'][0] = strtotime($data['value'][0]);
  528. if (in_array($data['form_type'], ['datetime', 'next_time']) && !empty($data['value'][1])) $data['value'][1] = strtotime($data['value'][1]);
  529. return advancedQueryWhere($data['condition'], count($data['value']) == 2 ? $data['value'] : $data['value'][0]);
  530. }
  531. /**
  532. * 模块、审核状态、成交状态、产品分类、单行文本、多行文本、网址、手机、邮箱、下拉框、布尔值、多选、定位、创建人、负责人
  533. *
  534. * @param array $data 要查询的数据
  535. * @param string $condition 查询方式
  536. * @param string $formType 字段类型
  537. * @return array
  538. * @since 2021-05-20
  539. * @author fanqi
  540. */
  541. function advancedQueryFormatForCommon($data, $condition, $formType, $key)
  542. {
  543. // 处理查询方式
  544. if (in_array($formType, ['checkbox']) && $condition == 'is') $condition = 'contains';
  545. if (in_array($formType, ['checkbox']) && $condition == 'isNot') $condition = 'notContains';
  546. // 处理查询参数
  547. if(in_array($condition, ['contains', 'notContains']) && in_array($key,['create_user_id','owner_user_id'])){
  548. $data = advancedQueryDataUserform($data, $condition);
  549. }elseif (in_array($condition, ['contains', 'notContains', 'startWith', 'endWith'])){
  550. $data = advancedQueryDataTransform($data, $condition);
  551. }
  552. // 处理回访形式
  553. if (in_array($key, ['shape', 'satisfaction'])) {
  554. array_walk($data, function ($value, $key) use (&$data) {
  555. $data[$key] = $value . "\r";
  556. });
  557. }
  558. // 处理审核状态
  559. if ($formType == 'check_status') {
  560. $data[0] = str_replace('待审核', 0, $data[0]);
  561. $data[0] = str_replace('审核中', 1, $data[0]);
  562. $data[0] = str_replace('审核通过', 2, $data[0]);
  563. $data[0] = str_replace('审核失败', 3, $data[0]);
  564. $data[0] = str_replace('已撤回', 4, $data[0]);
  565. $data[0] = str_replace('未提交', 5, $data[0]);
  566. $data[0] = str_replace('已作废', 6, $data[0]);
  567. }
  568. return advancedQueryWhere($condition, $data,$key);
  569. }
  570. /**
  571. * 设置搜索条件
  572. *
  573. * @param string $condition 查询方式
  574. * @param string|array $data 查询数据
  575. * @return array
  576. * @since 2021-05-22
  577. * @author fanqi
  578. */
  579. function advancedQueryWhere($condition, $data, $key='')
  580. {
  581. $result = [];
  582. // NULL(0)不存在、IS(1)等于、IS_NOT(2)不等于、CONTAINS(3)包含、NOT_CONTAINS(4)不包含、IS_NULL(5)为空、IS_NOT_NULL(6)不为空
  583. // GT(7)大于、EGT(8)大于等于、LT(9)小于、ELT(10)小于等于、ID(11)通过id、PREFIX(12) 前缀匹配、SUFFIX(13) 后缀匹配、RANGE(14) 数字区间
  584. if ($condition == "in") $result = ['in', $data]; // 等于
  585. if ($condition == 'is') $result = ['in', $data]; // 等于
  586. if ($condition == 'isNot') $result = ['notin', $data]; // 不等于
  587. if ($condition == 'contains') $result = ['like', $data, 'OR']; // 包含
  588. if ($condition == 'notContains') $result = ['notlike', $data, 'AND']; // 不包含
  589. if ($condition == 'startWith') $result = ['like', $data, 'OR']; // 开始于
  590. if ($condition == 'endWith') $result = ['like', $data, 'OR']; // 结束于
  591. if ($condition == 'gt') $result = ['gt', $data]; // 大于
  592. if ($condition == 'lt') $result = ['lt', $data]; // 小于
  593. if ($condition == 'egt') $result = ['egt', $data]; // 大于等于
  594. if ($condition == 'elt') $result = ['elt', $data]; // 小于等于
  595. if ($condition == 'between') $result = ['between', $data]; // 处于某个时间段
  596. if ($condition == 'range') $result = ['between', $data]; // 处于某个时间段
  597. if ($condition == 'isNull') $result = [['eq', ''], ['null'], 'OR']; // 为空
  598. if ($condition == 'isNotNull') $result = [['neq', ''], ['not null'], 'AND']; // 不为空
  599. if ($condition == 'contains' && in_array($key,['create_user_id','owner_user_id'])) $result = ['in', $data]; // 暂定为创建人 负责人 包含
  600. if ($condition == 'notContains' && in_array($key,['create_user_id','owner_user_id'])) $result = ['notin', $data]; // 暂定为创建人 负责人不包含
  601. return $result;
  602. }
  603. /**
  604. * 处理要查询的数据
  605. *
  606. * @param array $data 要查询的数据
  607. * @param string $condition 查询方式
  608. * @return mixed
  609. * @since 2021-05-20
  610. * @author fanqi
  611. */
  612. function advancedQueryDataTransform($data, $condition)
  613. {
  614. if (in_array($condition, ['contains', 'notContains'])) {
  615. array_walk($data, function ($value, $key) use (&$data) {
  616. $data[$key] = '%' . $value . '%';
  617. });
  618. }
  619. if ($condition == 'startWith') {
  620. array_walk($data, function ($value, $key) use (&$data) {
  621. $data[$key] = $value . '%';
  622. });
  623. }
  624. if ($condition == 'endWith') {
  625. array_walk($data, function ($value, $key) use (&$data) {
  626. $data[$key] = '%' . $value;
  627. });
  628. }
  629. return $data;
  630. }
  631. /**
  632. * 处理要查询的数据 包含不包含条件 数据为数字专用
  633. *
  634. * @param array $data 要查询的数据
  635. * @param string $condition 查询方式
  636. * @return mixed
  637. * @author: alvin guogaobo
  638. * @version: 11.1.0
  639. * Date: 2021/9/2 14:44
  640. */
  641. function advancedQueryDataUserform($data, $condition){
  642. if (in_array($condition, ['contains', 'notContains'])) {
  643. array_walk($data, function ($value, $key) use (&$data) {
  644. $data[$key] = $value;
  645. });
  646. }
  647. return $data;
  648. }
  649. /**
  650. * 等于(时间段)数据处理
  651. *
  652. * @param $data
  653. * @return array
  654. * @since 2021-06-11
  655. * @author fanqi
  656. */
  657. function advancedQueryHandleDate($data)
  658. {
  659. // 本年度
  660. if ($data['value'][0] == 'year') {
  661. $arrTime = DataTime::year();
  662. $data['value'][0] = date('Y-m-d 00:00:00', $arrTime[0]);
  663. $data['value'][1] = date('Y-m-d 23:59:59', $arrTime[1]);
  664. }
  665. // 上一年度
  666. if ($data['value'][0] == 'lastYear') {
  667. $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-1 year'));
  668. $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 year'));
  669. }
  670. // 下一年度
  671. if ($data['value'][0] == 'nextYear') {
  672. $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 year'));
  673. $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+1 year'));
  674. }
  675. // 上半年
  676. if ($data['value'][0] == 'firstHalfYear') {
  677. $data['value'][0] = date('Y-01-01 00:00:00');
  678. $data['value'][1] = date('Y-06-30 23:59:59');
  679. }
  680. // 下半年
  681. if ($data['value'][0] == 'nextHalfYear') {
  682. $data['value'][0] = date('Y-07-01 00:00:00');
  683. $data['value'][1] = date('Y-12-31 23:59:59');
  684. }
  685. // 本季度
  686. if ($data['value'][0] == 'quarter') {
  687. $season = ceil((date('n')) / 3);
  688. $data['value'][0] = date('Y-m-d H:i:s', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y')));
  689. $data['value'][1] = date('Y-m-d H:i:s', mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y')));
  690. }
  691. // 上一季度
  692. if ($data['value'][0] == 'lastQuarter') {
  693. $season = ceil((date('n')) / 3) - 1;
  694. $data['value'][0] = date('Y-m-d H:i:s', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y')));
  695. $data['value'][1] = date('Y-m-d H:i:s', mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y')));
  696. }
  697. // 下一季度
  698. if ($data['value'][0] == 'nextQuarter') {
  699. $season = ceil((date('n')) / 3);
  700. $data['value'][0] = date('Y-m-d H:i:s', mktime(0, 0, 0, $season * 3 + 1, 1, date('Y')));
  701. $data['value'][1] = date('Y-m-d H:i:s', mktime(23, 59, 59, $season * 3 + 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y')));
  702. }
  703. // 本月
  704. if ($data['value'][0] == 'month') {
  705. $data['value'][0] = date('Y-m-01 00:00:00');
  706. $data['value'][1] = date('Y-m-31 23:59:59');
  707. }
  708. // 上月
  709. if ($data['value'][0] == 'lastMonth') {
  710. $data['value'][0] = date('Y-m-01 00:00:00', strtotime(date('Y-m-d') . '-1 month'));
  711. $data['value'][1] = date('Y-m-31 23:59:59', strtotime(date('Y-m-d') . '-1 month'));
  712. }
  713. // 下月
  714. if ($data['value'][0] == 'nextMonth') {
  715. $data['value'][0] = date('Y-m-01 00:00:00', strtotime(date('Y-m-d') . '+1 month'));
  716. $data['value'][1] = date('Y-m-31 23:59:59', strtotime(date('Y-m-d') . '+1 month'));
  717. }
  718. // 本周
  719. if ($data['value'][0] == 'week') {
  720. $data['value'][0] = date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y')));
  721. $data['value'][1] = date('Y-m-d 23:59:59', mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y')));
  722. }
  723. // 上周
  724. if ($data['value'][0] == 'lastWeek') {
  725. $date = date("Y-m-d");
  726. $w = date("w", strtotime($date));
  727. $d = $w ? $w - 1 : 6;
  728. $start = date("Y-m-d", strtotime($date . " - " . $d . " days"));
  729. $data['value'][0] = date('Y-m-d', strtotime($start . " - 7 days"));
  730. $data['value'][1] = date('Y-m-d', strtotime($start . " - 1 days"));
  731. }
  732. // 下周
  733. if ($data['value'][0] == 'nextWeek') {
  734. $date = date("Y-m-d");
  735. $w = date("w", strtotime($date));
  736. $d = $w ? $w - 1 : 6;
  737. $start = date("Y-m-d", strtotime($date . " - " . $d . " days"));
  738. $data['value'][0] = date('Y-m-d', strtotime($start . " + 7 days"));
  739. $data['value'][1] = date('Y-m-d', strtotime($start . " + 13 days"));
  740. }
  741. // 今天
  742. if ($data['value'][0] == 'today') {
  743. $data['value'][0] = date('Y-m-d 00:00:00');
  744. $data['value'][1] = date('Y-m-d 23:59:59');
  745. }
  746. // 昨天
  747. if ($data['value'][0] == 'yesterday') {
  748. $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-1 day'));
  749. $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 day'));
  750. }
  751. // 明天
  752. if ($data['value'][0] == 'tomorrow') {
  753. $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 day'));
  754. $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+1 day'));
  755. }
  756. // 过去7天
  757. if ($data['value'][0] == 'previous7day') {
  758. $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-7 day'));
  759. $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 day'));
  760. }
  761. // 过去30天
  762. if ($data['value'][0] == 'previous30day') {
  763. $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-30 day'));
  764. $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 day'));
  765. }
  766. // 未来7天
  767. if ($data['value'][0] == 'future7day') {
  768. $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 day'));
  769. $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+7 day'));
  770. }
  771. // 未来30天
  772. if ($data['value'][0] == 'future30day') {
  773. $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 day'));
  774. $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+30 day'));
  775. }
  776. return $data;
  777. }
  778. /**
  779. * 根据搜索生成where条件
  780. *
  781. * @param string $search 搜索内容
  782. * @param $condition 搜索条件
  783. * @param $k 搜索字段
  784. * @return array|Closure|string[]
  785. */
  786. function field($search, $condition = '', $k = '')
  787. {
  788. switch (trim($condition)) {
  789. case "is" :
  790. $where = ['in', $search];
  791. break;
  792. case "isNot" :
  793. $where = ['notin', $search];
  794. break;
  795. case "contains" :
  796. $containsWhere = [];
  797. foreach ((array)$search as $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
  798. $where = ['like', $containsWhere, 'OR'];
  799. break;
  800. case "notContains" :
  801. $containsWhere = [];
  802. foreach ((array)$search as $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
  803. $where = ['notlike', $containsWhere, 'AND'];
  804. break;
  805. case "startWith" :
  806. $startWithWhere = [];
  807. foreach ((array)$search as $key1 => $value1) $startWithWhere[] = $value1 . '%';
  808. $where = ['like', $startWithWhere, 'OR'];
  809. break;
  810. case "endWith" :
  811. $endWithWhere = [];
  812. foreach ((array)$search as $key1 => $value1) $endWithWhere[] = '%' . $value1;
  813. $where = ['like', $endWithWhere, 'OR'];
  814. break;
  815. case "isNull" :
  816. $where = ['eq', ''];
  817. break;
  818. case "isNotNull" :
  819. $where = ['neq', ''];
  820. break;
  821. case "eq" :
  822. $where = function ($query) use ($search, $k) {
  823. foreach ((array)$search as $key1 => $value1) {
  824. $query->whereOr($k, $value1);
  825. }
  826. };
  827. break;
  828. case "neq" :
  829. $where = function ($query) use ($search, $k) {
  830. foreach ((array)$search as $key1 => $value1) {
  831. $query->whereOr($k, '<>', $value1);
  832. }
  833. };
  834. break;
  835. case "gt" :
  836. $where = function ($query) use ($search, $k) {
  837. foreach ((array)$search as $key1 => $value1) {
  838. $query->whereOr($k, '>', $value1);
  839. }
  840. };
  841. break;
  842. case "egt" :
  843. $where = function ($query) use ($search, $k) {
  844. foreach ((array)$search as $key1 => $value1) {
  845. $query->whereOr($k, '>=', $value1);
  846. }
  847. };
  848. break;
  849. case "lt" :
  850. $where = function ($query) use ($search, $k) {
  851. foreach ((array)$search as $key1 => $value1) {
  852. $query->whereOr($k, '<', $value1);
  853. }
  854. };
  855. break;
  856. case "elt" :
  857. $where = function ($query) use ($search, $k) {
  858. foreach ((array)$search as $key1 => $value1) {
  859. $query->whereOr($k, '<=', $value1);
  860. }
  861. };
  862. break;
  863. case "in" :
  864. $where = ['in', $search];
  865. break;
  866. default :
  867. $where = ['eq', $search];
  868. break;
  869. }
  870. return $where;
  871. }
  872. /**
  873. * 将单个搜索转换为高级搜索格式
  874. * @param string $value 搜索内容
  875. * @param $condition 搜索条件
  876. * @return array
  877. * @author Michael_xu
  878. */
  879. function field_arr($value, $condition = '')
  880. {
  881. if (is_array($value)) {
  882. } else {
  883. $condition = $condition ?: 'eq';
  884. $where_arr = ['value' => $value, 'condition' => $condition];
  885. }
  886. return $where_arr;
  887. }
  888. /**
  889. * 记录操作日志
  890. * @param $id array 操作对象id数组
  891. * @return
  892. * @author Michael_xu
  893. */
  894. function actionLog($id, $join_user_ids = '', $structure_ids = '', $content = '')
  895. {
  896. if (!is_array($id)) {
  897. $idArr[] = $id;
  898. } else {
  899. $idArr = $id;
  900. }
  901. $header = Request::instance()->header();
  902. $authKey = $header['authkey'];
  903. $cache = cache('Auth_' . $authKey);
  904. if (!$cache) {
  905. return false;
  906. }
  907. $userInfo = $cache['userInfo'];
  908. $category = $userInfo['id'] == 1 ? '管理员' : '员工';
  909. $request = request();
  910. $m = strtolower($request->module());
  911. $c = strtolower($request->controller());
  912. $a = strtolower($request->action());
  913. $res_action = true;
  914. foreach ($idArr as $v) {
  915. $data = [];
  916. $data['user_id'] = $userInfo['id'];
  917. $data['module_name'] = $module_name = $m;
  918. $data['controller_name'] = $controller_name = $c;
  919. $data['action_name'] = $action_name = $a;
  920. $data['action_id'] = $v;
  921. $data['create_time'] = time();
  922. $data['client_ip'] = request()->ip();
  923. $data['content'] = $content ?: lang('ACTIONLOG', [$category, $userInfo['realname'], date('Y-m-d H:i:s'), lang($action_name), $v, lang($controller_name)]);
  924. $data['join_user_ids'] = $join_user_ids ?: ''; //抄送人
  925. $data['structure_ids'] = $structure_ids ?: ''; //抄送部门
  926. if ($action_name == 'delete' || $action_name == 'commentdel') {
  927. $data['action_delete'] = 1;
  928. }
  929. if (!db('admin_action_log')->insert($data)) {
  930. $res_action = false;
  931. }
  932. # 数据操作日志
  933. db('admin_operation_log')->insert([
  934. 'user_id' => $userInfo['id'],
  935. 'client_ip' => request()->ip(),
  936. 'module' => $m . '_' . $c,
  937. 'action_id' => $v,
  938. 'content' => $content,
  939. 'create_time' => time()
  940. ]);
  941. }
  942. if ($res_action) {
  943. return true;
  944. } else {
  945. return false;
  946. }
  947. }
  948. /**
  949. * 判断操作权限
  950. * @param
  951. * @return
  952. * @author Michael_xu
  953. */
  954. function checkPerByAction($m, $c, $a)
  955. {
  956. /*获取头部信息*/
  957. $header = Request::instance()->header();
  958. $authKey = $header['authkey'];
  959. $cache = cache('Auth_' . $authKey);
  960. if (!$cache) {
  961. return false;
  962. }
  963. $userInfo = $cache['userInfo'];
  964. $adminTypes = adminGroupTypes($userInfo['id']);
  965. if (in_array(1, $adminTypes)) {
  966. return true;
  967. }
  968. if (empty($m) && empty($c) && empty($a)) {
  969. $request = Request::instance();
  970. $m = strtolower($request->module());
  971. $c = strtolower($request->controller());
  972. $a = strtolower($request->action());
  973. }
  974. $authAdapter = new AuthAdapter($authKey);
  975. $ruleName = $m . '-' . $c . '-' . $a;
  976. if (!$authAdapter->checkIntime($ruleName, $userInfo['id'])) {
  977. return false;
  978. }
  979. return true;
  980. }
  981. /**
  982. * 给树状菜单添加level并去掉没有子菜单的菜单项
  983. * @param array $data [description]
  984. * @param integer $root [description]
  985. * @param string $child [description]
  986. * @param string $level [description]
  987. */
  988. function memuLevelClear($data, $root = 1, $child = 'children', $level = 'level')
  989. {
  990. if (is_array($data)) {
  991. foreach ($data as $key => $val) {
  992. // $data[$key]['selected'] = false;
  993. $data[$key]['level'] = $root;
  994. if (!empty($val[$child]) && is_array($val[$child])) {
  995. $data[$key][$child] = memuLevelClear($val[$child], $root + 1);
  996. } else if ($root < 3 && $data[$key]['menu_type'] == 1) {
  997. unset($data[$key]);
  998. }
  999. if (empty($data[$key][$child]) && ($data[$key]['level'] == 1) && ($data[$key]['menu_type'] == 1)) {
  1000. unset($data[$key]);
  1001. }
  1002. }
  1003. return array_values($data);
  1004. }
  1005. return array();
  1006. }
  1007. /**
  1008. * [rulesDeal 给树状规则表处理成 module-controller-action ]
  1009. * @AuthorHTL
  1010. * @DateTime
  1011. * @param [array] $data [树状规则数组]
  1012. * @return [array] [返回数组]
  1013. */
  1014. function rulesDeal($data)
  1015. {
  1016. if (is_array($data)) {
  1017. $ret = [];
  1018. foreach ($data as $k1 => $v1) {
  1019. $str1 = $v1['name'];
  1020. if (is_array($v1['children'])) {
  1021. foreach ($v1['children'] as $k2 => $v2) {
  1022. $str2 = $str1 . '-' . $v2['name'];
  1023. if (is_array($v2['children'])) {
  1024. foreach ($v2['children'] as $k3 => $v3) {
  1025. $str3 = $str2 . '-' . $v3['name'];
  1026. $ret[] = $str3;
  1027. }
  1028. } else {
  1029. $ret[] = $str2;
  1030. }
  1031. }
  1032. } else {
  1033. $ret[] = $str1;
  1034. }
  1035. }
  1036. return $ret;
  1037. }
  1038. return [];
  1039. }
  1040. /**
  1041. * 获取下属userId
  1042. * @param $self == true 包含自己
  1043. * @param $type == 0 下属userid
  1044. * @param $type == 1 全部userid
  1045. * @param $user_id 需要查询的user_id
  1046. * @author Michael_xu
  1047. */
  1048. function getSubUserId($self = true, $type = 0, $user_id = '')
  1049. {
  1050. $request = Request::instance();
  1051. $header = $request->header();
  1052. $authKey = $header['authkey'];
  1053. $cache = cache('Auth_' . $authKey);
  1054. if (!$user_id) {
  1055. if (!$cache) {
  1056. return false;
  1057. }
  1058. $userInfo = $cache['userInfo'];
  1059. $user_id = $userInfo['id'];
  1060. $adminTypes = adminGroupTypes($user_id);
  1061. if (in_array(1, $adminTypes)) {
  1062. $type = 1;
  1063. }
  1064. }
  1065. $belowIds = [];
  1066. if (empty($type)) {
  1067. if ($user_id) {
  1068. $belowIds = getSubUser($user_id);
  1069. }
  1070. } else {
  1071. $belowIds = getSubUser(0);
  1072. }
  1073. if ($self == true) {
  1074. $belowIds[] = $user_id;
  1075. } else {
  1076. $belowIds = $belowIds ? array_diff($belowIds, array($user_id)) : [];
  1077. }
  1078. return array_unique($belowIds);
  1079. }
  1080. /**
  1081. * 获取下属userId
  1082. * @author Michael_xu
  1083. */
  1084. function getSubUser($userId, $queried = [], $allUserList = [])
  1085. {
  1086. if (empty($allUserList)) {
  1087. $allUserList = db('admin_user')->field('id,parent_id')->select();
  1088. }
  1089. foreach ($allUserList as $k => $v) {
  1090. if ($v['parent_id'] == $userId) {
  1091. $sub_user[] = $v['id'];
  1092. }
  1093. }
  1094. if ($sub_user) {
  1095. foreach ($sub_user as $v) {
  1096. if (in_array($v, $queried)) {
  1097. continue;
  1098. }
  1099. $queried[] = $v;
  1100. $son_user = [];
  1101. $son_user = getSubUser($v, $queried, $allUserList);
  1102. if (!empty($son_user)) {
  1103. $sub_user = array_merge($sub_user, $son_user);
  1104. }
  1105. }
  1106. }
  1107. return $sub_user;
  1108. }
  1109. /**
  1110. * 阿里大于短信发送
  1111. * @param unknown $appkey
  1112. * @param unknown $secret
  1113. * @param unknown $signName 短信签名
  1114. * @param unknown $smsParam
  1115. * @param unknown $templateCode 短信模板
  1116. * @param unknown $send_mobile 接收手机号
  1117. * @param unknown $code 短信验证码
  1118. * @param unknown $template_code 模板参数
  1119. */
  1120. function aliSmsSend($send_mobile, $code, $signName, $templateCode)
  1121. {
  1122. $appkey = '';
  1123. $secret = '';
  1124. import('alimsg.api.Sms', EXTEND_PATH);
  1125. header('Content-Type: text/plain; charset=utf-8');
  1126. $sms = new Sms($appkey, $secret);
  1127. $template_code = array("code" => $code);
  1128. $response = $sms->sendSms($signName, $templateCode, $send_mobile, $template_code);
  1129. $data = object_to_array($response);
  1130. if ($data['Message'] == 'OK' && $data['Code'] == "OK") {
  1131. return true;
  1132. } else {
  1133. return false;
  1134. }
  1135. }
  1136. /**
  1137. * 发送邮件
  1138. * @param unknown $toemail
  1139. * @param unknown $title
  1140. * @param unknown $content
  1141. * @return boolean
  1142. */
  1143. function emailSend($email_host, $email_id, $email_pass, $email_addr, $toemail, $title, $content)
  1144. {
  1145. $result = false;
  1146. try {
  1147. $mail = new Email();
  1148. $mail->setServer($email_host, $email_id, $email_pass);
  1149. $mail->setFrom($email_addr);
  1150. $mail->setReceiver($toemail);
  1151. $mail->setMailInfo($title, $content);
  1152. $result = $mail->sendMail();
  1153. } catch (\Exception $e) {
  1154. $result = false;
  1155. }
  1156. return $result;
  1157. }
  1158. /**
  1159. * 发送站内信
  1160. * @param $user_id 接收人user_id
  1161. * @param $action_id 操作id
  1162. * @param $sysMessage 1为系统消息
  1163. * @param $content 消息内容
  1164. * @return
  1165. * @author Michael_xu
  1166. */
  1167. function sendMessage($user_id, $content, $action_id, $sysMessage = 0)
  1168. {
  1169. $content = trim($content);
  1170. if (!$user_id) return false;
  1171. if (!$content) return false;
  1172. if (!is_array($user_id)) {
  1173. $user_ids[] = $user_id;
  1174. } else {
  1175. $user_ids = $user_id;
  1176. }
  1177. $user_ids = array_unique(array_filter($user_ids));
  1178. $request = request();
  1179. $m = strtolower($request->module());
  1180. $c = strtolower($request->controller());
  1181. $a = strtolower($request->action());
  1182. $userInfo = [];
  1183. if ($sysMessage == 0) {
  1184. $header = $request->header();
  1185. $authkey = $header['authkey'];
  1186. $cache = cache('Auth_' . $authkey);
  1187. if (!$cache) {
  1188. return false;
  1189. }
  1190. $userInfo = $cache['userInfo'];
  1191. }
  1192. foreach ($user_ids as $v) {
  1193. $data = [];
  1194. $data['content'] = $content;
  1195. $data['from_user_id'] = $userInfo['id'] ?: 0;
  1196. $data['to_user_id'] = $v;
  1197. $data['read_time'] = 0;
  1198. $data['send_time'] = time();
  1199. $data['module_name'] = $m;
  1200. $data['controller_name'] = $c;
  1201. $data['action_name'] = $a;
  1202. $data['action_id'] = $action_id;
  1203. db('admin_message')->insert($data);
  1204. }
  1205. return true;
  1206. }
  1207. /**
  1208. * 格式化字节大小
  1209. * @param number $size 字节数
  1210. * @param string $delimiter 数字和单位分隔符
  1211. * @return string 格式化后的带单位的大小
  1212. * @author
  1213. */
  1214. function format_bytes($size, $delimiter = '')
  1215. {
  1216. $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  1217. for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
  1218. return round($size, 2) . $delimiter . $units[$i];
  1219. }
  1220. /**
  1221. * 数据修改日志
  1222. * @param $types 类型
  1223. * @param $action_id 操作ID
  1224. * @param $newData 新数据
  1225. * @param $newData 新数据
  1226. * @return
  1227. * @author Michael_xu
  1228. */
  1229. function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData = [], $content = '')
  1230. {
  1231. # 转格式
  1232. if (!empty($oldData['next_time']) && $oldData['next_time'] != strtotime($oldData['next_time'])) {
  1233. $oldData['next_time'] = strtotime($oldData['next_time']);
  1234. }
  1235. if (is_array($oldData) && is_array($newData) && $user_id) {
  1236. $differentData = array_diff_assoc($newData, $oldData);
  1237. $fieldModel = new FieldModel();
  1238. $userModel = new UserModel();
  1239. $structureModel = new \app\admin\model\Structure();
  1240. $field_arr = $fieldModel->getField(['types' => $types, 'unFormType' => ['file', 'form']]); //获取字段属性
  1241. $newFieldArr = array();
  1242. foreach ($field_arr as $k => $v) {
  1243. $newFieldArr[$v['field']] = $v;
  1244. }
  1245. $unField = ['update_time', 'create_time']; //定义过滤字段
  1246. $message = [];
  1247. $un_form_type = ['file', 'form'];
  1248. foreach ($differentData as $k => $v) {
  1249. if ($newFieldArr[$k] && !in_array($newFieldArr[$k]['form_type'], $un_form_type)) {
  1250. $field_name = '';
  1251. $field_name = $newFieldArr[$k]['name'];
  1252. $new_value = $v ?: '空';
  1253. $old_value = $oldData[$k] ?: '空';
  1254. if ($newFieldArr[$k]['form_type'] == 'datetime') {
  1255. $new_value = $v ? date('Y-m-d', $v) : '空';
  1256. if (date('Y-m-d H:i:s', strtotime($oldData[$k])) == $oldData[$k]) {
  1257. $old_value = !empty($oldData[$k]) ? $oldData[$k] : '空';
  1258. } else {
  1259. $old_value = !empty($oldData[$k]) ? date('Y-m-d', $oldData[$k]) : '空';
  1260. }
  1261. if (empty($v) && empty($oldData[$k])) continue;
  1262. } elseif ($newFieldArr[$k]['form_type'] == 'user') {
  1263. $new_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($v))) : '';
  1264. $old_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($oldData[$k]))) : '';
  1265. } elseif ($newFieldArr[$k]['form_type'] == 'structure') {
  1266. $new_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($v))) : '';
  1267. $old_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($oldData[$k]))) : '';
  1268. } elseif ($newFieldArr[$k]['form_type'] == 'business_status') {
  1269. $new_value = $v ? db('crm_business_status')->where(['status_id' => $v])->value('name') : '';
  1270. $old_value = $v ? db('crm_business_status')->where(['status_id' => $oldData[$k]])->value('name') : '';
  1271. } elseif ($newFieldArr[$k]['form_type'] == 'business_type') {
  1272. $new_value = $v ? db('crm_business_type')->where(['type_id' => $v])->value('name') : '';
  1273. $old_value = $v ? db('crm_business_type')->where(['type_id' => $oldData[$k]])->value('name') : '';
  1274. } elseif ($newFieldArr[$k]['form_type'] == 'customer') {
  1275. $new_value = $v ? db('crm_customer')->where(['customer_id' => $v])->value('name') : '';
  1276. $old_value = $v ? db('crm_customer')->where(['customer_id' => $oldData[$k]])->value('name') : '';
  1277. } elseif ($newFieldArr[$k]['form_type'] == 'category') {
  1278. $new_value = $v ? db('crm_product_category')->where(['category_id' => $v])->value('name') : '';
  1279. $old_value = $v ? db('crm_product_category')->where(['category_id' => $oldData[$k]])->value('name') : '';
  1280. } elseif ($newFieldArr[$k]['form_type'] == 'business') {
  1281. $new_value = $v ? db('crm_business')->where(['business_id' => $v])->value('name') : '';
  1282. $old_value = $v ? db('crm_business')->where(['business_id' => $oldData[$k]])->value('name') : '';
  1283. } elseif ($newFieldArr[$k]['field'] == 'check_status') {
  1284. $statusArr = ['0' => '待审核', '1' => '审核中', '2' => '审核通过', '3' => '已拒绝', '4' => '已撤回', '5' => '未提交'];
  1285. $new_value = $statusArr[$v];
  1286. $old_value = $statusArr[$oldData[$k]];
  1287. } elseif ($newFieldArr[$k]['form_type'] == 'visit') {
  1288. $new_value = $v ? db('crm_visit')->where(['visit_id' => $v])->value('number') : '';
  1289. $old_value = $v ? db('crm_visit')->where(['visit_id' => $oldData[$k]])->value('number') : '';
  1290. } elseif ($newFieldArr[$k]['form_type'] == 'single_user') {
  1291. $new_value = $v ? db('admin_user')->where(['id' => $v])->value('realname') : '';
  1292. $old_value = $v ? db('admin_user')->where(['id' => $oldData['owner_user_id']])->value('realname') : '';
  1293. } elseif ($newFieldArr[$k]['form_type'] == 'floatnumber') {
  1294. $new_value = $v ? number_format($v, 2) : '';
  1295. }
  1296. if ($old_value != $new_value) {
  1297. $message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
  1298. }
  1299. }
  1300. }
  1301. if ($message) {
  1302. $data = [];
  1303. $data['user_id'] = $user_id;
  1304. $data['create_time'] = time();
  1305. $data['types'] = $types;
  1306. $data['action_id'] = $action_id;
  1307. $data['content'] = implode('.|.', $message);
  1308. db('admin_action_record')->insert($data);
  1309. }
  1310. } elseif ($content) {
  1311. $data = [];
  1312. $data['user_id'] = $user_id;
  1313. $data['create_time'] = time();
  1314. $data['types'] = $types;
  1315. $data['action_id'] = $action_id;
  1316. $data['content'] = $content;
  1317. db('admin_action_record')->insert($data);
  1318. }
  1319. }
  1320. /**
  1321. * 截取字符串
  1322. * @param $start 开始截取位置
  1323. * @param $length 截取长度
  1324. * @return
  1325. * @author Michael_xu
  1326. */
  1327. function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
  1328. {
  1329. if (function_exists("mb_substr")) {
  1330. $slice = mb_substr($str, $start, $length, $charset);
  1331. } elseif (function_exists('iconv_substr')) {
  1332. $slice = iconv_substr($str, $start, $length, $charset);
  1333. if (false === $slice) {
  1334. $slice = '';
  1335. }
  1336. } else {
  1337. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  1338. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  1339. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  1340. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  1341. preg_match_all($re[$charset], $str, $match);
  1342. $slice = join("", array_slice($match[0], $start, $length));
  1343. }
  1344. if (utf8_strlen($str) < $length) $suffix = false;
  1345. return $suffix ? $slice . '...' : $slice;
  1346. }
  1347. function utf8_strlen($string = null)
  1348. {
  1349. preg_match_all("/./us", $string, $match);
  1350. return count($match[0]);
  1351. }
  1352. /**
  1353. * 合法性验证
  1354. * @param client_sign 签名参数值,使用相同规则对提交参数进行加密验证
  1355. * @return
  1356. * @author Michael_xu
  1357. */
  1358. function checkVerify($saftCode = '5kcrm@')
  1359. {
  1360. $parmList = Request::instance()->post();
  1361. $header = $request->header();
  1362. $parmList['sessionId'] = $header['sessionId'];
  1363. $authkey = $header['authKey'];
  1364. $clientSign = $parmList['client_sign'];
  1365. if ($clientSign) {
  1366. unset($parmList['client_sign']);
  1367. if (count($parmList) > 0) {
  1368. // 对要签名参数按照签名格式组合
  1369. foreach ($parmList as $key => $value) {
  1370. if (isset($_POST[$key])) {
  1371. $parame[$key] = $key . '=' . trim($_POST[$key]);
  1372. } else {
  1373. return false;
  1374. }
  1375. }
  1376. ksort($parame); //参数排序
  1377. $returnValue = implode("&", $parame); //拼接字符串
  1378. if ($returnValue) {
  1379. //base64加密
  1380. $signCalc = base64_encode(hash_hmac("sha1", $returnValue, $saftCode . $authkey, $raw_output = false));
  1381. // 检查参数签名是否一致
  1382. if (trim($clientSign) != trim($signCalc)) {
  1383. return false;
  1384. } else {
  1385. return true;
  1386. }
  1387. } else {
  1388. return false;
  1389. }
  1390. } else {
  1391. return false;
  1392. }
  1393. } else {
  1394. //签名认证错误
  1395. return false;
  1396. }
  1397. }
  1398. /**
  1399. * 数组转换字符串(以逗号隔开)
  1400. * @param
  1401. * @return
  1402. * @author Michael_xu
  1403. */
  1404. function arrayToString($array)
  1405. {
  1406. if (!is_array($array)) {
  1407. $data_arr[] = $array;
  1408. } else {
  1409. $data_arr = $array;
  1410. }
  1411. $data_arr = array_filter($data_arr); //数组去空
  1412. $data_arr = array_unique($data_arr); //数组去重
  1413. $data_arr = array_merge($data_arr);
  1414. $string = $data_arr ? ',' . implode(',', $data_arr) . ',' : '';
  1415. return $string ?: '';
  1416. }
  1417. /**
  1418. * 字符串转换数组(以逗号隔开)
  1419. * @param
  1420. * @return
  1421. * @author Michael_xu
  1422. */
  1423. function stringToArray($string)
  1424. {
  1425. if (is_array($string)) {
  1426. $data_arr = array_unique(array_filter($string));
  1427. } else {
  1428. $data_arr = $string ? array_unique(array_filter(explode(',', $string))) : [];
  1429. }
  1430. $data_arr = $data_arr ? array_merge($data_arr) : [];
  1431. return $data_arr ?: [];
  1432. }
  1433. /**
  1434. * 根据时间戳获取星期几
  1435. * @param $time 要转换的时间戳
  1436. */
  1437. function getTimeWeek($time, $i = 0)
  1438. {
  1439. $weekarray = array("日", "一", "二", "三", "四", "五", "六");
  1440. $oneD = 24 * 60 * 60;
  1441. return "星期" . $weekarray[date("w", $time + $oneD * $i)];
  1442. }
  1443. /**
  1444. * 二维数组排序(选择)
  1445. * @param $select 要进行排序的select结果集
  1446. * @param $field 排序的字段
  1447. * @param $order 排序方式1降序2升序
  1448. */
  1449. function sort_select($select = array(), $field, $order = 1)
  1450. {
  1451. $count = count($select);
  1452. if ($order == 1) {
  1453. for ($i = 0; $i < $count; $i++) {
  1454. $k = $i;
  1455. for ($j = $i; $j < $count; $j++) {
  1456. if ($select[$k][$field] < $select[$j][$field]) {
  1457. $k = $j;
  1458. }
  1459. }
  1460. $temp = $select[$i];
  1461. $select[$i] = $select[$k];
  1462. $select[$k] = $temp;
  1463. }
  1464. return $select;
  1465. } else {
  1466. for ($i = 0; $i < $count; $i++) {
  1467. $k = $i;
  1468. for ($j = $i; $j < $count; $j++) {
  1469. if ($select[$k][$field] > $select[$j][$field]) {
  1470. $k = $j;
  1471. }
  1472. }
  1473. $temp = $select[$i];
  1474. $select[$i] = $select[$k];
  1475. $select[$k] = $temp;
  1476. }
  1477. return $select;
  1478. }
  1479. }
  1480. /**
  1481. * 将秒数转换为时间 (年、天、小时、分、秒)
  1482. * @param
  1483. */
  1484. function getTimeBySec($time)
  1485. {
  1486. if (is_numeric($time)) {
  1487. $value = array(
  1488. "years" => 0, "days" => 0, "hours" => 0,
  1489. "minutes" => 0, "seconds" => 0,
  1490. );
  1491. if ($time >= 31556926) {
  1492. $value["years"] = floor($time / 31556926);
  1493. $time = ($time % 31556926);
  1494. $t .= $value["years"] . "年";
  1495. }
  1496. if ($time >= 86400) {
  1497. $value["days"] = floor($time / 86400);
  1498. $time = ($time % 86400);
  1499. $t .= $value["days"] . "天";
  1500. }
  1501. if ($time >= 3600) {
  1502. $value["hours"] = floor($time / 3600);
  1503. $time = ($time % 3600);
  1504. $t .= $value["hours"] . "小时";
  1505. }
  1506. if ($time >= 60) {
  1507. $value["minutes"] = floor($time / 60);
  1508. $time = ($time % 60);
  1509. $t .= $value["minutes"] . "分钟";
  1510. }
  1511. if ($time < 60) {
  1512. $value["seconds"] = floor($time);
  1513. $t .= $value["seconds"] . "秒";
  1514. }
  1515. return $t;
  1516. } else {
  1517. return (bool)FALSE;
  1518. }
  1519. }
  1520. /*
  1521. *根据年月计算有几天
  1522. */
  1523. function getmonthByYM($param)
  1524. {
  1525. $month = $param['month'] ? $param['month'] : date('m', time());
  1526. $year = $param['year'] ? $param['year'] : date('Y', time());
  1527. if (in_array($month, array('1', '3', '5', '7', '8', '01', '03', '05', '07', '08', '10', '12'))) {
  1528. $days = '31';
  1529. } elseif ($month == 2) {
  1530. if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 !== 0)) {
  1531. //判断是否是闰年
  1532. $days = '29';
  1533. } else {
  1534. $days = '28';
  1535. }
  1536. } else {
  1537. $days = '30';
  1538. }
  1539. return $days;
  1540. }
  1541. /**
  1542. * 根据时间戳计算当月天数
  1543. * @param
  1544. */
  1545. function getmonthdays($time)
  1546. {
  1547. $month = date('m', $time);
  1548. $year = date('Y', $time);
  1549. if (in_array($month, array('1', '3', '5', '7', '8', '01', '03', '05', '07', '08', '10', '12'))) {
  1550. $days = '31';
  1551. } elseif ($month == 2) {
  1552. if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 !== 0)) {
  1553. //判断是否是闰年
  1554. $days = '29';
  1555. } else {
  1556. $days = '28';
  1557. }
  1558. } else {
  1559. $days = '30';
  1560. }
  1561. return $days;
  1562. }
  1563. /**
  1564. * 生成从开始时间到结束时间的日期数组
  1565. * @param type,默认时间戳格式
  1566. * @param type = 1 时,date格式
  1567. * @param type = 2 时,获取每日开始、结束时间
  1568. */
  1569. function dateList($start, $end, $type = 0)
  1570. {
  1571. if (!is_numeric($start) || !is_numeric($end) || ($end <= $start)) return '';
  1572. $i = 0;
  1573. //从开始日期到结束日期的每日时间戳数组
  1574. $d = array();
  1575. if ($type == 1) {
  1576. while ($start <= $end) {
  1577. $d[$i] = date('Y-m-d', $start);
  1578. $start = $start + 86400;
  1579. $i++;
  1580. }
  1581. } else {
  1582. while ($start <= $end) {
  1583. $d[$i] = $start;
  1584. $start = $start + 86400;
  1585. $i++;
  1586. }
  1587. }
  1588. if ($type == 2) {
  1589. $list = array();
  1590. foreach ($d as $k => $v) {
  1591. $list[$k] = getDateRange($v);
  1592. }
  1593. return $list;
  1594. } else {
  1595. return $d;
  1596. }
  1597. }
  1598. /**
  1599. * 获取指定日期开始时间与结束时间
  1600. */
  1601. function getDateRange($timestamp)
  1602. {
  1603. $ret = array();
  1604. $ret['sdate'] = strtotime(date('Y-m-d', $timestamp));
  1605. $ret['edate'] = strtotime(date('Y-m-d', $timestamp)) + 86400;
  1606. return $ret;
  1607. }
  1608. /**
  1609. * 生成从开始月份到结束月份的月份数组
  1610. * @param int $start 开始时间戳
  1611. * @param int $end 结束时间戳
  1612. */
  1613. function monthList($start, $end)
  1614. {
  1615. if (!is_numeric($start) || !is_numeric($end) || ($end <= $start)) return '';
  1616. $start = date('Y-m', $start);
  1617. $end = date('Y-m', $end);
  1618. //转为时间戳
  1619. $start = strtotime($start . '-01');
  1620. $end = strtotime($end . '-01');
  1621. $i = 0;
  1622. $d = array();
  1623. while ($start <= $end) {
  1624. //这里累加每个月的的总秒数 计算公式:上一月1号的时间戳秒数减去当前月的时间戳秒数
  1625. $d[$i] = $start;
  1626. $start += strtotime('+1 month', $start) - $start;
  1627. $i++;
  1628. }
  1629. return $d;
  1630. }
  1631. /**
  1632. * 人民币转大写
  1633. * @param
  1634. */
  1635. function cny($ns)
  1636. {
  1637. static $cnums = array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"),
  1638. $cnyunits = array("圆", "角", "分"),
  1639. $grees = array("拾", "佰", "仟", "万", "拾", "佰", "仟", "亿");
  1640. list($ns1, $ns2) = explode(".", $ns, 2);
  1641. $ns2 = array_filter(array($ns2[1], $ns2[0]));
  1642. $ret = array_merge($ns2, array(implode("", _cny_map_unit(str_split($ns1), $grees)), ""));
  1643. $ret = implode("", array_reverse(_cny_map_unit($ret, $cnyunits)));
  1644. return str_replace(array_keys($cnums), $cnums, $ret);
  1645. }
  1646. function _cny_map_unit($list, $units)
  1647. {
  1648. $ul = count($units);
  1649. $xs = array();
  1650. foreach (array_reverse($list) as $x) {
  1651. $l = count($xs);
  1652. if ($x != "0" || !($l % 4)) {
  1653. $n = ($x == '0' ? '' : $x) . ($units[($l - 1) % $ul]);
  1654. } else {
  1655. $n = is_numeric($xs[0][0]) ? $x : '';
  1656. }
  1657. array_unshift($xs, $n);
  1658. }
  1659. return $xs;
  1660. }
  1661. /**
  1662. * 根据类型获取上一类型时间戳数组
  1663. */
  1664. function getLstTimeByType($type = 'today')
  1665. {
  1666. switch ($type) {
  1667. case 'yesterday' :
  1668. $timeArr = Time::yesterday();
  1669. break;
  1670. case 'week' :
  1671. $timeArr = Time::week();
  1672. break;
  1673. case 'lastWeek' :
  1674. $timeArr = Time::lastWeek();
  1675. break;
  1676. case 'month' :
  1677. $timeArr = Time::month();
  1678. break;
  1679. case 'lastMonth' :
  1680. $timeArr = Time::lastMonth();
  1681. break;
  1682. case 'quarter' :
  1683. //本季度
  1684. $month = date('m');
  1685. if ($month == 1 || $month == 2 || $month == 3) {
  1686. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1687. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1688. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1689. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1690. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1691. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1692. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1693. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1694. } else {
  1695. $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
  1696. $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
  1697. }
  1698. $timeArr = array($daterange_start_time, $daterange_end_time);
  1699. break;
  1700. case 'lastQuarter' :
  1701. //上季度
  1702. $month = date('m');
  1703. if ($month == 1 || $month == 2 || $month == 3) {
  1704. $year = date('Y') - 1;
  1705. $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
  1706. $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
  1707. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1708. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1709. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1710. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1711. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1712. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1713. } else {
  1714. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1715. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1716. }
  1717. $timeArr = array($daterange_start_time, $daterange_end_time);
  1718. break;
  1719. case 'year' :
  1720. $timeArr = Time::year();
  1721. break;
  1722. case 'lastYear' :
  1723. $timeArr = Time::lastYear();
  1724. break;
  1725. default :
  1726. $timeArr = Time::today();
  1727. break;
  1728. }
  1729. return $timeArr;
  1730. }
  1731. /**
  1732. * 根据类型获取开始结束时间戳数组
  1733. * @param
  1734. */
  1735. function getTimeByType($type = 'today', $is_last = false)
  1736. {
  1737. $lastArr = [];
  1738. switch ($type) {
  1739. case 'yesterday' :
  1740. $timeArr = Time::yesterday();
  1741. break;
  1742. case 'week' :
  1743. $timeArr = Time::week();
  1744. break;
  1745. case 'lastWeek' :
  1746. $timeArr = Time::lastWeek();
  1747. break;
  1748. case 'month' :
  1749. $timeArr = Time::month();
  1750. break;
  1751. case 'lastMonth' :
  1752. $timeArr = Time::lastMonth();
  1753. break;
  1754. case 'quarter' :
  1755. //本季度
  1756. $month = date('m');
  1757. if ($month == 1 || $month == 2 || $month == 3) {
  1758. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1759. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1760. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1761. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1762. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1763. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1764. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1765. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1766. } else {
  1767. $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
  1768. $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
  1769. }
  1770. $timeArr = array($daterange_start_time, $daterange_end_time);
  1771. break;
  1772. case 'lastQuarter' :
  1773. //上季度
  1774. $month = date('m');
  1775. if ($month == 1 || $month == 2 || $month == 3) {
  1776. $year = date('Y') - 1;
  1777. $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
  1778. $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
  1779. } elseif ($month == 4 || $month == 5 || $month == 6) {
  1780. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  1781. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  1782. } elseif ($month == 7 || $month == 8 || $month == 9) {
  1783. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  1784. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  1785. } else {
  1786. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  1787. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  1788. }
  1789. $timeArr = array($daterange_start_time, $daterange_end_time);
  1790. break;
  1791. case 'year' :
  1792. $timeArr = Time::year();
  1793. break;
  1794. case 'lastYear' :
  1795. $timeArr = Time::lastYear();
  1796. break;
  1797. default :
  1798. $timeArr = Time::today();
  1799. break;
  1800. }
  1801. if ($is_last) {
  1802. return $lastArr;
  1803. } else {
  1804. return $timeArr;
  1805. }
  1806. }
  1807. /**
  1808. * 服务器附件完整路径处理
  1809. * @param
  1810. */
  1811. function getFullPath($path)
  1812. {
  1813. if ($path) {
  1814. $protocol = strpos(strtolower($_SERVER['REQUEST_SCHEME']), 'https') === false ? 'http' : 'https';
  1815. return $protocol . '://' . $_SERVER['HTTP_HOST'] . substr($_SERVER["SCRIPT_NAME"], 0, -10) . substr(str_replace(DS, '/', $path), 1);
  1816. } else {
  1817. return '';
  1818. }
  1819. }
  1820. /*取得文件后缀*/
  1821. function getExtension($filename)
  1822. {
  1823. $mytext = substr($filename, strrpos($filename, '.') + 1);
  1824. return $mytext;
  1825. }
  1826. /**
  1827. * 生成编号
  1828. * @param prefix 前缀
  1829. * @return
  1830. * @author Michael_xu
  1831. */
  1832. function prefixNumber($prefix, $number_id = 0, $str = 5)
  1833. {
  1834. return $prefixNumber = $prefix . str_pad($number_id, $str, 0, STR_PAD_LEFT); //填充字符串的左侧(将字符串填充为新的长度)
  1835. }
  1836. /**
  1837. * curl 模拟GET请求
  1838. * @author lee
  1839. ***/
  1840. function curl_get($url)
  1841. {
  1842. //初始化
  1843. $ch = curl_init();
  1844. //设置抓取的url
  1845. curl_setopt($ch, CURLOPT_URL, $url);
  1846. //设置获取的信息以文件流的形式返回,而不是直接输出。
  1847. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1848. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书
  1849. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // https请求 不验证hosts
  1850. //执行命令
  1851. $output = curl_exec($ch);
  1852. curl_close($ch); //释放curl句柄
  1853. return $output;
  1854. }
  1855. /**
  1856. * 地址坐标转换
  1857. * @param prefix 前缀
  1858. * @return
  1859. * @author Michael_xu
  1860. */
  1861. function get_lng_lat($address)
  1862. {
  1863. $map_ak = config('map_ak');
  1864. $url = "http://api.map.baidu.com/geocoder/v2/?address=$address&output=json&ak=$map_ak&callback=showLocation";
  1865. $ret_script = curl_get($url);
  1866. preg_match_all("/\{.*?\}}/is", $ret_script, $matches);
  1867. $ret_arr = json_decode($matches[0][0], true);
  1868. if ($ret_arr['status'] == 0) { //成功
  1869. $location['lng'] = $ret_arr['result']['location']['lng'];
  1870. $location['lat'] = $ret_arr['result']['location']['lat'];
  1871. return $location;
  1872. } else {
  1873. return false;
  1874. }
  1875. }
  1876. /**
  1877. * 导出数据为excel表格
  1878. * @param $data 一个二维数组,结构如同从数据库查出来的数组
  1879. * @param $title excel的第一行标题,一个数组,如果为空则没有标题
  1880. * @param $filename 下载的文件名
  1881. * @param exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
  1882. */
  1883. function exportexcel($data = array(), $title = array(), $filename = 'report')
  1884. {
  1885. header("Content-type:application/octet-stream");
  1886. header("Accept-Ranges:bytes");
  1887. header("Content-type:application/vnd.ms-excel");
  1888. header("Content-Disposition:attachment;filename=" . $filename . ".xls");
  1889. header("Pragma: no-cache");
  1890. header("Expires: 0");
  1891. //导出xls 开始
  1892. if (!empty($title)) {
  1893. foreach ($title as $k => $v) {
  1894. $title[$k] = iconv("UTF-8", "GB2312", $v);
  1895. }
  1896. $title = implode("\t", $title);
  1897. echo "$title\n";
  1898. }
  1899. if (!empty($data)) {
  1900. foreach ($data as $key => $val) {
  1901. foreach ($val as $ck => $cv) {
  1902. $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
  1903. }
  1904. $data[$key] = implode("\t", $data[$key]);
  1905. }
  1906. echo implode("\n", $data);
  1907. }
  1908. }
  1909. //根据数据库查询出来数组获取某个字段拼接字符串
  1910. function getFieldArray($array = array(), $field = '')
  1911. {
  1912. if (is_array($array) && $field) {
  1913. $ary = array();
  1914. foreach ($array as $value) {
  1915. $ary[] = $value[$field];
  1916. }
  1917. $str = implode(',', $ary);
  1918. return $str;
  1919. } else {
  1920. return false;
  1921. }
  1922. }
  1923. /**
  1924. * 检查该字段若必填,加上"*"
  1925. * @param is_null 是否为空 0否 1是
  1926. * @param name 字段名称
  1927. **/
  1928. function sign_required($is_null, $name)
  1929. {
  1930. if ($is_null == 1) {
  1931. return '*' . $name;
  1932. } else {
  1933. return $name;
  1934. }
  1935. }
  1936. /**
  1937. * [获取是否有管理员角色 adminGroupTypes]
  1938. * @param user_id 当前人ID
  1939. * @return
  1940. */
  1941. function adminGroupTypes($user_id)
  1942. {
  1943. $userModel = new UserModel();
  1944. $groupsArr = $userModel->get($user_id)->groups;
  1945. $groupids = [];
  1946. if ($groupsArr) {
  1947. foreach ($groupsArr as $key => $val) {
  1948. $groupids[] = $val['id'];
  1949. }
  1950. }
  1951. $types = db('admin_group')->where(['id' => ['in', $groupids]])->group('types')->column('types');
  1952. if ($user_id == 1) {
  1953. $types[] = 1;
  1954. }
  1955. return $types ?: [];
  1956. }
  1957. /**
  1958. * [权限数组]
  1959. * @param ruleIds 当前人权限id
  1960. * @return
  1961. */
  1962. function rulesListToArray($rulesList, $ruleIds = [])
  1963. {
  1964. $newList = [];
  1965. if (!is_array($rulesList)) {
  1966. return array();
  1967. } else {
  1968. foreach ($rulesList as $k => $v) {
  1969. if (!is_array($v['children'])) continue;
  1970. foreach ($v['children'] as $k1 => $v1) {
  1971. if (!is_array($v1['children'])) continue;
  1972. foreach ($v1['children'] as $k2 => $v2) {
  1973. $check = false;
  1974. if (in_array($v2['id'], $ruleIds)) {
  1975. $check = true;
  1976. }
  1977. $newList[$v['name']][$v1['name']][$v2['name']] = $check;
  1978. }
  1979. }
  1980. }
  1981. }
  1982. return $newList ?: [];
  1983. }
  1984. /**
  1985. * [获取下一审批信息 nextCheckData]
  1986. * @param user_id 审批申请人ID
  1987. * @param flow_id 审批流ID
  1988. * @param types 关联对象
  1989. * @param types_id 联对象ID
  1990. * @param order_id 审批排序ID
  1991. * @return
  1992. */
  1993. function nextCheckData($user_id, $flow_id, $types, $types_id, $order_id, $check_user_id)
  1994. {
  1995. $new_order_id = $order_id;
  1996. $max_order_id = db('admin_examine_step')->where(['flow_id' => $flow_id])->max('order_id'); //审批流最大排序ID
  1997. $examineStepModel = new \app\admin\model\ExamineStep();
  1998. $stepInfo = $examineStepModel->getStepByOrder($flow_id, $new_order_id); //审批步骤
  1999. $next_user_ids = [];
  2000. $is_end = 0; //审批结束
  2001. //固定流程(status 1负责人主管,2指定用户(任意一人),3指定用户(多人会签),4上一级审批人主管)
  2002. //当前步骤审批人user_id
  2003. $step_user_ids = $examineStepModel->getUserByStep($stepInfo['step_id'], $user_id);
  2004. if ($step_user_ids) {
  2005. if (!$order_id) {
  2006. //创建时使用
  2007. $sub_user_ids = stringToArray($step_user_ids);
  2008. } else {
  2009. if ($stepInfo['status'] == 3) {
  2010. //会签(并关系)
  2011. //当前步骤已审批user_id
  2012. $check_user_ids = $examineStepModel->getUserByCheck($types, $types_id, $new_order_id);
  2013. $user_ids[] = $check_user_id;
  2014. $check_user_ids = $check_user_ids ? array_merge($check_user_ids, $user_ids) : $user_ids;
  2015. //剩余审批人user_id
  2016. $sub_user_ids = $check_user_ids ? array_diff(explode(',', $step_user_ids), $check_user_ids) : $step_user_ids;
  2017. $sub_user_ids = array_unique(array_filter($sub_user_ids));
  2018. if (!$sub_user_ids) {
  2019. $is_end = 1;
  2020. }
  2021. } else {
  2022. $is_end = 1;
  2023. }
  2024. }
  2025. } else {
  2026. $is_end = 1;
  2027. }
  2028. if ($is_end == 1) {
  2029. $next_order_id = $new_order_id + 1;
  2030. } else {
  2031. $next_order_id = $new_order_id;
  2032. }
  2033. //当前审批步骤已结束
  2034. if ($is_end == 1) {
  2035. //当前审批流程是否结束
  2036. $stepInfo = $examineStepModel->getStepByOrder($flow_id, $next_order_id); //审批步骤
  2037. $next_step_user_ids = $examineStepModel->getUserByStep($stepInfo['step_id'], $user_id);
  2038. $next_user_ids = stringToArray($next_step_user_ids);
  2039. } else {
  2040. $next_user_ids = array_unique(array_filter($sub_user_ids));
  2041. }
  2042. if (!$next_user_ids && $next_order_id <= $max_order_id) {
  2043. $newRes = [];
  2044. $newRes = nextCheckData($user_id, $flow_id, $types, $types_id, $next_order_id, $check_user_id);
  2045. $next_user_ids = $newRes['next_user_ids'];
  2046. }
  2047. $data = [];
  2048. $data['order_id'] = ($next_order_id <= $max_order_id) ? $next_order_id : $max_order_id;
  2049. $data['next_user_ids'] = $next_user_ids ?: '';
  2050. return $data;
  2051. }
  2052. /**
  2053. * 解析获取php.ini 的upload_max_filesize(单位:byte)
  2054. * @param $dec int 小数位数
  2055. * @return float (单位:byte)
  2056. * */
  2057. function get_upload_max_filesize_byte($dec = 2)
  2058. {
  2059. $max_size = ini_get('upload_max_filesize');
  2060. preg_match('/(^[0-9\.]+)(\w+)/', $max_size, $info);
  2061. $size = $info[1];
  2062. $suffix = strtoupper($info[2]);
  2063. $a = array_flip(array("B", "KB", "MB", "GB", "TB", "PB"));
  2064. $b = array_flip(array("B", "K", "M", "G", "T", "P"));
  2065. $pos = $a[$suffix] && $a[$suffix] !== 0 ? $a[$suffix] : $b[$suffix];
  2066. return round($size * pow(1024, $pos), $dec);
  2067. }
  2068. /**
  2069. * 模拟post进行url请求
  2070. * @param string $url
  2071. * @param string $param
  2072. */
  2073. function curl_post($url = '', $post = array())
  2074. {
  2075. $curl = curl_init(); // 启动一个CURL会话
  2076. curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
  2077. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
  2078. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
  2079. curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
  2080. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
  2081. curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
  2082. curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
  2083. curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
  2084. curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
  2085. curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
  2086. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
  2087. $res = curl_exec($curl); // 执行操作
  2088. if (curl_errno($curl)) {
  2089. echo 'Errno' . curl_error($curl);//捕抓异常
  2090. }
  2091. curl_close($curl); // 关闭CURL会话
  2092. return $res; // 返回数据,json格式
  2093. }
  2094. /**
  2095. * 输出json字符串,用于接口调试
  2096. *
  2097. * @return void
  2098. * @author ymob
  2099. */
  2100. function vdd()
  2101. {
  2102. header('Content-Type: text/json; charset=utf-8');
  2103. $args = func_get_args();
  2104. foreach ($args as &$val) {
  2105. if ($val instanceof think\Model) {
  2106. $val = $val->getLastSql();
  2107. }
  2108. }
  2109. if (count($args) < 2) {
  2110. $args = array_shift($args);
  2111. }
  2112. die(json_encode($args));
  2113. }
  2114. /**
  2115. * 根据时间查询参数返回时间条件 (用于统计分析模块)
  2116. *
  2117. * @param array $where
  2118. * @param string $field
  2119. * @return void
  2120. * @author ymob
  2121. */
  2122. function getWhereTimeByParam(&$where, $field = 'create_time')
  2123. {
  2124. $param = request()->param();
  2125. if (empty($param['type']) && empty($param['start_time'])) {
  2126. $param['type'] = 'month';
  2127. }
  2128. if (!empty($param['start_time'])) {
  2129. $where[$field] = ['between', [$param['start_time'], $param['end_time']]];
  2130. } else {
  2131. $timeRange = getTimeByType($param['type']);
  2132. if ($timeRange) {
  2133. $where[$field] = ['between', [$timeRange[0], $timeRange[1]]];
  2134. }
  2135. }
  2136. }
  2137. /**
  2138. * 根据员工、部门查询参数返回员工、部门条件 (用于统计分析模块)
  2139. *
  2140. * @param array $where
  2141. * @param string $field
  2142. * @param string $m
  2143. * @param string $c
  2144. * @param string $a
  2145. * @return void
  2146. * @author ymob
  2147. */
  2148. function getWhereUserByParam(&$where, $field = 'owner_user_id', $m = '', $c = '', $a = '')
  2149. {
  2150. $param = request()->param();
  2151. $userModel = new UserModel();
  2152. $map_user_ids = [];
  2153. if ($param['user_id']) {
  2154. $map_user_ids = array($param['user_id']);
  2155. } elseif ($param['structure_id']) {
  2156. $map_user_ids = $userModel->getSubUserByStr($param['structure_id'], 2);
  2157. } else {
  2158. $map_user_ids = $userModel->getUserByPer($m, $c, $a);
  2159. $where[$field] = array('in', $map_user_ids);
  2160. return;
  2161. }
  2162. $perUserIds = $userModel->getUserByPer($m, $c, $a); //权限范围内userIds
  2163. $userIds = array_intersect($map_user_ids, $perUserIds); //数组交集
  2164. $where[$field] = array('in', $userIds);
  2165. }
  2166. /**
  2167. * 获取客户浏览器类型
  2168. */
  2169. function getBrowser()
  2170. {
  2171. $Browser = $_SERVER['HTTP_USER_AGENT'];
  2172. if (preg_match('/MSIE/i', $Browser)) {
  2173. $Browser = 'MSIE';
  2174. } elseif (preg_match('/Firefox/i', $Browser)) {
  2175. $Browser = 'Firefox';
  2176. } elseif (preg_match('/Chrome/i', $Browser)) {
  2177. $Browser = 'Chrome';
  2178. } elseif (preg_match('/Safari/i', $Browser)) {
  2179. $Browser = 'Safari';
  2180. } elseif (preg_match('/Opera/i', $Browser)) {
  2181. $Browser = 'Opera';
  2182. } else {
  2183. $Browser = 'Other';
  2184. }
  2185. return $Browser;
  2186. }
  2187. /**
  2188. * 获取客户端系统
  2189. */
  2190. function getOS()
  2191. {
  2192. $agent = $_SERVER['HTTP_USER_AGENT'];
  2193. if (preg_match('/win/i', $agent)) {
  2194. if (preg_match('/nt 6.1/i', $agent)) {
  2195. $OS = 'Windows 7';
  2196. } else if (preg_match('/nt 6.2/i', $agent)) {
  2197. $OS = 'Windows 8';
  2198. } else if (preg_match('/nt 10.0/i', $agent)) {
  2199. $OS = 'Windows 10';
  2200. } else {
  2201. $OS = 'Windows';
  2202. }
  2203. } elseif (preg_match('/mac/i', $agent)) {
  2204. $OS = 'MAC';
  2205. } elseif (preg_match('/linux/i', $agent)) {
  2206. $OS = 'Linux';
  2207. } elseif (preg_match('/unix/i', $agent)) {
  2208. $OS = 'Unix';
  2209. } elseif (preg_match('/bsd/i', $agent)) {
  2210. $OS = 'BSD';
  2211. } else {
  2212. $OS = 'Other';
  2213. }
  2214. return $OS;
  2215. }
  2216. /**
  2217. * 根据IP获取地址
  2218. */
  2219. function getAddress($ip)
  2220. {
  2221. $res = file_get_contents("http://ip.360.cn/IPQuery/ipquery?ip=" . $ip);
  2222. $res = json_decode($res, 1);
  2223. if ($res && $res['errno'] == 0) {
  2224. return explode("\t", $res['data'])[0];
  2225. } else {
  2226. return '';
  2227. }
  2228. }
  2229. /**
  2230. * 下载服务器文件
  2231. *
  2232. * @param string $file 文件路径
  2233. * @param string $name 下载名称
  2234. * @param boolean $del 下载后删除
  2235. * @return void
  2236. * @author Ymob
  2237. */
  2238. function download($file, $name = '', $del = false)
  2239. {
  2240. if (!file_exists($file)) {
  2241. return resultArray([
  2242. 'error' => '文件不存在',
  2243. ]);
  2244. }
  2245. // 仅允许下载 public 目录下文件
  2246. $res = strpos(realpath($file), realpath('./public'));
  2247. if ($res !== 0) {
  2248. return resultArray([
  2249. 'error' => '文件路径错误',
  2250. ]);
  2251. }
  2252. $fp = fopen($file, 'r');
  2253. $size = filesize($file);
  2254. //下载文件需要的头
  2255. header("Content-type: application/octet-stream");
  2256. header("Accept-Ranges: bytes");
  2257. header('ResponseType: blob');
  2258. header("Accept-Length: $size");
  2259. $file_name = $name != '' ? $name : pathinfo($file, PATHINFO_BASENAME);
  2260. // urlencode 处理中文乱码
  2261. header("Content-Disposition:attachment; filename=" . urlencode($file_name));
  2262. // 导出数据时 csv office Excel 需要添加bom头
  2263. if (pathinfo($file, PATHINFO_EXTENSION) == 'csv') {
  2264. echo "\xEF\xBB\xBF"; // UTF-8 BOM
  2265. }
  2266. $fileCount = 0;
  2267. $fileUnit = 1024;
  2268. while (!feof($fp) && $size - $fileCount > 0) {
  2269. $fileContent = fread($fp, $fileUnit);
  2270. echo $fileContent;
  2271. $fileCount += $fileUnit;
  2272. }
  2273. fclose($fp);
  2274. // 删除
  2275. if ($del) @unlink($file);
  2276. die();
  2277. }
  2278. /**
  2279. * 临时目录生成文件名,并返回绝对路径
  2280. *
  2281. * @param string $ext 文件类型后缀
  2282. * @param string $path 临时文件目录 默认 ./public/temp/
  2283. * @return string $file_path 文件名称绝对路径
  2284. * @author ymob
  2285. */
  2286. function tempFileName($ext = '')
  2287. {
  2288. // 临时目录
  2289. $path = TEMP_DIR . date('Ymd') . DS;
  2290. if (!file_exists($path)) {
  2291. mkdir($path, 0777, true);
  2292. }
  2293. $ext = trim($ext, '.');
  2294. do {
  2295. $temp_file = md5(time() . rand(1000, 9999));
  2296. $file_path = $path . $temp_file . '.' . $ext;
  2297. } while (file_exists($file_path));
  2298. return $file_path;
  2299. }
  2300. /**
  2301. * 递归删除目录
  2302. *
  2303. * @param string $dir
  2304. * @return void
  2305. * @author Ymob
  2306. */
  2307. function delDir($dir)
  2308. {
  2309. $dh = opendir($dir);
  2310. while ($file = readdir($dh)) {
  2311. if ($file != "." && $file != "..") {
  2312. $fullpath = $dir . "/" . $file;
  2313. if (!is_dir($fullpath)) {
  2314. @unlink($fullpath);
  2315. } else {
  2316. deldir($fullpath);
  2317. }
  2318. }
  2319. }
  2320. closedir($dh);
  2321. //删除当前文件夹:
  2322. @rmdir($dir);
  2323. }
  2324. /**
  2325. * 商业智能 查询缓存
  2326. *
  2327. * @param string $sql Sql语句
  2328. * @param int $bi_slow_query_time 慢查询时间(毫秒),默认读取Config(bi_slow_query_time)
  2329. * @return mixed
  2330. * @author Ymob
  2331. * @datetime 2019-11-21 17:36:50
  2332. */
  2333. function queryCache($sql = '', $bi_slow_query_time = null)
  2334. {
  2335. $key = 'BI_queryCache' . md5($sql);
  2336. $val = cache($key);
  2337. if (!$val) {
  2338. $start_time = microtime(true) * 1000;
  2339. $val = Db::query($sql);
  2340. $end_time = microtime(true) * 1000;
  2341. $slow_query = true;
  2342. // 是否使用系统默认设置-慢查询时间
  2343. if ($bi_slow_query_time === null) {
  2344. $bi_slow_query_time = config('bi_slow_query_time');
  2345. }
  2346. if ($bi_slow_query_time > 0) {
  2347. $slow_query = ($end_time - $start_time) > $bi_slow_query_time;
  2348. }
  2349. if ($slow_query && $val) {
  2350. cache($key, $val, config('bi_cache_time'));
  2351. }
  2352. }
  2353. return $val;
  2354. }
  2355. /**
  2356. * 图表时间范围处理,按月/天返回时间段数组
  2357. *
  2358. * @param int $start 开始时间(时间戳)
  2359. * @param int $end 结束时间(时间戳)
  2360. * @return array
  2361. * @author Ymob
  2362. * @datetime 2019-11-18 09:25:09
  2363. */
  2364. function getTimeArray($start = null, $end = null)
  2365. {
  2366. if ($start == null || $end == null) {
  2367. $param = request()->param();
  2368. switch ($param['type']) {
  2369. // 本年
  2370. case 'year':
  2371. $start = strtotime(date('Y-01-01'));
  2372. $end = strtotime('+1 year', $start) - 1;
  2373. break;
  2374. // 去年
  2375. case 'lastYear':
  2376. $start = strtotime(date(date('Y') - 1 . '-01-01'));
  2377. $end = strtotime('+1 year', $start) - 1;
  2378. break;
  2379. // 本季度、上季度
  2380. case 'quarter':
  2381. case 'lastQuarter':
  2382. $t = intval((date('m') - 1) / 3);
  2383. $start_y = ($t * 3) + 1;
  2384. $start = strtotime(date("Y-{$start_y}-01"));
  2385. if ($param['type'] == 'lastQuarter') { // 上季度
  2386. $start = strtotime('-3 month', $start);
  2387. }
  2388. $end = strtotime('+3 month', $start) - 1;
  2389. break;
  2390. // 本月、上月
  2391. case 'month':
  2392. case 'lastMonth':
  2393. $start = strtotime(date('Y-m-01'));
  2394. if ($param['type'] == 'lastMonth') {
  2395. $start = strtotime('-1 month', $start);
  2396. }
  2397. $end = strtotime('+1 month', $start) - 1;
  2398. break;
  2399. // 本周、上周
  2400. case 'week':
  2401. case 'lastWeek':
  2402. $start = strtotime('-' . (date('w') - 1) . 'day', strtotime(date('Y-m-d')));
  2403. if ($param['type'] == 'lastWeek') {
  2404. $start = strtotime('-7 day', $start);
  2405. }
  2406. $end = strtotime('+7 day', $start) - 1;
  2407. break;
  2408. // 今天、昨天
  2409. case 'today':
  2410. case 'yesterday':
  2411. $start = strtotime(date('Y-m-d'));
  2412. if ($param['type'] == 'yesterday') {
  2413. $start = strtotime('-1 day', $start);
  2414. }
  2415. $end = strtotime('+1 day', $start) - 1;
  2416. break;
  2417. default:
  2418. if ($param['start_time'] && $param['end_time']) {
  2419. $start = $param['start_time'];
  2420. $end = $param['end_time'];
  2421. } else {
  2422. // 本年
  2423. $start = strtotime(date('Y-01-01'));
  2424. $end = strtotime('+1 year', $start) - 1;
  2425. }
  2426. break;
  2427. }
  2428. }
  2429. $between = [$start, $end];
  2430. $list = [];
  2431. $len = ($end - $start) / 86400;
  2432. // 大于30天 按月统计、小于按天统计
  2433. if ($len > 31) {
  2434. $time_format = '%Y-%m';
  2435. while (true) {
  2436. $start = strtotime(date('Y-m-01', $start));
  2437. $item = [];
  2438. $item['type'] = date('Y-m', $start);
  2439. $item['start_time'] = $start;
  2440. $item['end_time'] = strtotime('+1 month', $start) - 1;
  2441. $list[] = $item;
  2442. if ($item['end_time'] >= $end) break;
  2443. $start = $item['end_time'] + 1;
  2444. }
  2445. } else {
  2446. $time_format = '%Y-%m-%d';
  2447. while (true) {
  2448. $item = [];
  2449. $item['type'] = date('Y-m-d', $start);
  2450. $item['start_time'] = $start;
  2451. $item['end_time'] = strtotime('+1 day', $start) - 1;
  2452. $list[] = $item;
  2453. if ($item['end_time'] >= $end) break;
  2454. $start = $item['end_time'] + 1;
  2455. }
  2456. }
  2457. return [
  2458. 'list' => $list, // 时间段列表
  2459. 'time_format' => $time_format, // 时间格式 mysql 格式化时间戳
  2460. 'between' => $between // 开始结束时间
  2461. ];
  2462. }
  2463. /**
  2464. * 打印程序执行时间
  2465. *
  2466. * @param integer $s
  2467. * @return void
  2468. * @author Ymob
  2469. * @datetime 2019-11-28 09:31:45
  2470. */
  2471. function tt($s = 0)
  2472. {
  2473. die((string)round(microtime(1) - ($s ?: THINK_START_TIME), 3));
  2474. }
  2475. /**
  2476. * 数据库备份
  2477. */
  2478. function DBBackup($file = '', $path = '')
  2479. {
  2480. $type = config('database.type');
  2481. $host = config('database.hostname');
  2482. $port = config('database.hostport');
  2483. $dbname = config('database.database');
  2484. $username = config('database.username');
  2485. $password = config('database.password');
  2486. $dsn = "{$type}:host={$host};dbname={$dbname};port={$port}";
  2487. if ($file == '') {
  2488. $save_path = dirname(APP_PATH) . DS . 'data' . DS . date('Ym') . DS;
  2489. if (!file_exists($save_path) && !mkdir($save_path, '0777', true)) {
  2490. return 'data目录无写入权限';
  2491. }
  2492. $file = $save_path . date('d_H_i') . '_db_backup' . '.sql';
  2493. }
  2494. if (file_exists($file)) {
  2495. return '数据库备份文件已存在(自动备份时间间隔需大于1分钟)。';
  2496. }
  2497. try {
  2498. $backup = new \com\Mysqldump($dsn, $username, $password);
  2499. $backup->start($file);
  2500. return true;
  2501. } catch (\Exception $e) {
  2502. return '备份失败,请手动备份。错误原因:' . $e->getMessage();
  2503. }
  2504. }
  2505. /**
  2506. * 根据ip获取地址
  2507. */
  2508. function getAddressById($data)
  2509. {
  2510. $ip = new IpLocation();
  2511. $ip_address = $ip->getlocation($data);
  2512. return $ip_address;
  2513. }
  2514. if (!function_exists('isSuperAdministrators')) {
  2515. /**
  2516. * 判断是否是超级管理员
  2517. *
  2518. * @param $userId
  2519. * @return bool
  2520. */
  2521. function isSuperAdministrators($userId)
  2522. {
  2523. $status = false;
  2524. $apiCommon = new \app\admin\controller\ApiCommon();
  2525. $userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
  2526. $data = db('admin_access')->where('user_id', $userId)->column('group_id');
  2527. if ($userId == 1 || in_array(1, $data)) {
  2528. $status = true;
  2529. }
  2530. return $status;
  2531. }
  2532. }
  2533. if (!function_exists('getFieldGrantData')) {
  2534. /**
  2535. * 获取自动授权数据
  2536. *
  2537. * @return array
  2538. */
  2539. function getFieldGrantData($userId)
  2540. {
  2541. $result = [];
  2542. $apiCommon = new \app\admin\controller\ApiCommon();
  2543. $userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
  2544. $grantData = Db::query("
  2545. SELECT
  2546. `grant`.`module`, `grant`.`column`, `grant`.`content`
  2547. FROM
  2548. `5kcrm_admin_access` AS `access`
  2549. LEFT JOIN
  2550. `5kcrm_admin_group` AS `group` ON `access`.`group_id` = `group`.`id`
  2551. LEFT JOIN
  2552. `5kcrm_admin_field_grant` AS `grant` ON `group`.`id` = `grant`.`role_id`
  2553. WHERE
  2554. `access`.`user_id` =
  2555. " . $userId);
  2556. # 存在多角色多授权的情况
  2557. foreach ($grantData as $key => $value) {
  2558. if (empty($value['module']) || empty($value['column'])) continue;
  2559. $result[$value['module'] . '_' . $value['column']][] = !empty($value['content']) ? unserialize($value['content']) : [];
  2560. }
  2561. return $result;
  2562. }
  2563. }
  2564. if (!function_exists('getFieldGrantStatus')) {
  2565. /**
  2566. * 获取字段授权状态
  2567. *
  2568. * @param $field
  2569. * @param $grantData
  2570. * @return int[]
  2571. */
  2572. function getFieldGrantStatus($field, $grantData)
  2573. {
  2574. # 默认状态都是不能查看、不能编辑,通过配置来取最大权限。
  2575. $result = ['read' => 0, 'write' => 0,'maskType'=>0];
  2576. foreach ($grantData as $key => $value) {
  2577. $fieldBool = false;
  2578. foreach ($value as $ke => $va) {
  2579. # 多个字段授权,只取最高的读权限
  2580. if ($va['field'] == $field && $result['read'] == 0) {
  2581. $result['read'] = $va['read'] > $result['read'] ? $va['read'] : $result['read'];
  2582. }
  2583. # 多个字段授权,只取最高的写权限
  2584. if ($va['field'] == $field && $result['write'] == 0) {
  2585. $result['write'] = $va['write'] > $result['write'] ? $va['write'] : $result['write'];
  2586. }
  2587. if ($va['field'] == $field && $va['maskType'] != 0) {
  2588. $result['maskType'] = !empty($va['maskType'])?$va['maskType']:0;
  2589. }
  2590. if ($va['field'] == $field) $fieldBool = true;
  2591. }
  2592. # 对于不在权限控制之内的字段,将状态都改为1。
  2593. if (!$fieldBool) {
  2594. $result['read'] = 1;
  2595. $result['write'] = 1;
  2596. }
  2597. }
  2598. return $result;
  2599. }
  2600. }
  2601. /**
  2602. * 仪表盘日志使用
  2603. * 根据类型获取开始结束时间戳数组
  2604. * @param
  2605. */
  2606. function ByDateTime($type = 'today')
  2607. {
  2608. switch ($type) {
  2609. case 'yesterday' :
  2610. $timeArr = DataTime::yesterday();
  2611. $timeArr['last_time'] = DataTime::yesterday(1);
  2612. break;
  2613. case 'week' :
  2614. $timeArr = DataTime::week();
  2615. $timeArr['last_time'] = DataTime::lastWeek();
  2616. break;
  2617. case 'lastWeek' :
  2618. $timeArr = DataTime::lastWeek();
  2619. $timeArr['last_time'] = DataTime::lastWeek(1);
  2620. break;
  2621. case 'month' :
  2622. $timeArr = DataTime::month();
  2623. $timeArr['last_time'] = DataTime::lastMonth();
  2624. break;
  2625. case 'lastMonth' :
  2626. $timeArr = DataTime::lastMonth();
  2627. $timeArr['last_time'] = DataTime::lastMonth(1);
  2628. break;
  2629. case 'quarter' :
  2630. //本季度
  2631. $month = date('m');
  2632. if ($month == 1 || $month == 2 || $month == 3) {
  2633. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  2634. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  2635. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2636. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  2637. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  2638. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2639. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  2640. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  2641. } else {
  2642. $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
  2643. $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
  2644. }
  2645. //上季度
  2646. $month = date('m');
  2647. if ($month == 1 || $month == 2 || $month == 3) {
  2648. $year = date('Y') - 1;
  2649. $daterange_start_time_last_time = strtotime(date($year . '-10-01 00:00:00'));
  2650. $daterange_end_time_last_time = strtotime(date($year . '-12-31 23:59:59'));
  2651. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2652. $daterange_start_time_last_time = strtotime(date('Y-01-01 00:00:00'));
  2653. $daterange_end_time_last_time = strtotime(date("Y-03-31 23:59:59"));
  2654. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2655. $daterange_start_time_last_time = strtotime(date('Y-04-01 00:00:00'));
  2656. $daterange_end_time_last_time = strtotime(date("Y-06-30 23:59:59"));
  2657. } else {
  2658. $daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
  2659. $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
  2660. }
  2661. $timeArr = array($daterange_start_time, $daterange_end_time);
  2662. $timeArr['last_time'] = array($daterange_start_time_last_time, $daterange_end_time_last_time);
  2663. break;
  2664. case 'lastQuarter' :
  2665. //上季度
  2666. $month = date('m');
  2667. if ($month == 1 || $month == 2 || $month == 3) {
  2668. $year = date('Y') - 1;
  2669. $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
  2670. $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
  2671. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2672. $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
  2673. $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
  2674. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2675. $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
  2676. $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
  2677. } else {
  2678. $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
  2679. $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
  2680. }
  2681. //上季度
  2682. $month = date('m');
  2683. if ($month == 1 || $month == 2 || $month == 3) {
  2684. $year = date('Y') - 2;
  2685. $daterange_start_time_last_time = strtotime(date($year . '-10-01 00:00:00'));
  2686. $daterange_end_time_last_time = strtotime(date($year . '-12-31 23:59:59'));
  2687. } elseif ($month == 4 || $month == 5 || $month == 6) {
  2688. $daterange_start_time_last_time = strtotime(date('Y-01-01 00:00:00'));
  2689. $daterange_end_time_last_time = strtotime(date("Y-03-31 23:59:59"));
  2690. } elseif ($month == 7 || $month == 8 || $month == 9) {
  2691. $daterange_start_time_last_time = strtotime(date('Y-04-01 00:00:00'));
  2692. $daterange_end_time_last_time = strtotime(date("Y-06-30 23:59:59"));
  2693. } else {
  2694. $daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
  2695. $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
  2696. }
  2697. $timeArr = array($daterange_start_time, $daterange_end_time);
  2698. $timeArr['last_time'] = array($daterange_start_time_last_time, $daterange_end_time_last_time);
  2699. break;
  2700. case 'year' :
  2701. $timeArr = DataTime::year();
  2702. $timeArr['last_time'] = DataTime::lastYear();
  2703. break;
  2704. case 'lastYear' :
  2705. $timeArr = DataTime::lastYear();
  2706. $timeArr['last_time'] = DataTime::lastYear(1);
  2707. break;
  2708. case 'recent60' :
  2709. $timeArr = DataTime::recent60();
  2710. break;
  2711. case 'recent30' :
  2712. $timeArr = DataTime::recent30();
  2713. break;
  2714. default :
  2715. $timeArr = DataTime::today();
  2716. $timeArr['last_time'] = DataTime::yesterday();
  2717. break;
  2718. }
  2719. return $timeArr;
  2720. }
  2721. /**
  2722. * 系统操作日志
  2723. * @param int $user_id 用户
  2724. * @param string $types 方法所属模块
  2725. * @param int $action_id 操作
  2726. * @param string $module_name 模块
  2727. * @param string $action_name 修改添加删除新建
  2728. * @param array $oldData 旧数据
  2729. * @param array $newData 新数据
  2730. * @param string $target_name 被操作对象
  2731. * @param string $content 添加时创建使用
  2732. * @author alvin guogaobo
  2733. * @version 1.0 版本号
  2734. * @since 2021/3/26 0026 15:10
  2735. */
  2736. function SystemActionLog($user_id, $types, $module_name, $action_id, $action_name, $target_name, $oldData = [], $newData = [], $content = '')
  2737. {
  2738. //action_name 修改添加删除新建 action_id 操作id client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module_name 模块 系统管理 固定 user_id 用户
  2739. $data = [];
  2740. $data['user_id'] = $user_id;
  2741. $data['create_time'] = time();
  2742. $data['client_ip'] = request()->ip();
  2743. $data['action_id'] = $action_id;
  2744. $data['action_name'] = $action_name;
  2745. $data['target_name'] = $target_name;
  2746. $data['module_name'] = $module_name;
  2747. $data['controller_name'] = $types;
  2748. $data['content'] = $content;
  2749. db('admin_system_log')->insert($data);
  2750. }
  2751. /**
  2752. * 系统操作日志
  2753. * @param int $user_id 用户
  2754. * @param string $types 方法所属模块
  2755. * @param string $action_name 修改添加删除新建
  2756. * @param string $target_name 被操作对象
  2757. * @param array $oldData 旧数据
  2758. * @param array $newData 新数据
  2759. * @param string $content 添加时创建使用
  2760. * @author alvin guogaobo
  2761. * @version 1.0 版本号
  2762. * @since 2021/4/2 0026 15:10
  2763. */
  2764. function RecordActionLog($user_id, $types, $action_name, $target_name, $oldData = [], $newData = [], $content = '')
  2765. {
  2766. //action_name 修改 添加 删除 client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module 模块 user_id 用户
  2767. if (is_array($oldData) && is_array($newData) && $user_id) {
  2768. $differentData = array_diff_assoc($newData, $oldData);
  2769. $fieldModel = new FieldModel();
  2770. $userModel = new UserModel();
  2771. $structureModel = new \app\admin\model\Structure();
  2772. $field_arr = $fieldModel->getField(['types' => $types, 'unFormType' => ['file', 'form']]); //获取字段属性
  2773. $newFieldArr = array();
  2774. foreach ($field_arr as $k => $v) {
  2775. $newFieldArr[$v['field']] = $v;
  2776. }
  2777. $unField = ['update_time', 'create_time']; //定义过滤字段
  2778. $message = [];
  2779. $un_form_type = ['file', 'form'];
  2780. foreach ($differentData as $k => $v) {
  2781. if ($newFieldArr[$k] && !in_array($newFieldArr[$k]['form_type'], $un_form_type)) {
  2782. $field_name = '';
  2783. $field_name = $newFieldArr[$k]['name'];
  2784. $new_value = $v ?: '空';
  2785. $old_value = $oldData[$k] ?: '空';
  2786. switch ($newFieldArr[$k]['form_type']) {
  2787. case 'datetime' :
  2788. $new_value = $v ? date('Y-m-d', $v) : '';
  2789. $old_value = date('Y-m-d', $oldData[$k]);
  2790. if (!empty($v) && !empty($oldData[$k]))
  2791. break;
  2792. case 'user' :
  2793. $new_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($v))) : '';
  2794. $old_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($oldData[$k]))) : '';
  2795. break;
  2796. case 'structure' :
  2797. $new_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($v))) : '';
  2798. $old_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($oldData[$k]))) : '';
  2799. break;
  2800. case 'business_status' :
  2801. $new_value = $v ? db('crm_business_status')->where(['status_id' => $v])->value('name') : '';
  2802. $old_value = $v ? db('crm_business_status')->where(['status_id' => $oldData[$k]])->value('name') : '';
  2803. break;
  2804. case 'business_type' :
  2805. $new_value = $v ? db('crm_business_type')->where(['type_id' => $v])->value('name') : '';
  2806. $old_value = $v ? db('crm_business_type')->where(['type_id' => $oldData[$k]])->value('name') : '';
  2807. break;
  2808. case 'customer' :
  2809. $new_value = $v ? db('crm_customer')->where(['customer_id' => $v])->value('name') : '';
  2810. $old_value = $v ? db('crm_customer')->where(['customer_id' => $oldData[$k]])->value('name') : '';
  2811. break;
  2812. case 'category' :
  2813. $new_value = $v ? db('crm_product_category')->where(['category_id' => $v])->value('name') : '';
  2814. $old_value = $v ? db('crm_product_category')->where(['category_id' => $oldData[$k]])->value('name') : '';
  2815. break;
  2816. case 'business' :
  2817. $new_value = $v ? db('crm_business')->where(['business_id' => $v])->value('name') : '';
  2818. $old_value = $v ? db('crm_business')->where(['business_id' => $oldData[$k]])->value('name') : '';
  2819. break;
  2820. case 'visit' :
  2821. $new_value = $v ? db('crm_visit')->where(['visit_id' => $v])->value('number') : '';
  2822. $old_value = $v ? db('crm_visit')->where(['visit_id' => $oldData[$k]])->value('number') : '';
  2823. break;
  2824. case 'single_user' :
  2825. $new_value = $v ? db('admin_user')->where(['id' => $v])->value('realname') : '';
  2826. $old_value = $v ? db('admin_user')->where(['id' => $oldData['owner_user_id']])->value('realname') : '';
  2827. break;
  2828. case 'floatnumber' :
  2829. $new_value = $v ? number_format($v, 2) : '';
  2830. break;
  2831. }
  2832. if ($newFieldArr[$k]['field'] == 'check_status') {
  2833. $statusArr = ['0' => '待审核', '1' => '审核中', '2' => '审核通过', '3' => '已拒绝', '4' => '已撤回', '5' => '未提交'];
  2834. $new_value = $statusArr[$v];
  2835. $old_value = $statusArr[$oldData[$k]];
  2836. }
  2837. if ($old_value != $new_value) {
  2838. $message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
  2839. }
  2840. }
  2841. }
  2842. if ($message) {
  2843. $data = [];
  2844. $data['user_id'] = $user_id;
  2845. $data['create_time'] = time();
  2846. $data['client_ip'] = request()->ip();
  2847. $data['action_name'] = $action_name;
  2848. $data['action_id'] = 1;
  2849. $data['target_name'] = $target_name;
  2850. $data['module'] = $types; //子模块 客户线索
  2851. $data['content'] = implode(',', $message);
  2852. db('admin_operation_log')->insert($data);
  2853. }
  2854. } elseif ($content) {
  2855. $data = [];
  2856. $data['user_id'] = $user_id;
  2857. $data['create_time'] = time();
  2858. $data['client_ip'] = request()->ip();
  2859. $data['action_name'] = $action_name;
  2860. $data['target_name'] = $target_name;
  2861. $data['action_id'] = 1;
  2862. $data['module'] = $types; //子模块 客户线索
  2863. $data['content'] = $content;
  2864. db('admin_operation_log')->insert($data);
  2865. }
  2866. }
  2867. if (!function_exists('getFieldGroupOrderData')) {
  2868. /**
  2869. * 对自定义字段进行分组排序
  2870. *
  2871. * @param array $data 自定义字段数据
  2872. * @return array
  2873. * @since 2021-04-27
  2874. * @author fanqi
  2875. */
  2876. function getFieldGroupOrderData($data)
  2877. {
  2878. $formPositionEmpty = [];
  2879. $formPositionExist = [];
  2880. $result = [];
  2881. // 处理数据,将有位置信息和无位置信息的数据分开存放。
  2882. foreach ($data as $key => $value) {
  2883. if (empty($value['form_position'])) {
  2884. $formPositionEmpty[] = $value;
  2885. continue;
  2886. }
  2887. $formPositionArray = explode(',', $value['form_position']);
  2888. $x = (int)$formPositionArray[0];
  2889. $y = (int)$formPositionArray[1];
  2890. if (!isset($value['xaxis'])) $value['xaxis'] = $x;
  2891. if (!isset($value['yaxis'])) $value['yaxis'] = $y;
  2892. if ($value['form_type'] == 'date_interval' && !is_array($value['default_value'])) {
  2893. $value['default_value'] = !empty($value['default_value']) ? explode(',', $value['default_value']) : [];
  2894. }
  2895. $formPositionExist[$x][$y] = $value;
  2896. }
  2897. // 排序
  2898. ksort($formPositionExist);
  2899. // 处理有位置信息的数据
  2900. foreach ($formPositionExist as $key => $value) {
  2901. foreach ($value as $k => $v) {
  2902. if (!empty($formPositionExist[$key][$k])) $result[$key][$k] = $v;
  2903. }
  2904. $result[$key] = array_values($result[$key]);
  2905. }
  2906. // 将无位置信息的数据放置尾端
  2907. foreach ($formPositionEmpty as $key => $value) {
  2908. $result[] = [$value];
  2909. }
  2910. return array_values($result);
  2911. }
  2912. }
  2913. if (!function_exists('getPrimaryKeyName')) {
  2914. /**
  2915. * 获取主键
  2916. *
  2917. * @param string $types 栏目类型
  2918. * @return string
  2919. * @since 2021-05-18
  2920. * @author fanqi
  2921. */
  2922. function getPrimaryKeyName($types)
  2923. {
  2924. $primaryKey = '';
  2925. if ($types == 'crm_leads') $primaryKey = 'leads_id';
  2926. if ($types == 'crm_customer') $primaryKey = 'customer_id';
  2927. if ($types == 'crm_contacts') $primaryKey = 'contacts_id';
  2928. if ($types == 'crm_business') $primaryKey = 'business_id';
  2929. if ($types == 'crm_contract') $primaryKey = 'contract_id';
  2930. if ($types == 'crm_receivables') $primaryKey = 'receivables_id';
  2931. if ($types == 'crm_receivables_plan') $primaryKey = 'plan_id';
  2932. if ($types == 'crm_visit') $primaryKey = 'visit_id';
  2933. if ($types == 'crm_product') $primaryKey = 'product_id';
  2934. if ($types == 'crm_invoice') $primaryKey = 'invoice_id';
  2935. if ($types == 'oa_examine') $primaryKey = 'examine_id';
  2936. if ($types == 'jxc_product') $primaryKey = 'product_id';
  2937. if ($types == 'jxc_supplier') $primaryKey = 'supplier_id';
  2938. if ($types == 'jxc_purchase') $primaryKey = 'purchase_id';
  2939. if ($types == 'jxc_retreat') $primaryKey = 'retreat_id';
  2940. if ($types == 'jxc_sale') $primaryKey = 'sale_id';
  2941. if ($types == 'jxc_salereturn') $primaryKey = 'salereturn_id';
  2942. if ($types == 'jxc_receipt') $primaryKey = 'receipt_id';
  2943. if ($types == 'jxc_outbound') $primaryKey = 'outbound_id';
  2944. if ($types == 'jxc_payment') $primaryKey = 'payment_note_id';
  2945. if ($types == 'jxc_collection') $primaryKey = 'collection_note_id';
  2946. if ($types == 'jxc_inventory') $primaryKey = 'inventory_id';
  2947. if ($types == 'jxc_allocation') $primaryKey = 'allocation_id';
  2948. return $primaryKey;
  2949. }
  2950. }
  2951. function advancedQueryFormatForTeam($requestMap, $db, $db_id)
  2952. {
  2953. // 处理查询条件
  2954. foreach ($requestMap['team_id']['value'] as $v) {
  2955. if ($requestMap['team_id']['condition'] == 'contains') {
  2956. $date = function ($query) use ($v) {
  2957. $query->where('FIND_IN_SET("' . $v . '", ro_user_id)')
  2958. ->whereOr('FIND_IN_SET("' . $v . '", rw_user_id)');
  2959. };
  2960. } elseif ($requestMap['team_id']['condition'] == 'notContains') {
  2961. $date = function ($query) use ($v) {
  2962. $query->where('FIND_IN_SET("' . $v . '", ro_user_id)')
  2963. ->where('FIND_IN_SET("' . $v . '", rw_user_id)');
  2964. };
  2965. } elseif ($requestMap['team_id']['condition'] == 'isNull') {
  2966. $date = function ($query) {
  2967. $query->where('ro_user_id', ['eq', ''])
  2968. ->whereOr('rw_user_id', 'null');
  2969. };
  2970. } elseif ($requestMap['team_id']['condition'] == 'isNotNull') {
  2971. $date = function ($query) {
  2972. $query->where('ro_user_id', ['neq', ''])
  2973. ->where('rw_user_id', ['not null']);
  2974. };
  2975. }
  2976. $part[] = db($db)->where($date)->column($db_id);
  2977. }
  2978. $result = [];
  2979. array_walk_recursive($part, function ($value) use (&$result) {
  2980. array_push($result, $value);
  2981. });
  2982. $result = array_unique($result);
  2983. $partMap['customer.customer_id'] = ['in', trim(arrayToString($result), ',')];
  2984. return $partMap ?: [];
  2985. }