helpers.php 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750
  1. <?php
  2. use Illuminate\Support\Facades\Redis;
  3. use Illuminate\Support\Str;
  4. use Illuminate\Support\Arr;
  5. use app\common\services\PermissionService;
  6. use app\common\helpers\Url;
  7. use Ixudra\Curl\Facades\Curl;
  8. use app\common\models\user\WeiQingUsers;
  9. use app\common\services\Utils;
  10. use \app\platform\modules\system\models\SystemSetting;
  11. use \app\common\helpers\Client;
  12. use app\common\helpers\ImageHelper;
  13. if (!function_exists("yz_tpl_ueditor")) {
  14. function yz_tpl_ueditor($id, $value = '', $options = array())
  15. {
  16. if (config('app.framework') == 'platform') {
  17. $file_dir = '';
  18. } else {
  19. $file_dir = '../addons/yun_shop';
  20. }
  21. $s = '';
  22. $fileUploader = resource_get('static/js/fileUploader.min.js');
  23. if (!defined('TPL_INIT_UEDITOR')) {
  24. if (config('app.framework') == 'platform') {
  25. $s .= '<script type="text/javascript" src="' . $file_dir .'/app/common/components/ueditor/ueditor.config.js"></script><script type="text/javascript" src="' . $file_dir . '/app/common/components/ueditor/ueditor.all.min.js"></script><script type="text/javascript" src="' . $file_dir . '/app/common/components/ueditor/lang/zh-cn/zh-cn.js"></script><link href="/static/resource/components/webuploader/webuploader.css" rel="stylesheet"><link href="/static/resource/components/webuploader/style.css" rel="stylesheet">';
  26. } else {
  27. $s .= '<script type="text/javascript" src="' . $file_dir .'/app/common/components/ueditor/ueditor.config.js"></script><script type="text/javascript" src="' . $file_dir . '/app/common/components/ueditor/ueditor.all.min.js"></script><script type="text/javascript" src="' . $file_dir . '/app/common/components/ueditor/lang/zh-cn/zh-cn.js"></script><link href="/web/resource/components/webuploader/webuploader.css" rel="stylesheet"><link href="/web/resource/components/webuploader/style.css" rel="stylesheet">';
  28. }
  29. }
  30. $url = uploadUrl();
  31. $options['height'] = empty($options['height']) ? 200 : $options['height'];
  32. $s .= !empty($id) ? "<textarea id=\"{$id}\" name=\"{$id}\" type=\"text/plain\" style=\"height:{$options['height']}px;\">{$value}</textarea>" : '';
  33. $s .= "
  34. <script type=\"text/javascript\">
  35. var ueditoroption = {
  36. 'autoClearinitialContent' : false,
  37. 'toolbars' : [['fullscreen', 'source', 'preview', '|', 'bold', 'italic', 'underline', 'strikethrough', 'forecolor', 'backcolor', '|',
  38. 'justifyleft', 'justifycenter', 'justifyright', '|', 'insertorderedlist', 'insertunorderedlist', 'blockquote', 'emotion',
  39. 'link', 'removeformat', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight','indent', 'paragraph', 'fontsize', '|',
  40. 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol',
  41. 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|', 'anchor', 'map', 'print', 'drafts']],
  42. 'elementPathEnabled' : false,
  43. 'initialFrameHeight': {$options['height']},
  44. 'focus' : false,
  45. 'maximumWords' : 9999999999999
  46. };
  47. var opts = {
  48. type :'image',
  49. direct : false,
  50. multi : true,
  51. tabs : {
  52. 'upload' : 'active',
  53. 'browser' : '',
  54. 'crawler' : ''
  55. },
  56. path : '',
  57. dest_dir : '',
  58. global : false,
  59. thumb : false,
  60. width : 0
  61. };
  62. UE.registerUI('myinsertimage',function(editor,uiName){
  63. editor.registerCommand(uiName, {
  64. execCommand:function(){
  65. require(['fileUploader'], function(uploader){
  66. uploader.upload_url('".$url['upload_url']."');
  67. uploader.image_url('".$url['image_url']."');
  68. uploader.fetch_url('".$url['fetch_url']."');
  69. uploader.delet_url('".$url['delet_url']."');
  70. uploader.show(function(imgs){
  71. if (imgs.length == 0) {
  72. return;
  73. } else if (imgs.length == 1) {
  74. editor.execCommand('insertimage', {
  75. 'src' : imgs[0]['url'],
  76. '_src' : imgs[0]['attachment'],
  77. 'width' : '100%',
  78. 'alt' : imgs[0].filename
  79. });
  80. } else {
  81. var imglist = [];
  82. for (i in imgs) {
  83. imglist.push({
  84. 'src' : imgs[i]['url'],
  85. '_src' : imgs[i]['attachment'],
  86. 'width' : '100%',
  87. 'alt' : imgs[i].filename
  88. });
  89. }
  90. editor.execCommand('insertimage', imglist);
  91. }
  92. }, opts);
  93. });
  94. }
  95. });
  96. var btn = new UE.ui.Button({
  97. name: '插入图片',
  98. title: '插入图片',
  99. cssRules :'background-position: -726px -77px',
  100. onclick:function () {
  101. editor.execCommand(uiName);
  102. }
  103. });
  104. editor.addListener('selectionchange', function () {
  105. var state = editor.queryCommandState(uiName);
  106. if (state == -1) {
  107. btn.setDisabled(true);
  108. btn.setChecked(false);
  109. } else {
  110. btn.setDisabled(false);
  111. btn.setChecked(state);
  112. }
  113. });
  114. return btn;
  115. }, 19);
  116. UE.registerUI('myinsertvideo',function(editor,uiName){
  117. editor.registerCommand(uiName, {
  118. execCommand:function(){
  119. require(['".$fileUploader."'],
  120. function(uploader){
  121. uploader.upload_url('".$url['upload_url']."');
  122. uploader.image_url('".$url['image_url']."');
  123. uploader.fetch_url('".$url['fetch_url']."');
  124. uploader.delet_url('".$url['delet_url']."');
  125. uploader.video_url('".$url['video_url']."');
  126. uploader.show(function(video){
  127. if (!video) {
  128. return;
  129. } else {
  130. var videoType = video.isRemote ? 'iframe' : 'video';
  131. editor.execCommand('insertvideo', {
  132. 'url' : video.url,
  133. 'width' : '100%',
  134. 'height' : 200
  135. }, videoType);
  136. }
  137. }, {type:'video'});
  138. }
  139. );
  140. }
  141. });
  142. var btn = new UE.ui.Button({
  143. name: '插入视频',
  144. title: '插入视频',
  145. cssRules :'background-position: -320px -20px',
  146. onclick:function () {
  147. editor.execCommand(uiName);
  148. }
  149. });
  150. editor.addListener('selectionchange', function () {
  151. var state = editor.queryCommandState(uiName);
  152. if (state == -1) {
  153. btn.setDisabled(true);
  154. btn.setChecked(false);
  155. } else {
  156. btn.setDisabled(false);
  157. btn.setChecked(state);
  158. }
  159. });
  160. return btn;
  161. }, 20);
  162. " . (!empty($id) ? "
  163. $(function(){
  164. var ue = UE.getEditor('{$id}', ueditoroption);
  165. $('#{$id}').data('editor', ue);
  166. $('#{$id}').parents('form').submit(function() {
  167. if (ue.queryCommandState('source')) {
  168. ue.execCommand('source');
  169. }
  170. });
  171. });" : '') . "
  172. </script>";
  173. return $s;
  174. }
  175. }
  176. if (!function_exists("html_images")) {
  177. function html_images($detail = '')
  178. {
  179. $detail = htmlspecialchars_decode($detail);
  180. preg_match_all("/<img.*?src=[\'| \"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]?))[\'|\"].*?[\/]?>/", $detail, $imgs);
  181. $images = array();
  182. if (isset($imgs[1])) {
  183. foreach ($imgs[1] as $img) {
  184. $im = array(
  185. "old" => $img,
  186. "new" => save_media($img)
  187. );
  188. $images[] = $im;
  189. }
  190. }
  191. foreach ($images as $img) {
  192. $detail = str_replace($img['old'], $img['new'], $detail);
  193. }
  194. return $detail;
  195. }
  196. }
  197. if (!function_exists("xml_to_array")) {
  198. function xml_to_array($xml)
  199. {
  200. $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
  201. if (preg_match_all($reg, $xml, $matches)) {
  202. $count = count($matches[0]);
  203. for ($i = 0; $i < $count; $i++) {
  204. $subxml = $matches[2][$i];
  205. $key = $matches[1][$i];
  206. if (preg_match($reg, $subxml)) {
  207. $arr[$key] = xml_to_array($subxml);
  208. } else {
  209. $arr[$key] = $subxml;
  210. }
  211. }
  212. }
  213. return $arr;
  214. }
  215. }
  216. if (!function_exists("tomedia")) {
  217. /**
  218. * 获取附件的HTTP绝对路径
  219. * @param string $src 附件地址
  220. * @param bool $local_path 是否直接返回本地图片路径
  221. * @return string
  222. */
  223. function tomedia($src, $local_path = false)
  224. {
  225. if (empty($src)) {
  226. return '';
  227. }
  228. $local = strtolower($src);
  229. if (config('app.framework') == 'platform') {
  230. if (strexists($src, 'storage/')) {
  231. return request()->getSchemeAndHttpHost() . '/' . substr($src, strpos($src, 'storage/'));
  232. }
  233. //判断是否是本地带域名图片地址
  234. if (strexists($src, '/static/')) {
  235. if (strexists($local, 'http://') || strexists($local, 'https://') || substr($local, 0, 2) == '//') {
  236. return $src;
  237. } else {
  238. return request()->getSchemeAndHttpHost() . substr($src, strpos($src, '/static/'));
  239. }
  240. }
  241. } elseif (config('app.framework') != 'platform' && strexists($src, 'addons/')) {
  242. return request()->getSchemeAndHttpHost() . '/' . substr($src, strpos($src, 'addons/'));
  243. }
  244. //如果远程地址中包含本地host也检测是否远程图片
  245. if (strexists($src, request()->getSchemeAndHttpHost()) && !strexists($src, '/addons/')) {
  246. $urls = parse_url($src);
  247. $src = $t = substr($urls['path'], strpos($urls['path'], 'image'));
  248. }
  249. $t = strtolower($src);
  250. if (strexists($t, 'http://') || strexists($t, 'https://') || substr($t, 0, 2) == '//') {
  251. return $src;
  252. }
  253. if (config('app.framework') == 'platform') {
  254. $remote = SystemSetting::settingLoad('remote', 'system_remote');
  255. // $upload_type = \app\platform\modules\application\models\CoreAttach::where('attachment', $src)->first()['upload_type'];
  256. if (($local_path || !$remote['type']) && file_exists(base_path() . '/static/upload/' . $src)) {
  257. $src = request()->getSchemeAndHttpHost() . '/static/upload' . (strpos($src,'/') === 0 ? '':'/') . $src;
  258. } else {
  259. if ($remote['type'] == '2') {
  260. $src = $remote['alioss']['url'] . '/'. $src;
  261. } elseif ($remote['type'] == '4') {
  262. $src = $remote['cos']['url'] . '/'. $src;
  263. }
  264. }
  265. } else {
  266. if (($local_path || empty(YunShop::app()->setting['remote']['type'])) && file_exists(base_path('../../') . '/' . YunShop::app()->config['upload']['attachdir'] . '/' . $src)) {
  267. $src = request()->getSchemeAndHttpHost() . '/attachment/' . $src;
  268. } else {
  269. $src = YunShop::app()->attachurl_remote . $src;
  270. }
  271. }
  272. return $src;
  273. }
  274. }
  275. //内容审核,判断插件是否开启后,抛出事件去审核返回审核结果
  276. if (!function_exists("do_upload_verificaton")) {
  277. //file支持传入图片文件,文字,视频url,语音文件(多种类型:仅支持pcm、wav、amr、m4a),
  278. //type为固定值:img,text,video, audio_pcm(_wav,_amr,_m4a)
  279. function do_upload_verificaton($file,$type) {
  280. return event((new Yunshop\UploadVerification\service\UploadVerificationEvent($file,$type)));
  281. }
  282. }
  283. /**
  284. * 获取附件的HTTP绝对路径
  285. * @param string $src 附件地址
  286. * @param bool $local_path 是否直接返回本地图片路径
  287. * @param null $upload_type 上传图片时的类型,数据表 upload_type 字段(只需要在上传图片时,传参数,获取列表不需要传改参数)
  288. * @return string
  289. */
  290. function yz_tomedia($src, $local_path = false, $upload_type = null,$host = '')
  291. {
  292. if (empty($src)) {
  293. return '';
  294. }
  295. $HttpHost = request()->getSchemeAndHttpHost();
  296. if ($host) {
  297. $HttpHost = $host;
  298. }
  299. $setting = [];
  300. if (config('app.framework') == 'platform') {
  301. $systemSetting = app('SystemSetting');
  302. if ($remote = $systemSetting->get('remote')) {
  303. $setting[$remote['key']] = unserialize($remote['value']);
  304. }
  305. $upload_type = $setting['remote']['type'];
  306. $addons = '/storage/';
  307. $attachment = '/static/upload/';
  308. $file_name = 'photo-mr';
  309. $file_path = base_path($attachment) . $src;
  310. if (file_exists($file_path)) {//本地图片存在直接返回 示例图片path image/e3a555295b58e043dbf8ea3eb0434647.png
  311. return $HttpHost.$attachment . $src;
  312. }
  313. if (strexists($src, $attachment)) {//本地图片存在直接返回 示例图片path /static/upload/image/e3a555295b58e043dbf8ea3eb0434647.png
  314. $relative_path = substr($src, strpos($src, $attachment));
  315. $file_path = base_path($relative_path);
  316. if (file_exists($file_path)) {
  317. return $HttpHost.$relative_path;
  318. }
  319. }
  320. if (strexists($src, $file_name) && file_exists(base_path($src))) { //默认会员头像
  321. return $HttpHost.$src;
  322. }
  323. } else {
  324. //全局配置
  325. global $_W;
  326. //公众号独立配置信息 优先使用公众号独立配置
  327. $uni_setting = app('WqUniSetting')->get()->toArray();
  328. if (!empty($uni_setting['remote']) && iunserializer($uni_setting['remote'])['type'] != 0) {
  329. $setting['remote'] = iunserializer($uni_setting['remote']);
  330. $upload_type = $setting['remote']['type'];
  331. } else {
  332. $setting = $_W['setting'];
  333. $upload_type = $setting['remote']['type'];
  334. }
  335. $addons = '/addons/';
  336. $attachment = '/attachment/';
  337. $file_path = base_path('../../attachment/') . $src;
  338. if (file_exists($file_path)) {//本地图片存在直接返回 示例图片path image/e3a555295b58e043dbf8ea3eb0434647.png
  339. return $HttpHost.'/attachment/'.$src;
  340. }
  341. if (strexists($src, $attachment)) {//本地图片存在直接返回 示例图片path /attachment/image/e3a555295b58e043dbf8ea3eb0434647.png
  342. $relative_path = substr($src, strpos($src, $attachment));
  343. $file_path = base_path('../..'.$relative_path);
  344. if (file_exists($file_path)) {
  345. return $HttpHost.$relative_path;
  346. }
  347. }
  348. }
  349. $os = Client::osType();
  350. if (strexists($src, $addons)) {
  351. if ($os == Client::OS_TYPE_IOS) {
  352. $url_dz = $HttpHost . substr($src, strpos($src, $addons));
  353. return 'https:' . substr($url_dz, strpos($url_dz, '//'));
  354. }
  355. return $HttpHost . substr($src, strpos($src, $addons));
  356. }
  357. $local = strtolower($src);
  358. //todo 临时增加如果是插件图片
  359. if (strexists($src, "plugins/")) {
  360. $attachment = "/plugins/";
  361. if ($os == Client::OS_TYPE_IOS) {
  362. $url_dz = $HttpHost . substr($src, strpos($src, $attachment));
  363. return 'https:' . substr($url_dz, strpos($url_dz, '//'));
  364. }
  365. if (strexists($local, 'http://') || strexists($local, 'https://') || substr($local, 0, 2) == '//') {
  366. return $src;
  367. } else {
  368. return $HttpHost . substr($src, strpos($src, $attachment));
  369. }
  370. }
  371. //装修静态
  372. if (strexists($src, 'static/') && strexists($src, 'yunshop/')) {
  373. $path = substr($src, strpos($src, 'static/'));
  374. if (base_path($path)) {
  375. return $HttpHost.'/'.$path;
  376. }
  377. }
  378. $attach_url_remote = '';
  379. if ($upload_type) {
  380. switch ($upload_type) {
  381. case 1 :
  382. $attach_url_remote = $setting['remote']['ftp']['url'];
  383. break;
  384. case 2 :
  385. $attach_url_remote = $setting['remote']['alioss']['url'];
  386. break;
  387. case 3 :
  388. $attach_url_remote = $setting['remote']['qiniu']['url'];
  389. break;
  390. case 4 :
  391. $attach_url_remote = $setting['remote']['cos']['url'];
  392. break;
  393. case 5 :
  394. $attach_url_remote = $setting['remote']['obs']['url'];
  395. break;
  396. }
  397. }
  398. if (strexists($src, request()->getHost()) && strexists($src, $attachment) && $upload_type) {
  399. $host_str = $HttpHost.$attachment;
  400. $str_len = strlen($host_str);
  401. $relative_path = substr($src, $str_len);
  402. return $attach_url_remote .'/'. $relative_path;
  403. }
  404. //判断是否是本地不带域名图片地址
  405. if ((strexists($src, $attachment) && (parse_url($src)['scheme'].'://'.parse_url($src)['host']) == $HttpHost) || (strexists($src, $attachment) && !strexists($src, 'http://') && !strexists($src, 'https://'))) {
  406. if ($os == Client::OS_TYPE_IOS) {
  407. $url_dz = $HttpHost . substr($src, strpos($src, $attachment));
  408. return 'https:' . substr($url_dz, strpos($url_dz, '//'));
  409. }
  410. return $HttpHost . substr($src, strpos($src, $attachment));
  411. }
  412. //如果远程地址中包含本地host也检测是否远程图片
  413. if (strexists($local, 'http://') || strexists($local, 'https://') || substr($local, 0, 2) == '//') {
  414. if (strexists($local, 'http://')) {
  415. return 'http:' . substr($src, strpos($src, '//'));
  416. }
  417. if (strexists($local, 'https://')) {
  418. return 'https:' . substr($src, strpos($src, '//'));
  419. }
  420. return 'https:' . substr($src, strpos($src, '//'));
  421. }
  422. if ($upload_type) {
  423. return $attach_url_remote.'/'.$src;
  424. }
  425. if (preg_match('/^(\/\/){1}.*/',$src)) {
  426. return $src;
  427. }
  428. if (!config('app.debug')) {
  429. $src = 'https:' . substr($src, strpos($src, '//'));
  430. }
  431. return $src;
  432. }
  433. if (!function_exists("replace_yunshop")) {
  434. function replace_yunshop($url)
  435. {
  436. $moduleName = \Config::get('app.module_name');
  437. return str_replace(DIRECTORY_SEPARATOR . "addons" . DIRECTORY_SEPARATOR . $moduleName, "", $url);
  438. }
  439. }
  440. if (!function_exists("strexists")) {
  441. /**
  442. * 判断字符串是否包含子串
  443. * @param string $string 在该字符串中进行查找
  444. * @param string $find 需要查找的字符串
  445. * @return boolean
  446. */
  447. function strexists($string, $find)
  448. {
  449. return !(strpos($string, $find) === false);
  450. }
  451. }
  452. if (!function_exists("set_medias")) {
  453. function set_medias($list = array(), $fields = null)
  454. {
  455. if (empty($fields)) {
  456. foreach ($list as &$row) {
  457. $row = yz_tomedia($row);
  458. }
  459. return $list;
  460. }
  461. if (!is_array($fields)) {
  462. $fields = explode(',', $fields);
  463. }
  464. if (is_array2($list)) {
  465. foreach ($list as $key => &$value) {
  466. foreach ($fields as $field) {
  467. if (isset($list[$field])) {
  468. $list[$field] = yz_tomedia($list[$field]);
  469. }
  470. if (is_array($value) && isset($value[$field])) {
  471. $value[$field] = yz_tomedia($value[$field]);
  472. }
  473. }
  474. }
  475. return $list;
  476. } else {
  477. foreach ($fields as $field) {
  478. if (isset($list[$field])) {
  479. $list[$field] = yz_tomedia($list[$field]);
  480. }
  481. }
  482. return $list;
  483. }
  484. }
  485. }
  486. if (!function_exists('is_array2')) {
  487. function is_array2($array)
  488. {
  489. if (is_array($array)) {
  490. foreach ($array as $k => $v) {
  491. return is_array($v);
  492. }
  493. return false;
  494. }
  495. return false;
  496. }
  497. }
  498. if (!function_exists("show_json")) {
  499. function show_json($status = 1, $return = null, $variable = null)
  500. {
  501. $ret = array(
  502. 'status' => $status
  503. );
  504. if ($return) {
  505. $ret['result'] = $return;
  506. }
  507. if (Yunshop::isApi()) {
  508. return array(
  509. 'status' => $status,
  510. 'variable' => $variable,
  511. 'json' => $return,
  512. );
  513. }
  514. die(json_encode($ret));
  515. }
  516. }
  517. if (!function_exists("array_column")) {
  518. function array_column($input = null, $columnKey = null, $indexKey = null)
  519. {
  520. // Using func_get_args() in order to check for proper number of
  521. // parameters and trigger errors exactly as the built-in array_column()
  522. // does in PHP 5.5.
  523. $argc = func_num_args();
  524. $params = func_get_args();
  525. if ($argc < 2) {
  526. trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);
  527. return null;
  528. }
  529. if (!is_array($params[0])) {
  530. trigger_error(
  531. 'array_column() expects parameter 1 to be array, ' . gettype($params[0]) . ' given',
  532. E_USER_WARNING
  533. );
  534. return null;
  535. }
  536. if (!is_int($params[1])
  537. && !is_float($params[1])
  538. && !is_string($params[1])
  539. && $params[1] !== null
  540. && !(is_object($params[1]) && method_exists($params[1], '__toString'))
  541. ) {
  542. trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING);
  543. return false;
  544. }
  545. if (isset($params[2])
  546. && !is_int($params[2])
  547. && !is_float($params[2])
  548. && !is_string($params[2])
  549. && !(is_object($params[2]) && method_exists($params[2], '__toString'))
  550. ) {
  551. trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING);
  552. return false;
  553. }
  554. $paramsInput = $params[0];
  555. $paramsColumnKey = ($params[1] !== null) ? (string)$params[1] : null;
  556. $paramsIndexKey = null;
  557. if (isset($params[2])) {
  558. if (is_float($params[2]) || is_int($params[2])) {
  559. $paramsIndexKey = (int)$params[2];
  560. } else {
  561. $paramsIndexKey = (string)$params[2];
  562. }
  563. }
  564. $resultArray = array();
  565. foreach ($paramsInput as $row) {
  566. $key = $value = null;
  567. $keySet = $valueSet = false;
  568. if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
  569. $keySet = true;
  570. $key = (string)$row[$paramsIndexKey];
  571. }
  572. if ($paramsColumnKey === null) {
  573. $valueSet = true;
  574. $value = $row;
  575. } elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
  576. $valueSet = true;
  577. $value = $row[$paramsColumnKey];
  578. }
  579. if ($valueSet) {
  580. if ($keySet) {
  581. $resultArray[$key] = $value;
  582. } else {
  583. $resultArray[] = $value;
  584. }
  585. }
  586. }
  587. return $resultArray;
  588. }
  589. }
  590. if (!function_exists('shop_template_compile')) {
  591. function shop_template_compile($from, $to, $inmodule = false)
  592. {
  593. $path = dirname($to);
  594. \app\common\services\Utils::mkdirs($path);
  595. $content = shop_template_parse(file_get_contents($from), $inmodule);
  596. file_put_contents($to, $content);
  597. }
  598. }
  599. if (!function_exists('shop_template_parse')) {
  600. function shop_template_parse($str, $inmodule = false)
  601. {
  602. $str = template_parse($str, $inmodule);
  603. $str = preg_replace('/{ifp\s+(.+?)}/', '<?php if(cv($1)) { ?>', $str);
  604. $str = preg_replace('/{ifpp\s+(.+?)}/', '<?php if(cp($1)) { ?>', $str);
  605. $str = preg_replace('/{ife\s+(\S+)\s+(\S+)}/', '<?php if( ce($1 ,$2) ) { ?>', $str);
  606. return $str;
  607. }
  608. }
  609. if (!function_exists('objectArray')) {
  610. function objectArray($array)
  611. {
  612. if (is_object($array)) {
  613. $array = (array)$array;
  614. }
  615. if (is_array($array)) {
  616. foreach ($array as $key => $value) {
  617. $array[$key] = objectArray($value);
  618. }
  619. }
  620. return $array;
  621. }
  622. }
  623. if (!function_exists('my_link_extra')) {
  624. function my_link_extra($type = 'content')
  625. {
  626. $content = "";
  627. $extraContents = [];
  628. Event::dispatch(new app\common\events\RenderingMyLink($extraContents));
  629. return $type == 'content' ? $content . implode("\n", $extraContents) : implode("\n",
  630. array_keys($extraContents));
  631. }
  632. }
  633. if (!function_exists('can')) {
  634. /**
  635. * 权限判断
  636. * @param $item 可以是item 或者是route
  637. * @param bool $isRoute
  638. * @return bool
  639. */
  640. function can($itemRoute, $isRoute = false)
  641. {
  642. /*if(config('app.menu_key') != 'menu'){
  643. return true;
  644. }*/
  645. if ($isRoute == true) {
  646. $item = \app\common\models\Menu::getItemByRoute($itemRoute);
  647. } else {
  648. $item = $itemRoute;
  649. }
  650. return PermissionService::can($item);
  651. }
  652. }
  653. if (!function_exists('weAccount')) {
  654. /**
  655. * 获取微擎账号体系
  656. * @return NULL|WeAccount
  657. */
  658. function weAccount()
  659. {
  660. /* load()->model('account');
  661. return WeAccount::create();*/
  662. }
  663. }
  664. if (!function_exists('yzWebUrl')) {
  665. function yzWebUrl($route, $params = [])
  666. {
  667. return Url::web($route, $params);
  668. }
  669. }
  670. if (!function_exists('yzAppUrl')) {
  671. function yzAppUrl($route, $params = [])
  672. {
  673. return Url::app($route, $params);
  674. }
  675. }
  676. if (!function_exists('yzApiUrl')) {
  677. function yzApiUrl($route, $params = [])
  678. {
  679. return Url::api($route, $params);
  680. }
  681. }
  682. if (!function_exists('yzPluginUrl')) {
  683. function yzPluginUrl($route, $params = [])
  684. {
  685. return Url::plugin($route, $params);
  686. }
  687. }
  688. if (!function_exists('yzPluginFullUrl')) {
  689. function yzPluginFullUrl($route, $params = [])
  690. {
  691. return Url::absolutePlugin($route, $params);
  692. }
  693. }
  694. if (!function_exists('yzWebFullUrl')) {
  695. function yzWebFullUrl($route, $params = [])
  696. {
  697. return Url::absoluteWeb($route, $params);
  698. }
  699. }
  700. if (!function_exists('yzAppFullUrl')) {
  701. function yzAppFullUrl($route, $params = [])
  702. {
  703. return Url::absoluteApp($route, $params);
  704. }
  705. }
  706. if (!function_exists('yzBusinessFullUrl')) {
  707. function yzBusinessFullUrl($route, $params = [])
  708. {
  709. return request()->getSchemeAndHttpHost() . '/' . yzBusinessUrl($route, $params);
  710. }
  711. }
  712. if (!function_exists('yzBusinessUrl')) {
  713. function yzBusinessUrl($route, $params = [])
  714. {
  715. if (!$params['i']) $params = array_merge(['i' => YunShop::app()->uniacid], $params);
  716. return 'business/business_font/#/' . $route . '?' . http_build_query($params);
  717. }
  718. }
  719. if (!function_exists('yzDiyFullUrl')) {
  720. function yzDiyFullUrl($route, $params = [])
  721. {
  722. return Url::absoluteDiyApp($route, $params);
  723. }
  724. }
  725. if (!function_exists('yzUrl')) {
  726. function yzUrl($route, $params = [])
  727. {
  728. return Url::web($route, $params);
  729. }
  730. }
  731. if (!function_exists('array_child_kv_exists')) {
  732. function array_child_kv_exists($array, $childKey, $value)
  733. {
  734. $result = false;
  735. if (is_array($array)) {
  736. foreach ($array as $v) {
  737. if (is_array($v) && isset($v[$childKey])) {
  738. $result += $v[$childKey] == $value;
  739. }
  740. }
  741. }
  742. return $result;
  743. }
  744. }
  745. if (!function_exists('widget')) {
  746. function widget($class, $params = [])
  747. {
  748. return (new $class($params))->run();
  749. }
  750. }
  751. if (!function_exists('assets')) {
  752. function assets($relativeUri)
  753. {
  754. // add query string to fresh cache
  755. if (Str::startsWith($relativeUri, 'styles') || Str::startsWith($relativeUri, 'scripts')) {
  756. return Url::shopUrl("resources/assets/dist/$relativeUri") . "?v=" . config('app.version');
  757. } elseif (Str::startsWith($relativeUri, 'lang')) {
  758. return Url::shopUrl("resources/$relativeUri");
  759. } else {
  760. return Url::shopUrl("resources/assets/$relativeUri");
  761. }
  762. }
  763. }
  764. if (!function_exists('static_url')) {
  765. function static_url($relativeUri)
  766. {
  767. return Url::shopUrl('static/' . $relativeUri);
  768. }
  769. }
  770. if (!function_exists('plugin')) {
  771. function plugin($id)
  772. {
  773. return app('plugins')->getPlugin($id);
  774. }
  775. }
  776. if (!function_exists('plugin_assets')) {
  777. function plugin_assets($id, $relativeUri)
  778. {
  779. if ($plugin = plugin($id)) {
  780. return $plugin->assets($relativeUri);
  781. } else {
  782. throw new InvalidArgumentException("No such plugin.");
  783. }
  784. }
  785. }
  786. if (!function_exists('json')) {
  787. function json()
  788. {
  789. $args = func_get_args();
  790. if (count($args) == 1 && is_array($args[0])) {
  791. return Response::json($args[0]);
  792. } elseif (count($args) == 3 && is_array($args[2])) {
  793. // the third argument is array of extra fields
  794. return Response::json(array_merge([
  795. 'errno' => $args[1],
  796. 'msg' => $args[0]
  797. ], $args[2]));
  798. } else {
  799. return Response::json([
  800. 'errno' => Arr::get($args, 1, 1),
  801. 'msg' => $args[0]
  802. ]);
  803. }
  804. }
  805. }
  806. if (!function_exists('yz_footer')) {
  807. function yz_footer($page_identification = "")
  808. {
  809. $content = "";
  810. /*
  811. $scripts = [
  812. assets('scripts/app.min.js'),
  813. assets('lang/'.config('app.locale').'/locale.js'),
  814. ];
  815. if ($page_identification !== "") {
  816. $scripts[] = assets("scripts/$page_identification.js");
  817. }
  818. foreach ($scripts as $script) {
  819. $content .= "<script type=\"text/javascript\" src=\"$script\"></script>\n";
  820. }
  821. */
  822. $customJs = option("custom_js");
  823. $customJs && $content .= '<script>' . $customJs . '</script>';
  824. $extraContents = [];
  825. Event::dispatch(new app\common\events\RenderingFooter($extraContents));
  826. return $content . implode("\n", $extraContents);
  827. }
  828. }
  829. if (!function_exists('yz_header')) {
  830. function yz_header($pageIdentification = "")
  831. {
  832. $content = "";
  833. /*
  834. $styles = [
  835. assets('styles/app.min.css'),
  836. assets('styles/skins/'.Option::get('color_scheme').'.min.css')
  837. ];
  838. if ($pageIdentification !== "") {
  839. $styles[] = assets("styles/$pageIdentification.css");
  840. }
  841. foreach ($styles as $style) {
  842. $content .= "<link rel=\"stylesheet\" href=\"$style\">\n";
  843. }
  844. */
  845. $customCss = option("custom_css");
  846. $customCss && $content .= '<style>' . option("custom_css") . '</style>';
  847. $extraContents = [];
  848. Event::dispatch(new app\common\events\RenderingHeader($extraContents));
  849. return $content . implode("\n", $extraContents);
  850. }
  851. }
  852. if (!function_exists('yz_menu')) {
  853. function yz_menu($type)
  854. {
  855. $menu = \app\backend\modules\menu\Menu::current()->getItems();
  856. Event::dispatch($type == "member" ? new app\common\events\ConfigureMemberMenu($menu)
  857. : new app\common\events\ConfigureAdminMenu($menu));
  858. if (!isset($menu[$type])) {
  859. throw new InvalidArgumentException;
  860. }
  861. return yz_menu_render($menu[$type]);
  862. }
  863. function yz_menu_render($data)
  864. {
  865. $content = "";
  866. foreach ($data as $key => $value) {
  867. $active = app('request')->is(@$value['link']);
  868. // also set parent as active if any child is active
  869. foreach ((array)@$value['children'] as $childKey => $childValue) {
  870. if (app('request')->is(@$childValue['link'])) {
  871. $active = true;
  872. }
  873. }
  874. $content .= $active ? '<li class="active">' : '<li>';
  875. if (isset($value['children'])) {
  876. $content .= '<a href="#"><i class="fa ' . $value['icon'] . '"></i> <span>' . trans($value['title']) . '</span><span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span></a>';
  877. // recurse
  878. $content .= '<ul class="treeview-menu" style="display: none;">' . yz_menu_render($value['children']) . '</ul>';
  879. } else {
  880. $content .= '<a href="' . url($value['link']) . '"><i class="fa ' . $value['icon'] . '"></i> <span>' . trans($value['title']) . '</span></a>';
  881. }
  882. $content .= '</li>';
  883. }
  884. return $content;
  885. }
  886. }
  887. if (!function_exists('option')) {
  888. /**
  889. * Get / set the specified option value.
  890. *
  891. * If an array is passed as the key, we will assume you want to set an array of values.
  892. *
  893. * @param array|string $key
  894. * @param mixed $default
  895. * @param raw $raw return raw value without convertion
  896. * @return mixed
  897. */
  898. function option($key = null, $default = null, $raw = false)
  899. {
  900. $options = app('options');
  901. if (is_null($key)) {
  902. return $options;
  903. }
  904. if (is_array($key)) {
  905. foreach ($key as $innerKey => $innerValue) {
  906. $options->set($innerKey, $innerValue);
  907. }
  908. return;
  909. }
  910. //$optionsData = $options->get();
  911. //return $optionsData[$key]['option_value'];
  912. return array_get($options->all(),$key, $default)['option_value'];
  913. }
  914. }
  915. if (!function_exists('float_greater')) {
  916. function float_greater($number, $other_number)
  917. {
  918. return bccomp($number, $other_number) === 1;
  919. }
  920. }
  921. if (!function_exists('float_lesser')) {
  922. function float_lesser($number, $other_number)
  923. {
  924. return bccomp($number, $other_number) === -1;
  925. }
  926. }
  927. if (!function_exists('float_equal')) {
  928. function float_equal($number, $other_number)
  929. {
  930. return bccomp($number, $other_number) === 0;
  931. }
  932. }
  933. if (!function_exists('sdd')) {
  934. function sdd()
  935. {
  936. global $testDd;
  937. $testDd = !$testDd;
  938. }
  939. }
  940. if (!function_exists('tdd')) {
  941. function tdd()
  942. {
  943. global $testDd;
  944. if ($testDd) {
  945. dd(func_get_args());
  946. }
  947. }
  948. }
  949. /*
  950. * 生成一个随机订单号:如果需要唯一性,请自己验证重复调用
  951. *
  952. * @params string $prefix 标示 SN RV
  953. * @params bool $numeric 是否为纯数字
  954. *
  955. * @return mixed
  956. * @Author yitian */
  957. if (!function_exists('createNo')) {
  958. function createNo($prefix, $length = 6, $numeric = FALSE)
  959. {
  960. return $prefix . date('YmdHis') . Client::random($length, $numeric);
  961. }
  962. }
  963. if (!function_exists('yz_array_set')) {
  964. function yz_array_set($array, $key, $value)
  965. {
  966. $keys = explode('.', $key);
  967. while (count($keys) > 1) {
  968. $key = array_shift($keys);
  969. // If the key doesn't exist at this depth, we will just create an empty array
  970. // to hold the next value, allowing us to create the arrays to hold final
  971. // values at the correct depth. Then we'll keep digging into the array.
  972. if (!isset($array[$key]) || !is_array($array[$key])) {
  973. $array[$key] = [];
  974. }
  975. $array = &$array[$key];
  976. }
  977. $array[array_shift($keys)] = $value;
  978. return $array;
  979. }
  980. }
  981. if (!function_exists('trace_log')) {
  982. /**
  983. * @return \Illuminate\Foundation\Application|mixed
  984. */
  985. function trace_log(){
  986. return app('Log.trace');
  987. }
  988. }
  989. if (!function_exists('debug_log')) {
  990. /**
  991. * @return \Illuminate\Foundation\Application|mixed
  992. */
  993. function debug_log(){
  994. return app('Log.debug');
  995. }
  996. }
  997. if (!function_exists('randNum')) {
  998. /**
  999. * 获取随机字符串
  1000. * @param number $length 字符串长度
  1001. * @param boolean $numeric 是否为纯数字
  1002. * @return string
  1003. */
  1004. function randNum($length, $numeric = FALSE) {
  1005. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  1006. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  1007. if ($numeric) {
  1008. $hash = '';
  1009. } else {
  1010. $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
  1011. $length--;
  1012. }
  1013. $max = strlen($seed) - 1;
  1014. for ($i = 0; $i < $length; $i++) {
  1015. $hash .= $seed[mt_rand(0, $max)];
  1016. }
  1017. return $hash;
  1018. }
  1019. }
  1020. if (!function_exists('file_random_name')) {
  1021. function file_random_name($dir, $ext)
  1022. {
  1023. do {
  1024. $filename = random(30) . '.' . $ext;
  1025. } while (file_exists($dir . $filename));
  1026. return $filename;
  1027. }
  1028. }
  1029. if (!function_exists('random')) {
  1030. function random($length, $numeric = FALSE)
  1031. {
  1032. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  1033. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  1034. if ($numeric) {
  1035. $hash = '';
  1036. } else {
  1037. $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
  1038. $length--;
  1039. }
  1040. $max = strlen($seed) - 1;
  1041. for ($i = 0; $i < $length; $i++) {
  1042. $hash .= $seed[mt_rand(0, $max)];
  1043. }
  1044. return $hash;
  1045. }
  1046. }
  1047. if (!function_exists('is_error')) {
  1048. function is_error($data)
  1049. {
  1050. if (empty($data) || !is_array($data) || !array_key_exists('errno', $data) || (array_key_exists('errno', $data) && $data['errno'] == 0)) {
  1051. return false;
  1052. } else {
  1053. return true;
  1054. }
  1055. }
  1056. }
  1057. if (!function_exists('file_image_quality')) {
  1058. function file_image_quality($src, $to_path, $ext, $global)
  1059. {
  1060. $quality = intval($global['zip_percentage']);
  1061. if ($quality <= 0 || $quality >= 100) {
  1062. return;
  1063. }
  1064. if (filesize($src) / 1024 > 5120) {
  1065. return;
  1066. }
  1067. $result = \app\platform\modules\system\models\Image::create($src, $ext)->saveTo($to_path, $quality);
  1068. return $result;
  1069. }
  1070. }
  1071. if (!function_exists('safe_gpc_path')) {
  1072. function safe_gpc_path($value, $default = '') {
  1073. $path = safe_gpc_string($value);
  1074. $path = str_replace(array('..', '..\\', '\\\\' ,'\\', '..\\\\'), '', $path);
  1075. if (!$path || $path != $value) {
  1076. $path = $default;
  1077. }
  1078. return $path;
  1079. }
  1080. }
  1081. if (!function_exists('safe_gpc_string')) {
  1082. function safe_gpc_string($value, $default = '')
  1083. {
  1084. $value = safe_bad_str_replace($value);
  1085. $value = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $value);
  1086. if (empty($value) && $default != $value) {
  1087. $value = $default;
  1088. }
  1089. return $value;
  1090. }
  1091. }
  1092. if (!function_exists('array_elements')) {
  1093. function array_elements($keys, $src, $default = FALSE)
  1094. {
  1095. $return = array();
  1096. if (!is_array($keys)) {
  1097. $keys = array($keys);
  1098. }
  1099. foreach ($keys as $key) {
  1100. if (isset($src[$key])) {
  1101. $return[$key] = $src[$key];
  1102. } else {
  1103. $return[$key] = $default;
  1104. }
  1105. }
  1106. return $return;
  1107. }
  1108. }
  1109. if (!function_exists('sizecount')) {
  1110. function sizecount($size)
  1111. {
  1112. if ($size >= 1073741824) {
  1113. $size = round($size / 1073741824 * 100) / 100 . ' GB';
  1114. } elseif ($size >= 1048576) {
  1115. $size = round($size / 1048576 * 100) / 100 . ' MB';
  1116. } elseif ($size >= 1024) {
  1117. $size = round($size / 1024 * 100) / 100 . ' KB';
  1118. } else {
  1119. $size = $size . ' Bytes';
  1120. }
  1121. return $size;
  1122. }
  1123. }
  1124. if (!function_exists('file_image_thumb')) {
  1125. function file_image_thumb($srcfile, $desfile = '', $width = 0, $global)
  1126. {
  1127. if (intval($width) == 0) {
  1128. $width = intval($global['thumb_width']);
  1129. }
  1130. if (!$desfile) {
  1131. $ext = pathinfo($srcfile, PATHINFO_EXTENSION);
  1132. $srcdir = dirname($srcfile);
  1133. do {
  1134. $desfile = $srcdir . '/' . random(30) . ".{$ext}";
  1135. } while (file_exists($desfile));
  1136. }
  1137. $des = dirname($desfile);
  1138. if (!file_exists($des)) {
  1139. if (!\app\common\services\Utils::mkdirs($des)) {
  1140. return 1;
  1141. }
  1142. } elseif (!is_writable($des)) {
  1143. return 2;
  1144. }
  1145. $org_info = @getimagesize($srcfile);
  1146. if ($org_info) {
  1147. if ($width == 0 || $width > $org_info[0]) {
  1148. copy($srcfile, $desfile);
  1149. return str_replace(base_path() . '/static/upload/', '', $desfile);
  1150. }
  1151. }
  1152. $scale_org = $org_info[0] / $org_info[1];
  1153. $height = $width / $scale_org;
  1154. $desfile = \app\platform\modules\system\models\Image::create($srcfile)->resize($width, $height)->saveTo($desfile);
  1155. if (!$desfile) {
  1156. return false;
  1157. }
  1158. return str_replace(base_path() . '/static/upload/', '', $desfile);
  1159. }
  1160. }
  1161. if (!function_exists('file_is_image')) {
  1162. function file_is_image($url)
  1163. {
  1164. if (!parse_path($url)) {
  1165. return false;
  1166. }
  1167. $pathinfo = pathinfo($url);
  1168. $extension = strtolower($pathinfo['extension']);
  1169. return !empty($extension) && in_array($extension, array('jpg', 'jpeg', 'gif', 'png'));
  1170. }
  1171. }
  1172. if (!function_exists('file_remote_upload_wq')) {
  1173. function file_remote_upload_wq($filename, $auto_delete_local = true, $remote = [], $frontend = false)
  1174. {
  1175. // $filename 文件名
  1176. // $auto_delete_local 是否自动删除本地资源 true 删除 false 不删除
  1177. // $remote 远程配置信息
  1178. if (!empty($remote)) {
  1179. $remote_setting = $remote;
  1180. $upload_type = $remote['type'];
  1181. } else {
  1182. global $_W;
  1183. $remote_setting = $_W['setting']['remote'];
  1184. $upload_type = $_W['setting']['remote']['type'];
  1185. }
  1186. if (empty($upload_type)) {
  1187. return false;
  1188. }
  1189. if ($upload_type == '1') {
  1190. $ftp_config = array(
  1191. 'hostname' => $remote_setting['ftp']['host'],
  1192. 'username' => $remote_setting['ftp']['username'],
  1193. 'password' => $remote_setting['ftp']['password'],
  1194. 'port' => $remote_setting['ftp']['port'],
  1195. 'ssl' => $remote_setting['ftp']['ssl'],
  1196. 'passive' => $remote_setting['ftp']['pasv'],
  1197. 'timeout' => $remote_setting['ftp']['timeout'],
  1198. 'rootdir' => $remote_setting['ftp']['dir'],
  1199. );
  1200. load()->library('ftp');
  1201. $ftp = new Ftp($ftp_config);
  1202. if (true === $ftp->connect()) {
  1203. $response = $ftp->upload(ATTACHMENT_ROOT . $filename, $filename);
  1204. if ($auto_delete_local) {
  1205. file_deletes($filename);
  1206. }
  1207. if (!empty($response)) {
  1208. return true;
  1209. } else {
  1210. return error(1, '远程附件上传失败,请检查配置并重新上传');
  1211. }
  1212. } else {
  1213. return error(1, '远程附件上传失败,请检查配置并重新上传');
  1214. }
  1215. } elseif ($upload_type == '2') {
  1216. $buckets = attachment_alioss_buctkets($remote_setting['alioss']['key'], $remote_setting['alioss']['secret']);
  1217. $endpoint = 'http://' . $buckets[$remote_setting['alioss']['bucket']]['location'] . '.aliyuncs.com';
  1218. try {
  1219. $ossClient = new \app\common\services\aliyunoss\OssClient($remote_setting['alioss']['key'], $remote_setting['alioss']['secret'], $endpoint);
  1220. $ossClient->uploadFile($remote_setting['alioss']['bucket'], $filename, ATTACHMENT_ROOT . $filename);
  1221. } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
  1222. return error(1, $e->getMessage());
  1223. }
  1224. if ($auto_delete_local) {
  1225. file_deletes($filename);
  1226. }
  1227. } elseif ($upload_type == '3') {
  1228. load()->library('qiniu');
  1229. $auth = new Qiniu\Auth($remote_setting['qiniu']['accesskey'], $remote_setting['qiniu']['secretkey']);
  1230. $config = new Qiniu\Config();
  1231. $uploadmgr = new Qiniu\Storage\UploadManager($config);
  1232. $putpolicy = null;
  1233. $uploadtoken = $auth->uploadToken($remote_setting['qiniu']['bucket'], null, 3600, $putpolicy);
  1234. list($ret, $err) = $uploadmgr->putFile($uploadtoken, $filename, ATTACHMENT_ROOT . $filename);
  1235. if ($auto_delete_local) {
  1236. file_deletes($filename);
  1237. }
  1238. if ($err !== null) {
  1239. return error(1, '远程附件上传失败,请检查配置并重新上传');
  1240. } else {
  1241. return true;
  1242. }
  1243. } elseif ($upload_type == '4') {
  1244. //cosv5
  1245. $result = (new \app\common\services\QcloudCosService(
  1246. $remote_setting['cos']['local'],
  1247. $remote_setting['cos']['secretid'],
  1248. $remote_setting['cos']['secretkey'],
  1249. $remote_setting['cos']['bucket'],
  1250. $remote_setting['cos']['appid']
  1251. ))->upload($filename);
  1252. if ($auto_delete_local) {
  1253. file_deletes($filename);
  1254. }
  1255. if ($result === true) {
  1256. return true;
  1257. } else {
  1258. return error(-1, $result);
  1259. }
  1260. }
  1261. return true;
  1262. }
  1263. }
  1264. if (!function_exists('file_video_remote_upload_wq')) {
  1265. function file_video_remote_upload_wq($filename, $auto_delete_local = true, $remote = '', $frontend = false)
  1266. {
  1267. // $filename 文件名
  1268. // $auto_delete_local 是否自动删除本地资源 true 删除 false 不删除
  1269. // $remote 远程配置信息
  1270. // $frontend 是否前端调用 true 前端 false 后台
  1271. global $_W;
  1272. if (!empty($remote) && $frontend == true) {
  1273. $remote_setting = $remote;
  1274. $upload_type = $remote['type'];
  1275. } else {
  1276. $remote_setting = $_W['setting']['remote'];
  1277. $upload_type = $_W['setting']['remote']['type'];
  1278. }
  1279. if (empty($upload_type)) {
  1280. return false;
  1281. }
  1282. if ($upload_type == '1') {
  1283. $ftp_config = array(
  1284. 'hostname' => $remote_setting['ftp']['host'],
  1285. 'username' => $remote_setting['ftp']['username'],
  1286. 'password' => $remote_setting['ftp']['password'],
  1287. 'port' => $remote_setting['ftp']['port'],
  1288. 'ssl' => $remote_setting['ftp']['ssl'],
  1289. 'passive' => $remote_setting['ftp']['pasv'],
  1290. 'timeout' => $remote_setting['ftp']['timeout'],
  1291. 'rootdir' => $remote_setting['ftp']['dir'],
  1292. );
  1293. load()->library('ftp');
  1294. $ftp = new Ftp($ftp_config);
  1295. if (true === $ftp->connect()) {
  1296. $response = $ftp->upload(ATTACHMENT_ROOT . $filename, $filename);
  1297. if ($auto_delete_local) {
  1298. file_deletes($filename);
  1299. }
  1300. if (!empty($response)) {
  1301. return true;
  1302. } else {
  1303. return error(1, '远程附件上传失败,请检查配置并重新上传');
  1304. }
  1305. } else {
  1306. return error(1, '远程附件上传失败,请检查配置并重新上传');
  1307. }
  1308. } elseif ($upload_type == '2') {
  1309. $buckets = attachment_alioss_buctkets($remote_setting['alioss']['key'], $remote_setting['alioss']['secret']);
  1310. $endpoint = 'http://' . $buckets[$remote_setting['alioss']['bucket']]['location'] . '.aliyuncs.com';
  1311. try {
  1312. $ossClient = new \app\common\services\aliyunoss\OssClient($remote_setting['alioss']['key'], $remote_setting['alioss']['secret'], $endpoint);
  1313. $ossClient->uploadFile($remote_setting['alioss']['bucket'], $filename, ATTACHMENT_ROOT . $filename);
  1314. } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
  1315. return error(1, $e->getMessage());
  1316. }
  1317. if ($auto_delete_local) {
  1318. file_deletes($filename);
  1319. }
  1320. } elseif ($upload_type == '3') {
  1321. load()->library('qiniu');
  1322. $auth = new Qiniu\Auth($remote_setting['qiniu']['accesskey'], $remote_setting['qiniu']['secretkey']);
  1323. $config = new Qiniu\Config();
  1324. $uploadmgr = new Qiniu\Storage\UploadManager($config);
  1325. $putpolicy = null;
  1326. $uploadtoken = $auth->uploadToken($remote_setting['qiniu']['bucket'], null, 3600, $putpolicy);
  1327. list($ret, $err) = $uploadmgr->putFile($uploadtoken, $filename, ATTACHMENT_ROOT . $filename);
  1328. if ($auto_delete_local) {
  1329. file_deletes($filename);
  1330. }
  1331. if ($err !== null) {
  1332. return error(1, '远程附件上传失败,请检查配置并重新上传');
  1333. } else {
  1334. return true;
  1335. }
  1336. } elseif ($upload_type == '4') {
  1337. //cosv5
  1338. $result = (new \app\common\services\QcloudCosService(
  1339. $remote_setting['cos']['local'],
  1340. $remote_setting['cos']['secretid'],
  1341. $remote_setting['cos']['secretkey'],
  1342. $remote_setting['cos']['bucket'],
  1343. $remote_setting['cos']['appid']
  1344. ))->upload($filename);
  1345. if ($auto_delete_local) {
  1346. file_deletes($filename);
  1347. }
  1348. if ($result === true) {
  1349. return true;
  1350. } else {
  1351. return error(-1, $result);
  1352. }
  1353. }
  1354. }
  1355. }
  1356. if (!function_exists('file_remote_upload')) {
  1357. function file_remote_upload($filename, $auto_delete_local = true, $remote)
  1358. {
  1359. if (!$remote['type']) {
  1360. return false;
  1361. }
  1362. if ($remote['type'] == '2') {
  1363. $bucket = rtrim(substr($remote['alioss']['bucket'], 0, strrpos($remote['alioss']['bucket'],'@')), '@');
  1364. $buckets = attachment_alioss_buctkets($remote['alioss']['key'], $remote['alioss']['secret']);
  1365. $host_name = $remote['alioss']['internal'] ? '-internal.aliyuncs.com' : '.aliyuncs.com';
  1366. $endpoint = 'http://' . $buckets[$bucket]['location'] . $host_name;
  1367. try {
  1368. $ossClient = new \app\common\services\aliyunoss\OssClient($remote['alioss']['key'], $remote['alioss']['secret'], $endpoint);
  1369. $result = $ossClient->uploadFile($bucket, $filename, base_path('static/upload/') . $filename);
  1370. } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
  1371. return error(1, $e->getMessage());
  1372. }
  1373. if ($auto_delete_local) {
  1374. file_delete($filename);
  1375. }
  1376. if (!$result) {
  1377. return error(-1, $result);
  1378. }
  1379. return true;
  1380. } elseif ($remote['type'] == '4') {
  1381. $result = (new \app\common\services\QcloudCosService(
  1382. $remote['cos']['local'],
  1383. $remote['cos']['secretid'],
  1384. $remote['cos']['secretkey'],
  1385. $remote['cos']['bucket'],
  1386. $remote['cos']['appid']
  1387. ))->upload($filename);
  1388. if ($auto_delete_local) {
  1389. file_delete($filename);
  1390. }
  1391. if (!$result) {
  1392. return error(-1, '上传远程失败');
  1393. }
  1394. return true;
  1395. } elseif ($remote['type'] == '5') {
  1396. $result = (new \app\common\services\ObsService(
  1397. $remote['obs']['key'],
  1398. $remote['obs']['secret'],
  1399. $remote['obs']['endpoint'],
  1400. $remote['obs']['bucket']
  1401. ))->upload($filename);
  1402. if ($auto_delete_local) {
  1403. file_delete($filename);
  1404. }
  1405. if (!$result) {
  1406. return error(-1, '上传远程失败');
  1407. }
  1408. return true;
  1409. }
  1410. return false;
  1411. }
  1412. }
  1413. if (!function_exists('file_video_remote_upload')) {
  1414. function file_video_remote_upload($filename, $auto_delete_local = true, $remote)
  1415. {
  1416. if (!$remote['type']) {
  1417. return false;
  1418. }
  1419. if ($remote['type'] == '2') {
  1420. $bucket = rtrim(substr($remote['alioss']['bucket'], 0, strrpos($remote['alioss']['bucket'],'@')), '@');
  1421. $buckets = attachment_alioss_buctkets($remote['alioss']['key'], $remote['alioss']['secret']);
  1422. $host_name = $remote['alioss']['internal'] ? '-internal.aliyuncs.com' : '.aliyuncs.com';
  1423. $endpoint = 'http://' . $buckets[$bucket]['location'] . $host_name;
  1424. try {
  1425. $ossClient = new \app\common\services\aliyunoss\OssClient($remote['alioss']['key'], $remote['alioss']['secret'], $endpoint);
  1426. $ossClient->uploadFile($bucket, $filename, base_path() . $filename);
  1427. } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
  1428. \Log::info('-----alioss上传失败信息-----', $e->getMessage());
  1429. return error(1, $e->getMessage());
  1430. }
  1431. if ($auto_delete_local) {
  1432. file_delete($filename);
  1433. }
  1434. } elseif ($remote['type'] == '4') {
  1435. $result = (new \app\common\services\QcloudCosService(
  1436. $remote['cos']['local'],
  1437. $remote['cos']['secretid'],
  1438. $remote['cos']['secretkey'],
  1439. $remote['cos']['bucket'],
  1440. $remote['cos']['appid']
  1441. ))->upload($filename);
  1442. if ($auto_delete_local) {
  1443. file_delete($filename);
  1444. }
  1445. if (!$result) {
  1446. return error(-1, '上传远程失败');
  1447. }
  1448. return true;
  1449. } elseif ($remote['type'] == '5') {
  1450. $result = (new \app\common\services\ObsService(
  1451. $remote['obs']['key'],
  1452. $remote['obs']['secret'],
  1453. $remote['obs']['endpoint'],
  1454. $remote['obs']['bucket']
  1455. ))->upload($filename);
  1456. if ($auto_delete_local) {
  1457. file_delete($filename);
  1458. }
  1459. if (!$result) {
  1460. return error(-1, '上传远程失败');
  1461. }
  1462. return true;
  1463. }
  1464. return false;
  1465. }
  1466. }
  1467. if (!function_exists('file_remote_upload_new')) {
  1468. function file_remote_upload_new($filename, $auto_delete_local = true, $remote)
  1469. {
  1470. if (!$remote['type']) {
  1471. return false;
  1472. }
  1473. if ($remote['type'] == '2') {
  1474. $bucket = rtrim(substr($remote['alioss']['bucket'], 0, strrpos($remote['alioss']['bucket'],'@')), '@');
  1475. $buckets = attachment_alioss_buctkets($remote['alioss']['key'], $remote['alioss']['secret']);
  1476. $host_name = $remote['alioss']['internal'] ? '-internal.aliyuncs.com' : '.aliyuncs.com';
  1477. $endpoint = 'http://' . $buckets[$bucket]['location'] . $host_name;
  1478. try {
  1479. $ossClient = new \app\common\services\aliyunoss\OssClient($remote['alioss']['key'], $remote['alioss']['secret'], $endpoint);
  1480. $ossClient->uploadFile($bucket, $filename, base_path() . '/static/upload/' . $filename);
  1481. } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
  1482. \Log::info('-----alioss上传失败信息-----', $e->getMessage());
  1483. return error(1, $e->getMessage());
  1484. }
  1485. if ($auto_delete_local) {
  1486. file_delete($filename);
  1487. }
  1488. } elseif ($remote['type'] == '4') {
  1489. $result = (new \app\common\services\QcloudCosService(
  1490. $remote['cos']['local'],
  1491. $remote['cos']['secretid'],
  1492. $remote['cos']['secretkey'],
  1493. $remote['cos']['bucket'],
  1494. $remote['cos']['appid']
  1495. ))->upload($filename);
  1496. if ($auto_delete_local) {
  1497. file_delete($filename);
  1498. }
  1499. if (!$result) {
  1500. return error(-1, '上传远程失败');
  1501. }
  1502. return true;
  1503. } elseif ($remote['type'] == '5') {
  1504. $result = (new \app\common\services\ObsService(
  1505. $remote['obs']['key'],
  1506. $remote['obs']['secret'],
  1507. $remote['obs']['endpoint'],
  1508. $remote['obs']['bucket']
  1509. ))->upload($filename);
  1510. if ($auto_delete_local) {
  1511. file_delete($filename);
  1512. }
  1513. if (!$result) {
  1514. return error(-1, '上传远程失败');
  1515. }
  1516. return true;
  1517. }
  1518. return false;
  1519. }
  1520. }
  1521. if (!function_exists('attachment_alioss_buctkets')) {
  1522. function attachment_alioss_buctkets($key, $secret)
  1523. {
  1524. $url = 'http://oss-cn-beijing.aliyuncs.com';
  1525. try {
  1526. $ossClient = new \app\common\services\aliyunoss\OssClient($key, $secret, $url);
  1527. } catch(\app\common\services\aliyunoss\OSS\Core\OssException $e) {
  1528. return error(1, $e->getMessage());
  1529. }
  1530. try {
  1531. $bucketlistinfo = $ossClient->listBuckets();
  1532. } catch(\app\common\services\aliyunoss\OSS\Core\OssException $e) {
  1533. return error(1, $e->getMessage());
  1534. }
  1535. $bucketlistinfo = $bucketlistinfo->getBucketList();
  1536. $bucketlist = array();
  1537. foreach ($bucketlistinfo as &$bucket) {
  1538. $bucketlist[$bucket->getName()] = array('name' => $bucket->getName(), 'location' => $bucket->getLocation());
  1539. }
  1540. return $bucketlist;
  1541. }
  1542. }
  1543. if (!function_exists('file_deletes')) {
  1544. function file_deletes($file)
  1545. {
  1546. if (empty($file)) {
  1547. return false;
  1548. }
  1549. if (file_exists($file)) {
  1550. @unlink($file);
  1551. }
  1552. if (strexists($file, 'image/')) {
  1553. $file = str_replace('image/', '', $file);
  1554. }
  1555. if (file_exists(ATTACHMENT_ROOT . 'image/' . $file)) {
  1556. @unlink(ATTACHMENT_ROOT . 'image/' . $file);
  1557. }
  1558. if (file_exists(ATTACHMENT_ROOT . $file)) {
  1559. @unlink(ATTACHMENT_ROOT . $file);
  1560. }
  1561. return true;
  1562. }
  1563. }
  1564. if (!function_exists('file_delete')) {
  1565. function file_delete($file)
  1566. {
  1567. if (empty($file)) {
  1568. return false;
  1569. }
  1570. if (file_exists($file)) {
  1571. @unlink($file);
  1572. }
  1573. if (file_exists(base_path() . '/static/upload/' . $file)) {
  1574. @unlink(base_path() . '/static/upload/' . $file);
  1575. }
  1576. return true;
  1577. }
  1578. }
  1579. if (!function_exists('safe_gpc_html')) {
  1580. function safe_gpc_html($value, $default = '')
  1581. {
  1582. if (empty($value) || !is_string($value)) {
  1583. return $default;
  1584. }
  1585. $value = safe_bad_str_replace($value);
  1586. $value = safe_remove_xss($value);
  1587. if (!$value && $value != $default) {
  1588. $value = $default;
  1589. }
  1590. return $value;
  1591. }
  1592. }
  1593. if (!function_exists('safe_bad_str_replace')) {
  1594. function safe_bad_str_replace($string)
  1595. {
  1596. if (!$string) {
  1597. return '';
  1598. }
  1599. $badstr = array("\0", "%00", "%3C", "%3E", '<?', '<%', '<?php', '{php', '../');
  1600. $newstr = array('_', '_', '&lt;', '&gt;', '_', '_', '_', '_', '.._');
  1601. $string = str_replace($badstr, $newstr, $string);
  1602. return $string;
  1603. }
  1604. }
  1605. if (!function_exists('safe_remove_xss')) {
  1606. function safe_remove_xss($val)
  1607. {
  1608. $val = preg_replace('/([\x0e-\x19])/', '', $val);
  1609. $search = 'abcdefghijklmnopqrstuvwxyz';
  1610. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1611. $search .= '1234567890!@#$%^&*()';
  1612. $search .= '~`";:?+/={}[]-_|\'\\';
  1613. for ($i = 0; $i < strlen($search); $i++) {
  1614. $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val);
  1615. $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val);
  1616. }
  1617. preg_match_all('/href=[\'|\"](.*?)[\'|\"]|src=[\'|\"](.*?)[\'|\"]/i', $val, $matches);
  1618. $url_list = array_merge($matches[1], $matches[2]);
  1619. $encode_url_list = array();
  1620. if ($url_list) {
  1621. foreach ($url_list as $key => $url) {
  1622. $val = str_replace($url, 'we7_' . $key . '_we7placeholder', $val);
  1623. $encode_url_list[] = $url;
  1624. }
  1625. }
  1626. $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'frameset', 'ilayer', 'bgsound', 'base');
  1627. $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload', '@import');
  1628. $ra = array_merge($ra1, $ra2);
  1629. $found = true;
  1630. while ($found == true) {
  1631. $val_before = $val;
  1632. for ($i = 0; $i < sizeof($ra); $i++) {
  1633. $pattern = '/';
  1634. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  1635. if ($j > 0) {
  1636. $pattern .= '(';
  1637. $pattern .= '(&#[xX]0{0,8}([9ab]);)';
  1638. $pattern .= '|';
  1639. $pattern .= '|(&#0{0,8}([9|10|13]);)';
  1640. $pattern .= ')*';
  1641. }
  1642. $pattern .= $ra[$i][$j];
  1643. }
  1644. $pattern .= '/i';
  1645. $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2);
  1646. $val = preg_replace($pattern, $replacement, $val);
  1647. if ($val_before == $val) {
  1648. $found = false;
  1649. }
  1650. }
  1651. }
  1652. if ($encode_url_list && is_array($encode_url_list)) {
  1653. foreach ($encode_url_list as $key => $url) {
  1654. $val = str_replace('we7_' . $key . '_we7placeholder', $url, $val);
  1655. }
  1656. }
  1657. return $val;
  1658. }
  1659. }
  1660. if (!function_exists('file_move')) {
  1661. function file_move($filename, $dest)
  1662. {
  1663. \app\common\services\Utils::mkdirs(dirname($dest));
  1664. if (is_uploaded_file($filename)) {
  1665. move_uploaded_file($filename, $dest);
  1666. } else {
  1667. rename($filename, $dest);
  1668. }
  1669. // @chmod($filename, $_W['config']['setting']['filemode']);
  1670. return is_file($dest);
  1671. }
  1672. }
  1673. if (!function_exists('pagination')) {
  1674. function pagination($total, $pageIndex, $pageSize = 15, $url = '', $context = array('before' => 5, 'after' => 4, 'ajaxcallback' => '', 'callbackfuncname' => ''))
  1675. {
  1676. $pdata = array(
  1677. 'tcount' => 0,
  1678. 'tpage' => 0,
  1679. 'cindex' => 0,
  1680. 'findex' => 0,
  1681. 'pindex' => 0,
  1682. 'nindex' => 0,
  1683. 'lindex' => 0,
  1684. 'options' => ''
  1685. );
  1686. if (!$context['before']) {
  1687. $context['before'] = 5;
  1688. }
  1689. if (!$context['after']) {
  1690. $context['after'] = 4;
  1691. }
  1692. if ($context['ajaxcallback']) {
  1693. $context['isajax'] = true;
  1694. }
  1695. if ($context['callbackfuncname']) {
  1696. $callbackfunc = $context['callbackfuncname'];
  1697. }
  1698. $pdata['tcount'] = $total;
  1699. $pdata['tpage'] = (!$pageSize || $pageSize < 0) ? 1 : intval(ceil($total / $pageSize));
  1700. if ($pdata['tpage'] <= 1) {
  1701. return '';
  1702. }
  1703. $cindex = $pageIndex;
  1704. $cindex = min($cindex, $pdata['tpage']);
  1705. $cindex = max($cindex, 1);
  1706. $pdata['cindex'] = $cindex;
  1707. $pdata['findex'] = 1;
  1708. $pdata['pindex'] = $cindex > 1 ? $cindex - 1 : 1;
  1709. $pdata['nindex'] = $cindex < $pdata['tpage'] ? $cindex + 1 : $pdata['tpage'];
  1710. $pdata['lindex'] = $pdata['tpage'];
  1711. if ($context['isajax']) {
  1712. if (!$url) {
  1713. $url = '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET);
  1714. }
  1715. $pdata['faa'] = 'href="javascript:;" page="' . $pdata['findex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['findex'] . '\', this);"' : '');
  1716. $pdata['paa'] = 'href="javascript:;" page="' . $pdata['pindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['pindex'] . '\', this);"' : '');
  1717. $pdata['naa'] = 'href="javascript:;" page="' . $pdata['nindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['nindex'] . '\', this);"' : '');
  1718. $pdata['laa'] = 'href="javascript:;" page="' . $pdata['lindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['lindex'] . '\', this);"' : '');
  1719. } else {
  1720. if ($url) {
  1721. $pdata['faa'] = 'href="?' . str_replace('*', $pdata['findex'], $url) . '"';
  1722. $pdata['paa'] = 'href="?' . str_replace('*', $pdata['pindex'], $url) . '"';
  1723. $pdata['naa'] = 'href="?' . str_replace('*', $pdata['nindex'], $url) . '"';
  1724. $pdata['laa'] = 'href="?' . str_replace('*', $pdata['lindex'], $url) . '"';
  1725. } else {
  1726. $_GET['page'] = $pdata['findex'];
  1727. $pdata['faa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
  1728. $_GET['page'] = $pdata['pindex'];
  1729. $pdata['paa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
  1730. $_GET['page'] = $pdata['nindex'];
  1731. $pdata['naa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
  1732. $_GET['page'] = $pdata['lindex'];
  1733. $pdata['laa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
  1734. }
  1735. }
  1736. $html = '<div><ul class="pagination pagination-centered">';
  1737. $html .= "<li><a {$pdata['faa']} class=\"pager-nav\">首页</a></li>";
  1738. empty($callbackfunc) && $html .= "<li><a {$pdata['paa']} class=\"pager-nav\">&laquo;上一页</a></li>";
  1739. if (!$context['before'] && $context['before'] != 0) {
  1740. $context['before'] = 5;
  1741. }
  1742. if (!$context['after'] && $context['after'] != 0) {
  1743. $context['after'] = 4;
  1744. }
  1745. if ($context['after'] != 0 && $context['before'] != 0) {
  1746. $range = array();
  1747. $range['start'] = max(1, $pdata['cindex'] - $context['before']);
  1748. $range['end'] = min($pdata['tpage'], $pdata['cindex'] + $context['after']);
  1749. if ($range['end'] - $range['start'] < $context['before'] + $context['after']) {
  1750. $range['end'] = min($pdata['tpage'], $range['start'] + $context['before'] + $context['after']);
  1751. $range['start'] = max(1, $range['end'] - $context['before'] - $context['after']);
  1752. }
  1753. for ($i = $range['start']; $i <= $range['end']; $i++) {
  1754. if ($context['isajax']) {
  1755. $aa = 'href="javascript:;" page="' . $i . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $i . '\', this);"' : '');
  1756. } else {
  1757. if ($url) {
  1758. $aa = 'href="?' . str_replace('*', $i, $url) . '"';
  1759. } else {
  1760. $_GET['page'] = $i;
  1761. $aa = 'href="?' . http_build_query($_GET) . '"';
  1762. }
  1763. }
  1764. if (!empty($context['isajax'])) {
  1765. $html .= ($i == $pdata['cindex'] ? '<li class="active">' : '<li>') . "<a {$aa}>" . $i . '</a></li>';
  1766. } else {
  1767. $html .= ($i == $pdata['cindex'] ? '<li class="active"><a href="javascript:;">' . $i . '</a></li>' : "<li><a {$aa}>" . $i . '</a></li>');
  1768. }
  1769. }
  1770. }
  1771. if ($pdata['cindex'] < $pdata['tpage']) {
  1772. empty($callbackfunc) && $html .= "<li><a {$pdata['naa']} class=\"pager-nav\">下一页&raquo;</a></li>";
  1773. $html .= "<li><a {$pdata['laa']} class=\"pager-nav\">尾页</a></li>";
  1774. }
  1775. $html .= '</ul></div>';
  1776. return $html;
  1777. }
  1778. }
  1779. if (!function_exists('http_build_query')) {
  1780. /**
  1781. * 为了兼容微擎使用此方法
  1782. * @param $formdata
  1783. * @param null $numeric_prefix
  1784. * @param null $arg_separator
  1785. * @return bool|string
  1786. */
  1787. function http_build_query($formdata, $numeric_prefix = null, $arg_separator = null)
  1788. {
  1789. if (!is_array($formdata))
  1790. return false;
  1791. if ($arg_separator == null)
  1792. $arg_separator = '&';
  1793. return http_build_recursive($formdata, $arg_separator);
  1794. }
  1795. }
  1796. if (!function_exists('ihttp_get')) {
  1797. /**
  1798. * 为了兼容微擎使用此方法
  1799. * @param $url
  1800. * @return array
  1801. */
  1802. function ihttp_get($url)
  1803. {
  1804. return ihttp_request($url);
  1805. }
  1806. }
  1807. if (!function_exists('ihttp_request')) {
  1808. /**
  1809. * 为了兼容微擎使用此方法
  1810. * @param $url
  1811. * @param string $post
  1812. * @param array $extra
  1813. * @param int $timeout
  1814. * @return array
  1815. */
  1816. function ihttp_request($url, $post = '', $extra = array(), $timeout = 60)
  1817. {
  1818. if (function_exists('curl_init') && function_exists('curl_exec') && $timeout > 0) {
  1819. $ch = ihttp_build_curl($url, $post, $extra, $timeout);
  1820. if (is_error($ch)) {
  1821. return $ch;
  1822. }
  1823. $data = curl_exec($ch);
  1824. $status = curl_getinfo($ch);
  1825. $errno = curl_errno($ch);
  1826. $error = curl_error($ch);
  1827. curl_close($ch);
  1828. if ($errno || !$data) {
  1829. return error($errno, $error);
  1830. } else {
  1831. return ihttp_response_parse($data);
  1832. }
  1833. }
  1834. $urlset = ihttp_parse_url($url, true);
  1835. if ($urlset['ip']) {
  1836. $urlset['host'] = $urlset['ip'];
  1837. }
  1838. $body = ihttp_build_httpbody($url, $post, $extra);
  1839. if ($urlset['scheme'] == 'https') {
  1840. $fp = ihttp_socketopen('ssl://' . $urlset['host'], $urlset['port'], $errno, $error);
  1841. } else {
  1842. $fp = ihttp_socketopen($urlset['host'], $urlset['port'], $errno, $error);
  1843. }
  1844. stream_set_blocking($fp, $timeout > 0 ? true : false);
  1845. stream_set_timeout($fp, ini_get('default_socket_timeout'));
  1846. if (!$fp) {
  1847. return error(1, $error);
  1848. } else {
  1849. fwrite($fp, $body);
  1850. $content = '';
  1851. if ($timeout > 0) {
  1852. while (!feof($fp)) {
  1853. $content .= fgets($fp, 512);
  1854. }
  1855. }
  1856. fclose($fp);
  1857. return ihttp_response_parse($content, true);
  1858. }
  1859. }
  1860. }
  1861. if (!function_exists('ihttp_build_curl')) {
  1862. /**
  1863. * 为了兼容微擎使用此方法
  1864. * @param $url
  1865. * @param $post
  1866. * @param $extra
  1867. * @param $timeout
  1868. * @return resource
  1869. */
  1870. function ihttp_build_curl($url, $post, $extra, $timeout)
  1871. {
  1872. if (!function_exists('curl_init') || !function_exists('curl_exec')) {
  1873. return error(1, 'curl扩展未开启');
  1874. }
  1875. $urlset = ihttp_parse_url($url);
  1876. if (is_error($urlset)) {
  1877. return $urlset;
  1878. }
  1879. if ($urlset['ip']) {
  1880. $extra['ip'] = $urlset['ip'];
  1881. }
  1882. $ch = curl_init();
  1883. if ($extra['ip']) {
  1884. $extra['Host'] = $urlset['host'];
  1885. $urlset['host'] = $extra['ip'];
  1886. unset($extra['ip']);
  1887. }
  1888. curl_setopt($ch, CURLOPT_URL, $urlset['scheme'] . '://' . $urlset['host'] . ($urlset['port'] == '80' || !$urlset['port'] ? '' : ':' . $urlset['port']) . $urlset['path'] . $urlset['query']);
  1889. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1890. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  1891. curl_setopt($ch, CURLOPT_HEADER, 1);
  1892. @curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  1893. if ($post) {
  1894. if (is_array($post)) {
  1895. $filepost = false;
  1896. foreach ($post as $name => &$value) {
  1897. if (version_compare(phpversion(), '5.5') >= 0 && is_string($value) && substr($value, 0, 1) == '@') {
  1898. $post[$name] = new CURLFile(ltrim($value, '@'));
  1899. }
  1900. if ((is_string($value) && substr($value, 0, 1) == '@') || (class_exists('CURLFile') && $value instanceof CURLFile)) {
  1901. $filepost = true;
  1902. }
  1903. }
  1904. if (!$filepost) {
  1905. $post = http_build_query($post);
  1906. }
  1907. }
  1908. curl_setopt($ch, CURLOPT_POST, 1);
  1909. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  1910. }
  1911. if ($GLOBALS['_W']['config']['setting']['proxy']) {
  1912. $urls = parse_url($GLOBALS['_W']['config']['setting']['proxy']['host']);
  1913. if (!empty($urls['host'])) {
  1914. curl_setopt($ch, CURLOPT_PROXY, "{$urls['host']}:{$urls['port']}");
  1915. $proxytype = 'CURLPROXY_' . strtoupper($urls['scheme']);
  1916. if ($urls['scheme'] && defined($proxytype)) {
  1917. curl_setopt($ch, CURLOPT_PROXYTYPE, constant($proxytype));
  1918. } else {
  1919. curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  1920. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  1921. }
  1922. if ($GLOBALS['_W']['config']['setting']['proxy']['auth']) {
  1923. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['_W']['config']['setting']['proxy']['auth']);
  1924. }
  1925. }
  1926. }
  1927. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  1928. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  1929. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1930. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  1931. curl_setopt($ch, CURLOPT_SSLVERSION, 1);
  1932. if (defined('CURL_SSLVERSION_TLSv1')) {
  1933. curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
  1934. }
  1935. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
  1936. if ($extra && is_array($extra)) {
  1937. $headers = array();
  1938. foreach ($extra as $opt => $value) {
  1939. if (strexists($opt, 'CURLOPT_')) {
  1940. curl_setopt($ch, constant($opt), $value);
  1941. } elseif (is_numeric($opt)) {
  1942. curl_setopt($ch, $opt, $value);
  1943. } else {
  1944. $headers[] = "{$opt}: {$value}";
  1945. }
  1946. }
  1947. if ($headers) {
  1948. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  1949. }
  1950. }
  1951. return $ch;
  1952. }
  1953. }
  1954. if (!function_exists('ihttp_parse_url')) {
  1955. /**
  1956. * 为了兼容微擎使用此方法
  1957. * @param $url
  1958. * @param bool $set_default_port
  1959. * @return array|mixed
  1960. */
  1961. function ihttp_parse_url($url, $set_default_port = false)
  1962. {
  1963. if (!$url) {
  1964. return error(1);
  1965. }
  1966. $urlset = parse_url($url);
  1967. if ($urlset['scheme'] && !in_array($urlset['scheme'], array('http', 'https'))) {
  1968. return error(1, '只能使用 http 及 https 协议');
  1969. }
  1970. if (!$urlset['path']) {
  1971. $urlset['path'] = '/';
  1972. }
  1973. if ($urlset['query']) {
  1974. $urlset['query'] = "?{$urlset['query']}";
  1975. }
  1976. if (strexists($url, 'https://') && !extension_loaded('openssl')) {
  1977. if (!extension_loaded("openssl")) {
  1978. return error(1, '请开启您PHP环境的openssl', '');
  1979. }
  1980. }
  1981. if (!$urlset['host']) {
  1982. $current_url = parse_url($GLOBALS['_W']['siteroot']);
  1983. $urlset['host'] = $current_url['host'];
  1984. $urlset['scheme'] = $current_url['scheme'];
  1985. $urlset['path'] = $current_url['path'] . 'web/' . str_replace('./', '', $urlset['path']);
  1986. $urlset['ip'] = '127.0.0.1';
  1987. } else if (!ihttp_allow_host($urlset['host'])) {
  1988. return error(1, 'host 非法');
  1989. }
  1990. if ($set_default_port && !$urlset['port']) {
  1991. $urlset['port'] = $urlset['scheme'] == 'https' ? '443' : '80';
  1992. }
  1993. return $urlset;
  1994. }
  1995. }
  1996. if (!function_exists('error')) {
  1997. /**
  1998. * 为了兼容微擎使用此方法
  1999. * @param $errno
  2000. * @param string $message
  2001. * @return array
  2002. */
  2003. function error($errno, $message = '')
  2004. {
  2005. return array(
  2006. 'errno' => $errno,
  2007. 'message' => $message,
  2008. );
  2009. }
  2010. }
  2011. if (!function_exists('http_build_recursive')) {
  2012. /**
  2013. * 为了兼容微擎使用此方法
  2014. * @param $formdata
  2015. * @param $separator
  2016. * @param string $key
  2017. * @param string $prefix
  2018. * @return string
  2019. */
  2020. function http_build_recursive($formdata, $separator, $key = '', $prefix = '')
  2021. {
  2022. $rlt = '';
  2023. foreach ($formdata as $k => $v) {
  2024. if (is_array($v)) {
  2025. if ($key)
  2026. $rlt .= http_build_recursive($v, $separator, $key . '[' . $k . ']', $prefix);
  2027. else
  2028. $rlt .= http_build_recursive($v, $separator, $k, $prefix);
  2029. } else {
  2030. if ($key)
  2031. $rlt .= $prefix . $key . '[' . urlencode($k) . ']=' . urldecode($v) . '&';
  2032. else
  2033. $rlt .= $prefix . urldecode($k) . '=' . urldecode($v) . '&';
  2034. }
  2035. }
  2036. return $rlt;
  2037. }
  2038. }
  2039. if (!function_exists('ihttp_response_parse')) {
  2040. /**
  2041. * 为了兼容微擎使用此方法
  2042. * @param $data
  2043. * @param bool $chunked
  2044. * @return array
  2045. */
  2046. function ihttp_response_parse($data, $chunked = false)
  2047. {
  2048. $rlt = array();
  2049. $headermeta = explode('HTTP/', $data);
  2050. if (count($headermeta) > 2) {
  2051. $data = 'HTTP/' . array_pop($headermeta);
  2052. }
  2053. $pos = strpos($data, "\r\n\r\n");
  2054. $split1[0] = substr($data, 0, $pos);
  2055. $split1[1] = substr($data, $pos + 4, strlen($data));
  2056. $split2 = explode("\r\n", $split1[0], 2);
  2057. preg_match('/^(\S+) (\S+) (.*)$/', $split2[0], $matches);
  2058. $rlt['code'] = $matches[2] ? : 200;
  2059. $rlt['status'] = $matches[3] ? : 'OK';
  2060. $rlt['responseline'] = $split2[0] ? : '';
  2061. $header = explode("\r\n", $split2[1]);
  2062. $isgzip = false;
  2063. $ischunk = false;
  2064. foreach ($header as $v) {
  2065. $pos = strpos($v, ':');
  2066. $key = substr($v, 0, $pos);
  2067. $value = trim(substr($v, $pos + 1));
  2068. if (is_array($rlt['headers'][$key])) {
  2069. $rlt['headers'][$key][] = $value;
  2070. } elseif ($rlt['headers'][$key]) {
  2071. $temp = $rlt['headers'][$key];
  2072. unset($rlt['headers'][$key]);
  2073. $rlt['headers'][$key][] = $temp;
  2074. $rlt['headers'][$key][] = $value;
  2075. } else {
  2076. $rlt['headers'][$key] = $value;
  2077. }
  2078. if (!$isgzip && strtolower($key) == 'content-encoding' && strtolower($value) == 'gzip') {
  2079. $isgzip = true;
  2080. }
  2081. if (!$ischunk && strtolower($key) == 'transfer-encoding' && strtolower($value) == 'chunked') {
  2082. $ischunk = true;
  2083. }
  2084. }
  2085. if ($chunked && $ischunk) {
  2086. $rlt['content'] = ihttp_response_parse_unchunk($split1[1]);
  2087. } else {
  2088. $rlt['content'] = $split1[1];
  2089. }
  2090. if ($isgzip && function_exists('gzdecode')) {
  2091. $rlt['content'] = gzdecode($rlt['content']);
  2092. }
  2093. $rlt['meta'] = $data;
  2094. if ($rlt['code'] == '100') {
  2095. return ihttp_response_parse($rlt['content']);
  2096. }
  2097. return $rlt;
  2098. }
  2099. }
  2100. if (!function_exists('ihttp_response_parse_unchunk')) {
  2101. /**
  2102. * 为了兼容微擎使用此方法
  2103. * @param null $str
  2104. * @return bool|string|null
  2105. */
  2106. function ihttp_response_parse_unchunk($str = null)
  2107. {
  2108. if (!is_string($str) or strlen($str) < 1) {
  2109. return false;
  2110. }
  2111. $eol = "\r\n";
  2112. $add = strlen($eol);
  2113. $tmp = $str;
  2114. $str = '';
  2115. do {
  2116. $tmp = ltrim($tmp);
  2117. $pos = strpos($tmp, $eol);
  2118. if ($pos === false) {
  2119. return false;
  2120. }
  2121. $len = hexdec(substr($tmp, 0, $pos));
  2122. if (!is_numeric($len) or $len < 0) {
  2123. return false;
  2124. }
  2125. $str .= substr($tmp, ($pos + $add), $len);
  2126. $tmp = substr($tmp, ($len + $pos + $add));
  2127. $check = trim($tmp);
  2128. } while ($check);
  2129. unset($tmp);
  2130. return $str;
  2131. }
  2132. }
  2133. if (!function_exists('ihttp_build_httpbody')) {
  2134. /**
  2135. * 为了兼容微擎使用此方法
  2136. * @param $url
  2137. * @param $post
  2138. * @param $extra
  2139. * @return array|mixed|string
  2140. */
  2141. function ihttp_build_httpbody($url, $post, $extra)
  2142. {
  2143. $urlset = ihttp_parse_url($url, true);
  2144. if (is_error($urlset)) {
  2145. return $urlset;
  2146. }
  2147. if ($urlset['ip']) {
  2148. $extra['ip'] = $urlset['ip'];
  2149. }
  2150. $body = '';
  2151. if ($post && is_array($post)) {
  2152. $filepost = false;
  2153. $boundary = random(40);
  2154. foreach ($post as $name => &$value) {
  2155. if ((is_string($value) && substr($value, 0, 1) == '@') && file_exists(ltrim($value, '@'))) {
  2156. $filepost = true;
  2157. $file = ltrim($value, '@');
  2158. $body .= "--$boundary\r\n";
  2159. $body .= 'Content-Disposition: form-data; name="' . $name . '"; filename="' . basename($file) . '"; Content-Type: application/octet-stream' . "\r\n\r\n";
  2160. $body .= file_get_contents($file) . "\r\n";
  2161. } else {
  2162. $body .= "--$boundary\r\n";
  2163. $body .= 'Content-Disposition: form-data; name="' . $name . '"' . "\r\n\r\n";
  2164. $body .= $value . "\r\n";
  2165. }
  2166. }
  2167. if (!$filepost) {
  2168. $body = http_build_query($post, '', '&');
  2169. } else {
  2170. $body .= "--$boundary\r\n";
  2171. }
  2172. }
  2173. $method = !$post ? 'GET' : 'POST';
  2174. $fdata = "{$method} {$urlset['path']}{$urlset['query']} HTTP/1.1\r\n";
  2175. $fdata .= "Accept: */*\r\n";
  2176. $fdata .= "Accept-Language: zh-cn\r\n";
  2177. if ($method == 'POST') {
  2178. $fdata .= !$filepost ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data; boundary=$boundary\r\n";
  2179. }
  2180. $fdata .= "Host: {$urlset['host']}\r\n";
  2181. $fdata .= "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1\r\n";
  2182. if (function_exists('gzdecode')) {
  2183. $fdata .= "Accept-Encoding: gzip, deflate\r\n";
  2184. }
  2185. $fdata .= "Connection: close\r\n";
  2186. if ($extra && is_array($extra)) {
  2187. foreach ($extra as $opt => $value) {
  2188. if (!strexists($opt, 'CURLOPT_')) {
  2189. $fdata .= "{$opt}: {$value}\r\n";
  2190. }
  2191. }
  2192. }
  2193. if ($body) {
  2194. $fdata .= 'Content-Length: ' . strlen($body) . "\r\n\r\n{$body}";
  2195. } else {
  2196. $fdata .= "\r\n";
  2197. }
  2198. return $fdata;
  2199. }
  2200. }
  2201. if (!function_exists('ihttp_socketopen')) {
  2202. function ihttp_socketopen($hostname, $port = 80, &$errno, &$errstr, $timeout = 15)
  2203. {
  2204. $fp = '';
  2205. if (function_exists('fsockopen')) {
  2206. $fp = @fsockopen($hostname, $port, $errno, $errstr, $timeout);
  2207. } elseif (function_exists('pfsockopen')) {
  2208. $fp = @pfsockopen($hostname, $port, $errno, $errstr, $timeout);
  2209. } elseif (function_exists('stream_socket_client')) {
  2210. $fp = @stream_socket_client($hostname . ':' . $port, $errno, $errstr, $timeout);
  2211. }
  2212. return $fp;
  2213. }
  2214. }
  2215. if (!function_exists('ihttp_allow_host')) {
  2216. /**
  2217. * 为了兼容微擎使用此方法
  2218. * @param $host
  2219. * @return bool
  2220. */
  2221. function ihttp_allow_host($host)
  2222. {
  2223. if (strexists($host, '@')) {
  2224. return false;
  2225. }
  2226. $pattern = "/^(10|172|192|127)/";
  2227. $global = YunShop::app();
  2228. if (preg_match($pattern, $host) && isset($global['setting']['ip_white_list'])) {
  2229. $ip_white_list = $global['setting']['ip_white_list'];
  2230. if ($ip_white_list && isset($ip_white_list[$host]) && !$ip_white_list[$host]['status']) {
  2231. return false;
  2232. }
  2233. }
  2234. return true;
  2235. }
  2236. }
  2237. if (!function_exists('attachment_obs_auth')) {
  2238. function attachment_obs_auth($key, $secret, $endpoint, $bucket)
  2239. {
  2240. $filename = '/static/logo.png';
  2241. $result = (new \app\common\services\ObsService($key, $secret, $endpoint, $bucket))->upload($filename, true);
  2242. if (!$result) {
  2243. return error(-1, '测试上传失败');
  2244. }
  2245. return true;
  2246. }
  2247. }
  2248. if (!function_exists('attachment_cos_auth')) {
  2249. function attachment_cos_auth($bucket, $appid, $key, $secret, $bucket_local = '')
  2250. {
  2251. if (!is_numeric($appid)) {
  2252. return error(-1, '传入appid值不合法, 请重新输入');
  2253. }
  2254. if (!preg_match('/^[a-zA-Z0-9]{36}$/', $key)) {
  2255. return error(-1, '传入secretid值不合法,请重新传入');
  2256. }
  2257. if (!preg_match('/^[a-zA-Z0-9]{32}$/', $secret)) {
  2258. return error(-1, '传入secretkey值不合法,请重新传入');
  2259. }
  2260. $filename = 'logo.png';
  2261. $result = (new \app\common\services\QcloudCosService($bucket_local, $key, $secret, $bucket, $appid))->uploadTest($filename);
  2262. if ($result === true) {
  2263. return true;
  2264. } else {
  2265. return error(-1, $result);
  2266. }
  2267. }
  2268. }
  2269. if (!function_exists('file_tree')) {
  2270. function file_tree($path, $include = array()) {
  2271. $files = array();
  2272. if ($include) {
  2273. $ds = glob($path . '/{' . implode(',', $include) . '}', GLOB_BRACE);
  2274. } else {
  2275. $ds = glob($path . '/*');
  2276. }
  2277. if (is_array($ds)) {
  2278. foreach ($ds as $entry) {
  2279. if (is_file($entry)) {
  2280. $files[] = $entry;
  2281. }
  2282. if (is_dir($entry)) {
  2283. $rs = file_tree($entry);
  2284. foreach ($rs as $f) {
  2285. $files[] = $f;
  2286. }
  2287. }
  2288. }
  2289. }
  2290. return $files;
  2291. }
  2292. }
  2293. if (!function_exists('parse_path')) {
  2294. function parse_path($path)
  2295. {
  2296. $danger_char = array('../', '{php', '<?php', '<%', '<?', '..\\', '\\\\', '\\', '..\\\\', '%00', '\0', '\r');
  2297. foreach ($danger_char as $char) {
  2298. if (strexists($path, $char)) {
  2299. return false;
  2300. }
  2301. }
  2302. return $path;
  2303. }
  2304. }
  2305. if (!function_exists('bytecount')) {
  2306. function bytecount($str)
  2307. {
  2308. if (strtolower($str[strlen($str) - 1]) == 'b') {
  2309. $str = substr($str, 0, -1);
  2310. }
  2311. if (strtolower($str[strlen($str) - 1]) == 'k') {
  2312. return floatval($str) * 1024;
  2313. }
  2314. if (strtolower($str[strlen($str) - 1]) == 'm') {
  2315. return floatval($str) * 1048576;
  2316. }
  2317. if (strtolower($str[strlen($str) - 1]) == 'g') {
  2318. return floatval($str) * 1073741824;
  2319. }
  2320. }
  2321. }
  2322. if (!function_exists('attachment_alioss_datacenters')) {
  2323. function attachment_alioss_datacenters()
  2324. {
  2325. $bucket_datacenter = array(
  2326. 'oss-cn-hangzhou' => '杭州数据中心',
  2327. 'oss-cn-qingdao' => '青岛数据中心',
  2328. 'oss-cn-beijing' => '北京数据中心',
  2329. 'oss-cn-hongkong' => '香港数据中心',
  2330. 'oss-cn-shenzhen' => '深圳数据中心',
  2331. 'oss-cn-shanghai' => '上海数据中心',
  2332. 'oss-us-west-1' => '美国硅谷数据中心',
  2333. );
  2334. return $bucket_datacenter;
  2335. }
  2336. }
  2337. if (!function_exists('attachment_newalioss_auth')) {
  2338. function attachment_newalioss_auth($key, $secret, $bucket, $internal = false)
  2339. {
  2340. $buckets = attachment_alioss_buctkets($key, $secret);
  2341. $host = $internal ? '-internal.aliyuncs.com' : '.aliyuncs.com';
  2342. $url = 'http://' . $buckets[$bucket]['location'] . $host;
  2343. $filename = 'logo.png';
  2344. try {
  2345. $ossClient = new \app\common\services\aliyunoss\OssClient($key, $secret, $url);
  2346. $ossClient->uploadFile($bucket, $filename, base_path() . '/static/' . $filename);
  2347. } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
  2348. return error(1, $e->getMessage());
  2349. }
  2350. return 1;
  2351. }
  2352. }
  2353. if (!function_exists('getimagesizefromstring')) {
  2354. function getimagesizefromstring($string_data) {
  2355. $uri = 'data://application/octet-stream;base64,' . base64_encode($string_data);
  2356. return getimagesize($uri);
  2357. }
  2358. }
  2359. if (!function_exists('yz_buildCustomPostFields')) {
  2360. /**
  2361. * Build custom post fields for safe multipart POST request for php before 5.5.
  2362. * @param $fields array of key -> value fields to post.
  2363. * @return $boundary and encoded post fields.
  2364. */
  2365. function yz_buildCustomPostFields($fields)
  2366. {
  2367. // invalid characters for "name" and "filename"
  2368. static $disallow = array("\0", "\"", "\r", "\n");
  2369. // initialize body
  2370. $body = array();
  2371. // build normal parameters
  2372. foreach ($fields as $key => $value) {
  2373. $key = str_replace($disallow, "_", $key);
  2374. $body[] = implode("\r\n", array(
  2375. "Content-Disposition: form-data; name=\"{$key}\"",
  2376. '',
  2377. filter_var($value),
  2378. ));
  2379. }
  2380. // generate safe boundary
  2381. do {
  2382. $boundary = "---------------------" . md5(mt_rand() . microtime());
  2383. } while (preg_grep("/{$boundary}/", $body));
  2384. // add boundary for each parameters
  2385. foreach ($body as &$part) {
  2386. $part = "--{$boundary}\r\n{$part}";
  2387. }
  2388. unset($part);
  2389. // add final boundary
  2390. $body[] = "--{$boundary}--";
  2391. $body[] = '';
  2392. return array($boundary, implode("\r\n", $body));
  2393. }
  2394. }
  2395. if (!function_exists('resource_get')) {
  2396. function resource_get($file, $depth=2)
  2397. {
  2398. if (config('app.framework') == 'platform') {
  2399. return '/' . $file;
  2400. }
  2401. $path = $depth == 2 ? '../..' : '..';
  2402. return $path . '/addons/yun_shop/' . $file;
  2403. }
  2404. }
  2405. if (!function_exists('tpl_form_field_image')) {
  2406. function tpl_form_field_image($name, $value = '', $default = '', $options = array())
  2407. {
  2408. if (empty($default)) {
  2409. $default = static_url('resource/images/nopic.jpg');
  2410. }
  2411. $val = $default;
  2412. if (!empty($value)) {
  2413. $val = tomedia($value);
  2414. }
  2415. if (!empty($options['global'])) {
  2416. $options['global'] = true;
  2417. } else {
  2418. $options['global'] = false;
  2419. }
  2420. if (empty($options['class_extra'])) {
  2421. $options['class_extra'] = '';
  2422. }
  2423. if (isset($options['dest_dir']) && !empty($options['dest_dir'])) {
  2424. if (!preg_match('/^\w+([\/]\w+)?$/i', $options['dest_dir'])) {
  2425. exit('图片上传目录错误,只能指定最多两级目录,如: "yz_store","yz_store/d1"');
  2426. }
  2427. }
  2428. $options['direct'] = true;
  2429. $options['multiple'] = false;
  2430. if (isset($options['thumb'])) {
  2431. $options['thumb'] = !empty($options['thumb']);
  2432. }
  2433. $param = uploadParam();
  2434. $options['fileSizeLimit'] = $param['fileSizeLimit'];
  2435. $s = '';
  2436. if (!defined('TPL_INIT_IMAGE')) {
  2437. $s = '
  2438. <script type="text/javascript">
  2439. function showImageDialog(elm, opts, options) {
  2440. require(["'.$param['util'].'"], function(util){
  2441. var btn = $(elm);
  2442. var ipt = btn.parent().prev();
  2443. var val = ipt.val();
  2444. var img = ipt.parent().next().children();
  2445. options = '.str_replace('"', '\'', json_encode($options)).';
  2446. util.image(val, function(url){
  2447. if(url.url){
  2448. if(img.length > 0){
  2449. img.get(0).src = url.url;
  2450. }
  2451. ipt.val(url.attachment);
  2452. ipt.attr("filename",url.filename);
  2453. ipt.attr("url",url.url);
  2454. }
  2455. if(url.media_id){
  2456. if(img.length > 0){
  2457. img.get(0).src = "";
  2458. }
  2459. ipt.val(url.media_id);
  2460. }
  2461. }, options);
  2462. });
  2463. }
  2464. function deleteImage(elm){
  2465. $(elm).prev().attr("src", "static/resource/images/nopic.jpg");
  2466. $(elm).parent().prev().find("input").val("");
  2467. }
  2468. </script>';
  2469. define('TPL_INIT_IMAGE', true);
  2470. }
  2471. $s .= '
  2472. <div class="input-group ' . $options['class_extra'] . '">
  2473. <input type="text" name="' . $name . '" value="' . $value . '"' . ($options['extras']['text'] ? $options['extras']['text'] : '') . ' class="form-control" autocomplete="off">
  2474. <span class="input-group-btn">
  2475. <button class="btn btn-default" type="button" onclick="showImageDialog(this);">选择图片</button>
  2476. </span>
  2477. </div>
  2478. <div class="input-group ' . $options['class_extra'] . '" style="margin-top:.5em;">
  2479. <img src="' . $val . '" onerror="this.src=\'' . $default . '\'; this.title=\'图片未找到.\'" class="img-responsive img-thumbnail" ' . ($options['extras']['image'] ? $options['extras']['image'] : '') . ' width="150" />
  2480. <em class="close" style="position:absolute; top: 0px; right: -14px;" title="删除这张图片" onclick="deleteImage(this)">×</em>
  2481. </div>';
  2482. return $s;
  2483. }
  2484. }
  2485. if (!function_exists('tpl_form_field_color')) {
  2486. function tpl_form_field_color($name, $value = '')
  2487. {
  2488. $s = '';
  2489. if (!defined('TPL_INIT_COLOR')) {
  2490. $s = '
  2491. <script type="text/javascript">
  2492. $(function(){
  2493. $(".colorpicker").each(function(){
  2494. var elm = this;
  2495. util.colorpicker(elm, function(color){
  2496. $(elm).parent().prev().prev().val(color.toHexString());
  2497. $(elm).parent().prev().css("background-color", color.toHexString());
  2498. });
  2499. });
  2500. $(".colorclean").click(function(){
  2501. $(this).parent().prev().prev().val("");
  2502. $(this).parent().prev().css("background-color", "#FFF");
  2503. });
  2504. });
  2505. </script>';
  2506. define('TPL_INIT_COLOR', true);
  2507. }
  2508. $s .= '
  2509. <div class="row row-fix">
  2510. <div class="col-xs-8 col-sm-8" style="padding-right:0;">
  2511. <div class="input-group">
  2512. <input class="form-control" type="text" name="'.$name.'" placeholder="请选择颜色" value="'.$value.'">
  2513. <span class="input-group-addon" style="width:35px;border-left:none;background-color:'.$value.'"></span>
  2514. <span class="input-group-btn">
  2515. <button class="btn btn-default colorpicker" type="button">选择颜色 <i class="fa fa-caret-down"></i></button>
  2516. <button class="btn btn-default colorclean" type="button"><span><i class="fa fa-remove"></i></span></button>
  2517. </span>
  2518. </div>
  2519. </div>
  2520. </div>
  2521. ';
  2522. return $s;
  2523. }
  2524. }
  2525. if (!function_exists('safe_gpc_array')) {
  2526. function safe_gpc_array($value, $default = array())
  2527. {
  2528. if (!$value || !is_array($value)) {
  2529. return $default;
  2530. }
  2531. foreach ($value as &$row) {
  2532. if (is_numeric($row)) {
  2533. $row = safe_gpc_int($row);
  2534. } elseif (is_array($row)) {
  2535. $row = safe_gpc_array($row, $default);
  2536. } else {
  2537. $row = safe_gpc_string($row);
  2538. }
  2539. }
  2540. return $value;
  2541. }
  2542. }
  2543. if (!function_exists('safe_gpc_int')) {
  2544. function safe_gpc_int($value, $default = 0)
  2545. {
  2546. if (strpos($value, '.') !== false) {
  2547. $value = floatval($value);
  2548. $default = floatval($default);
  2549. } else {
  2550. $value = intval($value);
  2551. $default = intval($default);
  2552. }
  2553. if (!$value && $default != $value) {
  2554. $value = $default;
  2555. }
  2556. return $value;
  2557. }
  2558. }
  2559. if (!function_exists('file_remote_delete')) {
  2560. function file_remote_delete($file, $upload_type, $remote)
  2561. {
  2562. if (!$file) {
  2563. return true;
  2564. }
  2565. if ($upload_type == '2') {
  2566. $bucket = rtrim(substr($remote['alioss']['bucket'], 0, strrpos($remote['alioss']['bucket'],'@')), '@');
  2567. $buckets = attachment_alioss_buctkets($remote['alioss']['key'], $remote['alioss']['secret']);
  2568. $endpoint = 'https://' . $buckets[$bucket]['location'] . '.aliyuncs.com';
  2569. try {
  2570. $ossClient = new \app\common\services\aliyunoss\OssClient($remote['alioss']['key'], $remote['alioss']['secret'], $endpoint);
  2571. $ossClient->deleteObject($bucket, $file);
  2572. } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
  2573. return error(1, '删除oss远程文件失败');
  2574. }
  2575. } elseif ($upload_type == '4') {
  2576. $result = (new \app\common\services\QcloudCosService(
  2577. $remote['cos']['local'],
  2578. $remote['cos']['secretid'],
  2579. $remote['cos']['secretkey'],
  2580. $remote['cos']['bucket'],
  2581. $remote['cos']['appid']
  2582. ))->delete($file);
  2583. if (!$result) {
  2584. return error(-1, '删除cos远程文件失败');
  2585. }
  2586. } elseif ($upload_type == '5') {
  2587. try {
  2588. $result = (new \app\common\services\ObsService())->delete($file);
  2589. } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
  2590. return error(1, '删除oss远程文件失败');
  2591. }
  2592. }
  2593. return true;
  2594. }
  2595. }
  2596. if (!function_exists('material_list')) {
  2597. function material_list($type = '', $server = '', $page = array('page_index' => 1, 'page_size' => 24), $uniacid = 0, $offset)
  2598. {
  2599. $core_attach = array('local' => new \app\platform\modules\application\models\CoreAttach, 'perm' => new app\platform\modules\application\models\WechatAttachment);
  2600. $conditions['uniacid'] = $uniacid;
  2601. $core_attach = $core_attach[$server];
  2602. switch ($type) {
  2603. case 'voice' :
  2604. $conditions['type'] = $server == 'local' ? 2 : 'voice';
  2605. break;
  2606. case 'video' :
  2607. $conditions['type'] = $server == 'local' ? 3 : 'video';
  2608. break;
  2609. default :
  2610. $conditions['type'] = $server == 'local' ? 1 : 'image';
  2611. break;
  2612. }
  2613. if ($server == 'local') {
  2614. $core_attach = $core_attach->where($conditions)->orderBy('created_at', 'desc');
  2615. $total = $core_attach->count();
  2616. $core_attach = $core_attach->offset($offset)->limit($page['page_size'])->get();
  2617. } else {
  2618. $conditions['model'] = 'perm';
  2619. $core_attach = $core_attach->where($conditions)->orderBy('created_at', 'desc');
  2620. $total = $core_attach->count();
  2621. $core_attach = $core_attach->offset($offset)->limit($page['page_size'])->get();
  2622. if ($type == 'video') {
  2623. foreach ($core_attach as &$row) {
  2624. $row['tag'] = $row['tag'] == '' ? array() : iunserializer($row['tag']);
  2625. }
  2626. unset($row);
  2627. }
  2628. }
  2629. $pager = pagination($total, $page['page_index'], $page['page_size'], '', $context = array('before' => 5, 'after' => 4, 'isajax' => '1'));
  2630. $material_news = array('material_list' => $core_attach, 'page' => $pager);
  2631. return $material_news;
  2632. }
  2633. }
  2634. if (!function_exists('iunserializer')) {
  2635. function iunserializer($value)
  2636. {
  2637. if (!$value) {
  2638. return array();
  2639. }
  2640. if (!is_serialized($value)) {
  2641. return $value;
  2642. }
  2643. $result = unserialize($value);
  2644. if ($result === false) {
  2645. $temp = preg_replace_callback('!s:(\d+):"(.*?)";!s', function ($matchs) {
  2646. return 's:' . strlen($matchs[2]) . ':"' . $matchs[2] . '";';
  2647. }, $value);
  2648. return unserialize($temp);
  2649. } else {
  2650. return $result;
  2651. }
  2652. }
  2653. }
  2654. if (!function_exists('is_serialized')) {
  2655. function is_serialized($data, $strict = true)
  2656. {
  2657. if (!is_string($data)) {
  2658. return false;
  2659. }
  2660. $data = trim($data);
  2661. if ('N;' == $data) {
  2662. return true;
  2663. }
  2664. if (strlen($data) < 4) {
  2665. return false;
  2666. }
  2667. if (':' !== $data[1]) {
  2668. return false;
  2669. }
  2670. if ($strict) {
  2671. $lastc = substr($data, -1);
  2672. if (';' !== $lastc && '}' !== $lastc) {
  2673. return false;
  2674. }
  2675. } else {
  2676. $semicolon = strpos($data, ';');
  2677. $brace = strpos($data, '}');
  2678. if (false === $semicolon && false === $brace)
  2679. return false;
  2680. if (false !== $semicolon && $semicolon < 3)
  2681. return false;
  2682. if (false !== $brace && $brace < 4)
  2683. return false;
  2684. }
  2685. $token = $data[0];
  2686. switch ($token) {
  2687. case 's' :
  2688. if ($strict) {
  2689. if ('"' !== substr($data, -2, 1)) {
  2690. return false;
  2691. }
  2692. } elseif (false === strpos($data, '"')) {
  2693. return false;
  2694. }
  2695. case 'a' :
  2696. return (bool)preg_match("/^{$token}:[0-9]+:/s", $data);
  2697. case 'O' :
  2698. return false;
  2699. case 'b' :
  2700. case 'i' :
  2701. case 'd' :
  2702. $end = $strict ? '$' : '';
  2703. return (bool)preg_match("/^{$token}:[0-9.E-]+;$end/", $data);
  2704. }
  2705. return false;
  2706. }
  2707. }
  2708. if (!function_exists('ver_compare')) {
  2709. /**
  2710. * 为了兼容微擎使用此方法
  2711. * @param $version1
  2712. * @param $version2
  2713. * @return mixed
  2714. */
  2715. function ver_compare($version1, $version2)
  2716. {
  2717. $version1 = str_replace('.', '', $version1);
  2718. $version2 = str_replace('.', '', $version2);
  2719. $oldLength = istrlen($version1);
  2720. $newLength = istrlen($version2);
  2721. if (is_numeric($version1) && is_numeric($version2)) {
  2722. if ($oldLength > $newLength) {
  2723. $version2 .= str_repeat('0', $oldLength - $newLength);
  2724. }
  2725. if ($newLength > $oldLength) {
  2726. $version1 .= str_repeat('0', $newLength - $oldLength);
  2727. }
  2728. $version1 = intval($version1);
  2729. $version2 = intval($version2);
  2730. }
  2731. return version_compare($version1, $version2);
  2732. }
  2733. }
  2734. if (!function_exists('istrlen')) {
  2735. /**
  2736. * 为了兼容微擎使用此方法
  2737. * @param $string
  2738. * @param string $charset
  2739. * @return int
  2740. */
  2741. function istrlen($string, $charset = '')
  2742. {
  2743. if (!$charset) {
  2744. $charset = \YunShop::app()['charset'];
  2745. }
  2746. if (strtolower($charset) == 'gbk') {
  2747. $charset = 'gbk';
  2748. } else {
  2749. $charset = 'utf8';
  2750. }
  2751. if (function_exists('mb_strlen') && extension_loaded('mbstring')) {
  2752. return mb_strlen($string, $charset);
  2753. } else {
  2754. $n = $noc = 0;
  2755. $strlen = strlen($string);
  2756. if ($charset == 'utf8') {
  2757. while ($n < $strlen) {
  2758. $t = ord($string[$n]);
  2759. if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  2760. $n++;
  2761. $noc++;
  2762. } elseif (194 <= $t && $t <= 223) {
  2763. $n += 2;
  2764. $noc++;
  2765. } elseif (224 <= $t && $t <= 239) {
  2766. $n += 3;
  2767. $noc++;
  2768. } elseif (240 <= $t && $t <= 247) {
  2769. $n += 4;
  2770. $noc++;
  2771. } elseif (248 <= $t && $t <= 251) {
  2772. $n += 5;
  2773. $noc++;
  2774. } elseif ($t == 252 || $t == 253) {
  2775. $n += 6;
  2776. $noc++;
  2777. } else {
  2778. $n++;
  2779. }
  2780. }
  2781. } else {
  2782. while ($n < $strlen) {
  2783. $t = ord($string[$n]);
  2784. if ($t > 127) {
  2785. $n += 2;
  2786. $noc++;
  2787. } else {
  2788. $n++;
  2789. $noc++;
  2790. }
  2791. }
  2792. }
  2793. return $noc;
  2794. }
  2795. }
  2796. }
  2797. if (!function_exists('mb_strlen')) {
  2798. function mb_strlen($string, $charset = '') {
  2799. return istrlen($string, $charset);
  2800. }
  2801. }
  2802. if (!function_exists('tpl_form_field_daterange')) {
  2803. /**
  2804. * 为了兼容微擎使用此方法
  2805. * @param $name
  2806. * @param array $value
  2807. * @param bool $time
  2808. * @return string
  2809. */
  2810. function tpl_form_field_daterange($name, $value = array(), $time = false) {
  2811. $s = '';
  2812. if (empty($time) && !defined('TPL_INIT_DATERANGE_DATE')) {
  2813. $s = '
  2814. <script type="text/javascript">
  2815. require(["daterangepicker"], function(){
  2816. $(function(){
  2817. $(".daterange.daterange-date").each(function(){
  2818. var elm = this;
  2819. $(this).daterangepicker({
  2820. startDate: $(elm).prev().prev().val(),
  2821. endDate: $(elm).prev().val(),
  2822. format: "YYYY-MM-DD"
  2823. }, function(start, end){
  2824. $(elm).find(".date-title").html(start.toDateStr() + " 至 " + end.toDateStr());
  2825. $(elm).prev().prev().val(start.toDateStr());
  2826. $(elm).prev().val(end.toDateStr());
  2827. });
  2828. });
  2829. });
  2830. });
  2831. </script>
  2832. ';
  2833. define('TPL_INIT_DATERANGE_DATE', true);
  2834. }
  2835. if (!empty($time) && !defined('TPL_INIT_DATERANGE_TIME')) {
  2836. $s = '
  2837. <script type="text/javascript">
  2838. require(["daterangepicker"], function(){
  2839. $(function(){
  2840. $(".daterange.daterange-time").each(function(){
  2841. var elm = this;
  2842. $(this).daterangepicker({
  2843. startDate: $(elm).prev().prev().val(),
  2844. endDate: $(elm).prev().val(),
  2845. format: "YYYY-MM-DD HH:mm",
  2846. timePicker: true,
  2847. timePicker12Hour : false,
  2848. timePickerIncrement: 1,
  2849. minuteStep: 1
  2850. }, function(start, end){
  2851. $(elm).find(".date-title").html(start.toDateTimeStr() + " 至 " + end.toDateTimeStr());
  2852. $(elm).prev().prev().val(start.toDateTimeStr());
  2853. $(elm).prev().val(end.toDateTimeStr());
  2854. });
  2855. });
  2856. });
  2857. });
  2858. </script>
  2859. ';
  2860. define('TPL_INIT_DATERANGE_TIME', true);
  2861. }
  2862. if ($value['starttime'] !== false && $value['start'] !== false) {
  2863. if($value['start']) {
  2864. $value['starttime'] = empty($time) ? date('Y-m-d',strtotime($value['start'])) : date('Y-m-d H:i',strtotime($value['start']));
  2865. }
  2866. $value['starttime'] = empty($value['starttime']) ? (empty($time) ? date('Y-m-d') : date('Y-m-d H:i') ): $value['starttime'];
  2867. } else {
  2868. $value['starttime'] = '请选择';
  2869. }
  2870. if ($value['endtime'] !== false && $value['end'] !== false) {
  2871. if($value['end']) {
  2872. $value['endtime'] = empty($time) ? date('Y-m-d',strtotime($value['end'])) : date('Y-m-d H:i',strtotime($value['end']));
  2873. }
  2874. $value['endtime'] = empty($value['endtime']) ? $value['starttime'] : $value['endtime'];
  2875. } else {
  2876. $value['endtime'] = '请选择';
  2877. }
  2878. $s .= '
  2879. <input name="'.$name . '[start]'.'" type="hidden" value="'. $value['starttime'].'" />
  2880. <input name="'.$name . '[end]'.'" type="hidden" value="'. $value['endtime'].'" />
  2881. <button class="btn btn-default daterange '.(!empty($time) ? 'daterange-time' : 'daterange-date').'" type="button"><span class="date-title">'.$value['starttime'].' 至 '.$value['endtime'].'</span> <i class="fa fa-calendar"></i></button>
  2882. ';
  2883. return $s;
  2884. }
  2885. }
  2886. if (!function_exists('tpl_ueditor')) {
  2887. /**
  2888. * 为了兼容微擎使用此方法
  2889. * @param $id
  2890. * @param string $value
  2891. * @param array $options
  2892. * @return string
  2893. */
  2894. function tpl_ueditor($id, $value = '', $options = array())
  2895. {
  2896. $s = '';
  2897. $options['height'] = empty($options['height']) ? 200 : $options['height'];
  2898. $options['allow_upload_video'] = isset($options['allow_upload_video']) ? $options['allow_upload_video'] : true;
  2899. $param = uploadParam();
  2900. $s .= !empty($id) ? "<textarea id=\"{$id}\" name=\"{$id}\" type=\"text/plain\" style=\"height:{$options['height']}px;\">{$value}</textarea>" : '';
  2901. $s .= "
  2902. <script type=\"text/javascript\">
  2903. require(['".$param['util']."'], function(util){
  2904. util.editor('" . ($id ? $id : "") . "', {
  2905. height : {$options['height']},
  2906. dest_dir : '" . ($options['dest_dir'] ? $options['dest_dir'] : "") . "',
  2907. image_limit : " . (intval($param['global']['image_limit']) * 1024) . ",
  2908. allow_upload_video : " . ($options['allow_upload_video'] ? 'true' : 'false') . ",
  2909. audio_limit : " . (intval($param['global']['audio_limit']) * 1024) . ",
  2910. callback : ''
  2911. });
  2912. });
  2913. </script>";
  2914. return $s;
  2915. }
  2916. }
  2917. if (!function_exists('image_put_path')) {
  2918. function image_put_path()
  2919. {
  2920. if (config('app.framework') == 'platform') {
  2921. return base_path('static/upload/');
  2922. }
  2923. return IA_ROOT . '/attachment/';
  2924. }
  2925. }
  2926. if (!function_exists('iserializer')) {
  2927. /**
  2928. * 为了兼容微擎使用此方法
  2929. * @param $value
  2930. * @return string
  2931. */
  2932. function iserializer($value) {
  2933. return serialize($value);
  2934. }
  2935. }
  2936. if (!function_exists('tpl_form_field_date')) {
  2937. /**
  2938. * 为了兼容微擎使用此方法
  2939. * @param $name
  2940. * @param string $value
  2941. * @param bool $withtime
  2942. * @return string
  2943. */
  2944. function tpl_form_field_date($name, $value = '', $withtime = false)
  2945. {
  2946. return _tpl_form_field_date($name, $value, $withtime);
  2947. }
  2948. }
  2949. if (!function_exists('_tpl_form_field_date')) {
  2950. /**
  2951. * 为了兼容微擎使用此方法
  2952. * @param $name
  2953. * @param string $value
  2954. * @param bool $withtime
  2955. * @return string
  2956. */
  2957. function _tpl_form_field_date($name, $value = '', $withtime = false)
  2958. {
  2959. $s = '';
  2960. $withtime = !$withtime ? false : true;
  2961. if ($value) {
  2962. $value = strexists($value, '-') ? strtotime($value) : $value;
  2963. } else {
  2964. $value = TIMESTAMP;
  2965. }
  2966. $value = ($withtime ? date('Y-m-d H:i:s', $value) : date('Y-m-d', $value));
  2967. $s .= '<input type="text" name="' . $name . '" value="' . $value . '" placeholder="请选择日期时间" readonly="readonly" class="datetimepicker form-control" style="padding-left:12px;" />';
  2968. $s .= '
  2969. <script type="text/javascript">
  2970. require(["datetimepicker"], function(){
  2971. var option = {
  2972. lang : "zh",
  2973. step : 5,
  2974. timepicker : ' . (!empty($withtime) ? "true" : "false") . ',
  2975. closeOnDateSelect : true,
  2976. format : "Y-m-d' . (!empty($withtime) ? ' H:i"' : '"') . '
  2977. };
  2978. $(".datetimepicker[name = \'' . $name . '\']").datetimepicker(option);
  2979. });
  2980. </script>';
  2981. return $s;
  2982. }
  2983. }
  2984. if (!function_exists('user_register')) {
  2985. /**
  2986. * 添加用户(为了兼容微擎使用此方法)
  2987. * @param $user
  2988. * @return mixed
  2989. */
  2990. function user_register ($user, $default = null)
  2991. {
  2992. $data = [
  2993. 'username' => trim($user['username']),
  2994. 'password' => bcrypt($user['password']),
  2995. 'salt' => randNum(8),
  2996. 'lastvisit' => time(),
  2997. 'lastip' => Utils::getClientIp(),
  2998. 'joinip' => Utils::getClientIp(),
  2999. 'status' => 2,
  3000. 'remark' => '',
  3001. 'owner_uid' => 0
  3002. ];
  3003. $users_model = new WeiQingUsers;
  3004. $users_model->fill($data);
  3005. $users_model->save();
  3006. $user_uid = $users_model['uid'];
  3007. return $user_uid;
  3008. }
  3009. }
  3010. if (!function_exists('user_hash')) {
  3011. /**
  3012. * 密码加密(为了兼容微擎使用此方法)
  3013. * @param $new_pwd
  3014. * @param $salt
  3015. * @return string
  3016. */
  3017. function user_hash($new_pwd, $salt)
  3018. {
  3019. if (config('app.framework') == 'platform') {
  3020. $password = bcrypt($new_pwd);
  3021. } else {
  3022. global $_W;
  3023. $password = sha1("{$new_pwd}-{$salt}-{$_W['config']['setting']['authkey']}");
  3024. }
  3025. return $password;
  3026. }
  3027. }
  3028. if (!function_exists('uploadUrl')) {
  3029. /**
  3030. * 上传 相关组件 使用的url
  3031. * @return mixed
  3032. */
  3033. function uploadUrl($type = 'default')
  3034. {
  3035. $rand_str = randNum(4, true);
  3036. if (config('app.framework') == 'platform') {
  3037. $url['upload_url'] = '/admin/shop?route=upload.upload.jsUpload&upload_type=';
  3038. $url['image_url'] = '/admin/shop?route=upload.upload.jsImage';
  3039. $url['fetch_url'] = '/admin/shop?route=upload.upload.fetch';
  3040. $url['delet_url'] = '/admin/shop?route=upload.upload.delete';
  3041. $url['video_url'] = '/admin/system/upload/video?local=local&type=video&pagesize=5';
  3042. } else {
  3043. $url['upload_url'] = './index.php?c=site&a=entry&m=yun_shop&do='.$rand_str.'&route=upload.upload.jsUpload&upload_type=';
  3044. if ($type == 'new') {
  3045. $image_url = str_replace('/web','.',yzWebUrl('upload.uploadImage.getImage'));
  3046. $url['image_url'] = $image_url;
  3047. } elseif($type == 'default') {
  3048. $url['image_url'] = './index.php?c=site&a=entry&m=yun_shop&do='.$rand_str.'&route=upload.upload.jsImage';
  3049. }
  3050. $url['fetch_url'] = './index.php?c=site&a=entry&m=yun_shop&do='.$rand_str.'&route=upload.upload.fetch';
  3051. $url['delet_url'] = './index.php?c=site&a=entry&m=yun_shop&do='.$rand_str.'&route=upload.upload.delete';
  3052. $url['video_url'] = './index.php?c=site&a=entry&m=yun_shop&do='.$rand_str.'&route=upload.upload.getVideo&local=local&type=video&pagesize=5';
  3053. }
  3054. return $url;
  3055. }
  3056. }
  3057. if (!function_exists('uploadParam')) {
  3058. /**
  3059. * ImageHelper 上传需要的变量
  3060. * @return mixed
  3061. */
  3062. function uploadParam()
  3063. {
  3064. $util = 'util';
  3065. $u_url = 'static/resource/js/app/';
  3066. if (config('app.framework') == 'platform') {
  3067. $global = SystemSetting::settingLoad('global', 'system_global');
  3068. $result['fileSizeLimitImage'] = intval($global['image_limit']) * 1024;
  3069. $result['fileSizeLimitAudio'] = intval($global['audio_limit']) * 1024;
  3070. $util = 'utils';
  3071. $util_url = '/' . $u_url . $util;
  3072. } else {
  3073. $util_url = '/addons/yun_shop/' . $u_url . $util;
  3074. $global = \YunShop::app()->setting['upload'];
  3075. $result['fileSizeLimitImage'] = intval($global['image']['limit']) * 1024;
  3076. $result['fileSizeLimitAudio'] = intval($global['audio']['limit']) * 1024;
  3077. }
  3078. $result['util'] = $util;
  3079. $result['global'] = $global;
  3080. $result['util_url'] = $util_url;
  3081. return $result;
  3082. }
  3083. }
  3084. if (!function_exists('resource_absolute')) {
  3085. function resource_absolute($file)
  3086. {
  3087. if (config('app.framework') == 'platform') {
  3088. return '/' . $file;
  3089. }
  3090. return '/addons/yun_shop/' . $file;
  3091. }
  3092. }
  3093. if (!function_exists('upload_image_local')) {
  3094. function upload_image_local($file)
  3095. {
  3096. if (config('app.framework') == 'platform') {
  3097. if (strexists($file, 'newimage')) {
  3098. $file = ImageHelper::getImageUrl('static/upload/' . substr($file,strripos($file,"newimage")));
  3099. }else {
  3100. $file = ImageHelper::getImageUrl('static/upload/' . substr($file,strripos($file,"image")));
  3101. }
  3102. } else {
  3103. $file = ImageHelper::getImageUrl('attachment/' . substr($file,strripos($file,"image")));
  3104. }
  3105. return $file;
  3106. }
  3107. }
  3108. if (!function_exists('change_to_local_url')) {
  3109. function change_to_local_url($file)
  3110. {
  3111. if (strexists($file, 'storage')) {
  3112. $file = strstr($file, 'storage');
  3113. return request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . $file;
  3114. }
  3115. if (strexists($file, 'static/upload/')) {
  3116. $file = strstr($file, 'static/upload/');
  3117. return request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . $file;
  3118. }
  3119. if (strexists($file, 'attachment/')) {
  3120. $file = strstr($file, 'attachment/');
  3121. return request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . $file;
  3122. }
  3123. $disks = config('filesystems.disks');
  3124. foreach ($disks as $key => $disk) {
  3125. if (strexists($file, $key)) {
  3126. $file = strstr($file, $key);
  3127. break;
  3128. }
  3129. }
  3130. if (config('app.framework') == 'platform') {
  3131. $file = request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . 'static/upload/' . $file;
  3132. } else {
  3133. $file = request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . 'attachment/' . $file;
  3134. }
  3135. return $file;
  3136. }
  3137. }
  3138. if (!function_exists('setSystemVersion')) {
  3139. function setSystemVersion($version, $file)
  3140. {
  3141. $str = file_get_contents(base_path('config/') . $file);
  3142. $str = preg_replace('/"[\d\.]+"/', '"'. $version . '"', $str);
  3143. file_put_contents(base_path('config/') . $file, $str);
  3144. }
  3145. }
  3146. if (!function_exists('changeUmImgPath')) {
  3147. function changeUmImgPath($str = '')
  3148. {
  3149. $details = htmlspecialchars_decode($str);
  3150. preg_match_all("/(\s+src\s?\=)\s?[\'|\"]([^\'|\"]*)/is", $details, $imgs);
  3151. $old_arr = [];
  3152. $new_arr = [];
  3153. if (isset($imgs[2])) {
  3154. foreach ($imgs[2] as $img) {
  3155. $old_arr[] = $img;
  3156. $new_arr[] = yz_tomedia($img);
  3157. }
  3158. }
  3159. $str = str_replace($old_arr, $new_arr, $details);
  3160. return $str;
  3161. }
  3162. }
  3163. //bc计算金额比例
  3164. if (!function_exists('proportionMath')) {
  3165. function proportionMath($money, $proportion)
  3166. {
  3167. return bcdiv(bcmul($money, $proportion, 2), 100, 2);
  3168. }
  3169. }
  3170. if (!function_exists('changeSpecialSymbols')) {
  3171. function changeSpecialSymbols($str = '')
  3172. {
  3173. $regex = "/\/|\~|\,|\。|\!|\?|\“|\”|\【|\】|\『|\』|\:|\;|\《|\》|\’|\‘|\ |\·|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
  3174. return preg_replace($regex,'', $str);
  3175. }
  3176. }
  3177. if (!function_exists('verifyPasswordStrength')) {
  3178. /**
  3179. * 校验密码强度(更多用于操作员之类的密码效验)
  3180. * @param string $password
  3181. * @return bool|\Illuminate\Http\JsonResponse
  3182. */
  3183. function verifyPasswordStrength($password = '')
  3184. {
  3185. // if (preg_match('/[\x{4e00}-\x{9fa5}]/u', $password)>0) {
  3186. // return '密码不能含有中文';
  3187. // }
  3188. $is_check = 0;
  3189. if (config('app.APP_Framework', false) == 'platform') {
  3190. //独立版
  3191. $loginset = SystemSetting::settingLoad('loginset', 'system_loginset');
  3192. $is_check = $loginset['password_verify'];
  3193. }elseif(config('app.APP_Framework', false) != 'platform'){
  3194. //微擎版
  3195. if (\Illuminate\Support\Facades\Schema::hasTable('core_settings')) {
  3196. $setting = \Illuminate\Support\Facades\DB::table('core_settings')->where('key','register')->first();
  3197. if($setting){
  3198. $value = unserialize($setting['value']);
  3199. $is_check = $value['safe']?:0;
  3200. }
  3201. }
  3202. }
  3203. if ($is_check == 1) {
  3204. // if (!preg_match('/(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,30}/', $password)) {
  3205. // return '密码至少为8-16个字符,至少1个大写字母,1个小写字母和一个数字,其他可以任意字符';
  3206. // }
  3207. if (!preg_match('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[.!~@#$%^&*?\(\)+_-]).{8,18}$/', $password)) {
  3208. return '密码长度至少为8位,最多18位,要求包括数字,大小写字母和特殊字符';
  3209. }
  3210. }
  3211. return true;
  3212. }
  3213. }
  3214. if (!function_exists('getMiniAccessToken')) {
  3215. /**
  3216. * 获取小程序全局access_token
  3217. * @param false $force_refresh 强制刷新
  3218. * @return false|mixed
  3219. * @throws \GuzzleHttp\Exception\GuzzleException
  3220. */
  3221. function getMiniAccessToken($force_refresh = false)
  3222. {
  3223. $set = \Setting::get('plugin.min_app');
  3224. $cache_key = 'mini_token:'.$set['key'];
  3225. $token = Redis::get($cache_key);
  3226. if ($force_refresh || empty($token)) {
  3227. $get_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
  3228. $get_token_url = sprintf($get_token_url, $set['key'],$set['secret']);
  3229. $res = (new \GuzzleHttp\Client)->request('GET', $get_token_url);
  3230. $token = json_decode($res->getBody()->getContents(), JSON_FORCE_OBJECT);
  3231. if (isset($token['errcode'])) {
  3232. \Log::debug('------生成小程序二维码获取token出错------', $token);
  3233. return false;
  3234. }
  3235. Redis::setex($cache_key,$token['expires_in']-1500,$token['access_token']);
  3236. return $token['access_token'];
  3237. }
  3238. return $token;
  3239. }
  3240. }
  3241. if (!function_exists('miniVersionCompare')) {
  3242. /**
  3243. * 小程序版本比较,小于传入版本返回false,其他返回true
  3244. * @param string $version
  3245. * @return bool
  3246. */
  3247. function miniVersionCompare($version = '')
  3248. {
  3249. //不是小程序直接返回
  3250. if (request()->type != 2) {
  3251. return true;
  3252. }
  3253. $mini_version = request()->mini_version;
  3254. $mini_version = str_replace('v','',$mini_version);
  3255. $mini_version = explode('.',$mini_version);
  3256. $version = explode('.',$version);
  3257. //版本验证
  3258. foreach ($mini_version as $key=>$value) {
  3259. if ($mini_version[$key] < $version[$key]) {
  3260. return false;
  3261. }
  3262. }
  3263. return true;
  3264. }
  3265. }
  3266. if (!function_exists('versionCompare')) {
  3267. /**
  3268. * H5版本比较,小于传入版本返回false,其他返回true
  3269. * @param string $version
  3270. * @return bool
  3271. */
  3272. function versionCompare($version = '')
  3273. {
  3274. if (request()->type == 2) {
  3275. return true;
  3276. }
  3277. $front_version = request()->version;
  3278. $front_version = str_replace('v','',$front_version);
  3279. $front_version = explode('.',$front_version);
  3280. $version = explode('.',$version);
  3281. //版本验证
  3282. foreach ($front_version as $key=>$value) {
  3283. if ($front_version[$key] < $version[$key]) {
  3284. return false;
  3285. }
  3286. }
  3287. return true;
  3288. }
  3289. }
  3290. if (!function_exists('substrCut')) {
  3291. /**
  3292. * 只保留字符串首尾字符,隐藏中间用*代替(两个字符时只显示第一个)
  3293. * @param string $user_name 姓名
  3294. * @return string 格式化后的姓名
  3295. */
  3296. function substrCut($user_name) {
  3297. $strlen = mb_strlen($user_name, 'utf-8');
  3298. $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
  3299. $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
  3300. if ($strlen < 2) {
  3301. return $user_name;
  3302. } else {
  3303. return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
  3304. }
  3305. }
  3306. }
  3307. if (!function_exists('validatePassword')) {
  3308. /**
  3309. * 密码强度效验统一规则(更多用于平台的密码强度效验)
  3310. * @param $password
  3311. * @return string
  3312. */
  3313. function validatePassword($password) {
  3314. $is_check = 0;
  3315. if (config('app.APP_Framework', false) == 'platform') {
  3316. //独立版
  3317. $loginset = SystemSetting::settingLoad('loginset', 'system_loginset');
  3318. $is_check = $loginset['password_verify'];
  3319. }elseif(config('app.APP_Framework', false) != 'platform'){
  3320. //微擎版
  3321. if (\Illuminate\Support\Facades\Schema::hasTable('core_settings')) {
  3322. $setting = \Illuminate\Support\Facades\DB::table('core_settings')->where('key','register')->first();
  3323. if($setting){
  3324. $value = unserialize($setting['value']);
  3325. $is_check = $value['safe']?:0;
  3326. }
  3327. }
  3328. }
  3329. if ($is_check == 1) {
  3330. if (!preg_match('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[.!~@#$%^&*?\(\)+_-]).{8,18}$/', $password)) {
  3331. return '密码长度至少为8位,要求包括数字,大小写字母和特殊字符';
  3332. }
  3333. }
  3334. return true;
  3335. }
  3336. /*
  3337. if (!function_exists("yz_tpl_ueditor")) {
  3338. function yz_tpl_ueditor($id, $value = '', $options = array()){
  3339. $upload_url1 = yzWebFullUrl('upload.uploadV2.upload-vue');
  3340. if (config('app.framework') == 'platform') {
  3341. $file_dir = '';
  3342. } else {
  3343. $file_dir = '../addons/yun_shop';
  3344. }
  3345. $s = '';
  3346. $s .= '<script src="'.$file_dir.'/static/yunshop/tinymce4.7.5/tinymce.min.js"></script>
  3347. <script>
  3348. tinymce.init({
  3349. selector: \'#textarea\',
  3350. fontsize_formats: "8px 10px 12px 14px 18px 24px 36px",
  3351. plugins: [\'advlist anchor autolink autoresize code codesample colorpicker contextmenu directionality emoticons fullscreen hr image imagetools insertdatetime link charmap lists media nonbreaking noneditable pagebreak preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount powerpaste bdmap \'],
  3352. toolbar: [\'forecolor backcolor searchreplace bold italic underline strikethrough fontsizeselect\',\'alignleft aligncenter alignright outdent indent ltr rtl blockquote undo redo removeformat subscript superscript code codesample\', \'hr bullist numlist link image charmap preview anchor pagebreak print insertdatetime media table emoticons fullscreen bdmap \'],
  3353. language:\'zh_CN\',
  3354. height: "500px",
  3355. file_picker_callback: function(callback, value, meta) {
  3356. //文件分类
  3357. var filetype = \'.pdf, .jpg, .jpeg, .png, .gif, .mp3, .mp4\';
  3358. //后端接收上传文件的地址
  3359. var upurl = \''.$upload_url1.'\' +\'&upload_type=video\';
  3360. //为不同插件指定文件类型及后端地址
  3361. switch (meta.filetype) {
  3362. case \'image\':
  3363. upurl = \''.$upload_url1.'\' +\'&upload_type=image\';
  3364. filetype = \'.jpg, .jpeg, .png, .gif\';
  3365. break;
  3366. case \'media\':
  3367. filetype = \'.mp3, .mp4\';
  3368. break;
  3369. case \'file\':
  3370. default:
  3371. }
  3372. //模拟出一个input用于添加本地文件
  3373. var input = document.createElement(\'input\');
  3374. input.setAttribute(\'type\', \'file\');
  3375. input.setAttribute(\'accept\', filetype);
  3376. input.click();
  3377. input.onchange = function(F) {
  3378. var file = this.files[0];
  3379. // const loading = component.$loading({
  3380. // lock: true,
  3381. // text: \'正在上传\',
  3382. // spinner: \'el-icon-loading\',
  3383. // background: \'rgba(0, 0, 0, 0.7)\'
  3384. // });
  3385. var xhr, formData;
  3386. // console.log(file, file.name);
  3387. xhr = new XMLHttpRequest();
  3388. xhr.withCredentials = false;
  3389. xhr.open(\'POST\', upurl);
  3390. xhr.onload = function() {
  3391. var json;
  3392. if (xhr.status != 200) {
  3393. loading.close();
  3394. // failure(\'HTTP Error: \' + xhr.status);
  3395. return;
  3396. }
  3397. json = JSON.parse(xhr.responseText);
  3398. if (!json || typeof json.location != \'string\') {
  3399. // failure(\'Invalid JSON: \' + xhr.responseText);
  3400. return;
  3401. }
  3402. // loading.close();
  3403. callback(encodeURI(json.location), {
  3404. title: file.name
  3405. });
  3406. };
  3407. formData = new FormData();
  3408. formData.append(\'file\', file, file.name);
  3409. xhr.send(formData);
  3410. };
  3411. },
  3412. media_url_resolver: (data, resolve)=> {
  3413. try {
  3414. let videoUri = encodeURI(data.url);
  3415. if(data.url.indexOf(\'.mp4\')>-1) {
  3416. // 判断是否mp4 否则用ifarme嵌套
  3417. let embedHtml = `<p>
  3418. <video src=${ data.url } width="100%" height="auto" style="max-width: 100%;" allowfullscreen="false" controls="controls" controlslist="nodownload">
  3419. </video>
  3420. </p>`;
  3421. resolve({ html: embedHtml });
  3422. }else {
  3423. let embedHtml = `<p>
  3424. <iframe frameborder="0" src=${ data.url } width="100%" height="100%" style="max-width: 100%;">
  3425. </iframe>
  3426. </p>`;
  3427. resolve({ html: embedHtml });
  3428. }
  3429. } catch (e) {
  3430. resolve({ html: "" });
  3431. }
  3432. },
  3433. });
  3434. </script>
  3435. ';
  3436. $s .= '
  3437. <form method="post">
  3438. <textarea id="textarea" name="'.$id.'" style="height:500px;">'.$value.'</textarea>
  3439. </form>';
  3440. return $s;
  3441. }
  3442. }
  3443. */
  3444. }
  3445. if (!function_exists('passwordVerifyStatus')) {
  3446. /**
  3447. * @return bool|string
  3448. */
  3449. function passwordVerifyStatus()
  3450. {
  3451. $is_check = 0;
  3452. if (config('app.APP_Framework', false) == 'platform') {
  3453. //独立版
  3454. $loginset = SystemSetting::settingLoad('loginset', 'system_loginset');
  3455. $is_check = $loginset['password_verify'];
  3456. }elseif(config('app.APP_Framework', false) != 'platform'){
  3457. //微擎版
  3458. if (\Illuminate\Support\Facades\Schema::hasTable('core_settings')) {
  3459. $setting = \Illuminate\Support\Facades\DB::table('core_settings')->where('key','register')->first();
  3460. if($setting){
  3461. $value = unserialize($setting['value']);
  3462. $is_check = $value['safe']?:0;
  3463. }
  3464. }
  3465. }
  3466. if ($is_check == 1) {
  3467. return true;//开启了密码强度效验
  3468. }
  3469. return false;
  3470. }
  3471. /**
  3472. * 四舍六入五成双规则、银行进位法
  3473. * 被修约的数字等于5时,要看5前面的数字,
  3474. * 若是奇数则进位,若是偶数则将5舍掉,即修约后末尾数字都成为偶数;
  3475. * 若5的后面还有不为'0'的任何数,则此时无论5的前面是奇数还是偶数,均应进位
  3476. */
  3477. if (!function_exists('bankerRounding')) {
  3478. function bankerRounding($money, $precision = 2)
  3479. {
  3480. return round($money,$precision,PHP_ROUND_HALF_EVEN);
  3481. }
  3482. }
  3483. }