| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750 |
- <?php
- use Illuminate\Support\Facades\Redis;
- use Illuminate\Support\Str;
- use Illuminate\Support\Arr;
- use app\common\services\PermissionService;
- use app\common\helpers\Url;
- use Ixudra\Curl\Facades\Curl;
- use app\common\models\user\WeiQingUsers;
- use app\common\services\Utils;
- use \app\platform\modules\system\models\SystemSetting;
- use \app\common\helpers\Client;
- use app\common\helpers\ImageHelper;
- if (!function_exists("yz_tpl_ueditor")) {
- function yz_tpl_ueditor($id, $value = '', $options = array())
- {
- if (config('app.framework') == 'platform') {
- $file_dir = '';
- } else {
- $file_dir = '../addons/yun_shop';
- }
- $s = '';
- $fileUploader = resource_get('static/js/fileUploader.min.js');
- if (!defined('TPL_INIT_UEDITOR')) {
- if (config('app.framework') == 'platform') {
- $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">';
- } else {
- $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">';
- }
- }
- $url = uploadUrl();
- $options['height'] = empty($options['height']) ? 200 : $options['height'];
- $s .= !empty($id) ? "<textarea id=\"{$id}\" name=\"{$id}\" type=\"text/plain\" style=\"height:{$options['height']}px;\">{$value}</textarea>" : '';
- $s .= "
- <script type=\"text/javascript\">
- var ueditoroption = {
- 'autoClearinitialContent' : false,
- 'toolbars' : [['fullscreen', 'source', 'preview', '|', 'bold', 'italic', 'underline', 'strikethrough', 'forecolor', 'backcolor', '|',
- 'justifyleft', 'justifycenter', 'justifyright', '|', 'insertorderedlist', 'insertunorderedlist', 'blockquote', 'emotion',
- 'link', 'removeformat', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight','indent', 'paragraph', 'fontsize', '|',
- 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol',
- 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|', 'anchor', 'map', 'print', 'drafts']],
- 'elementPathEnabled' : false,
- 'initialFrameHeight': {$options['height']},
- 'focus' : false,
- 'maximumWords' : 9999999999999
- };
- var opts = {
- type :'image',
- direct : false,
- multi : true,
- tabs : {
- 'upload' : 'active',
- 'browser' : '',
- 'crawler' : ''
- },
- path : '',
- dest_dir : '',
- global : false,
- thumb : false,
- width : 0
- };
- UE.registerUI('myinsertimage',function(editor,uiName){
- editor.registerCommand(uiName, {
- execCommand:function(){
- require(['fileUploader'], function(uploader){
- uploader.upload_url('".$url['upload_url']."');
- uploader.image_url('".$url['image_url']."');
- uploader.fetch_url('".$url['fetch_url']."');
- uploader.delet_url('".$url['delet_url']."');
- uploader.show(function(imgs){
- if (imgs.length == 0) {
- return;
- } else if (imgs.length == 1) {
- editor.execCommand('insertimage', {
- 'src' : imgs[0]['url'],
- '_src' : imgs[0]['attachment'],
- 'width' : '100%',
- 'alt' : imgs[0].filename
- });
- } else {
- var imglist = [];
- for (i in imgs) {
- imglist.push({
- 'src' : imgs[i]['url'],
- '_src' : imgs[i]['attachment'],
- 'width' : '100%',
- 'alt' : imgs[i].filename
- });
- }
- editor.execCommand('insertimage', imglist);
- }
- }, opts);
- });
- }
- });
- var btn = new UE.ui.Button({
- name: '插入图片',
- title: '插入图片',
- cssRules :'background-position: -726px -77px',
- onclick:function () {
- editor.execCommand(uiName);
- }
- });
- editor.addListener('selectionchange', function () {
- var state = editor.queryCommandState(uiName);
- if (state == -1) {
- btn.setDisabled(true);
- btn.setChecked(false);
- } else {
- btn.setDisabled(false);
- btn.setChecked(state);
- }
- });
- return btn;
- }, 19);
- UE.registerUI('myinsertvideo',function(editor,uiName){
- editor.registerCommand(uiName, {
- execCommand:function(){
- require(['".$fileUploader."'],
- function(uploader){
- uploader.upload_url('".$url['upload_url']."');
- uploader.image_url('".$url['image_url']."');
- uploader.fetch_url('".$url['fetch_url']."');
- uploader.delet_url('".$url['delet_url']."');
- uploader.video_url('".$url['video_url']."');
- uploader.show(function(video){
- if (!video) {
- return;
- } else {
- var videoType = video.isRemote ? 'iframe' : 'video';
- editor.execCommand('insertvideo', {
- 'url' : video.url,
- 'width' : '100%',
- 'height' : 200
- }, videoType);
- }
- }, {type:'video'});
- }
- );
- }
- });
- var btn = new UE.ui.Button({
- name: '插入视频',
- title: '插入视频',
- cssRules :'background-position: -320px -20px',
- onclick:function () {
- editor.execCommand(uiName);
- }
- });
- editor.addListener('selectionchange', function () {
- var state = editor.queryCommandState(uiName);
- if (state == -1) {
- btn.setDisabled(true);
- btn.setChecked(false);
- } else {
- btn.setDisabled(false);
- btn.setChecked(state);
- }
- });
- return btn;
- }, 20);
- " . (!empty($id) ? "
- $(function(){
- var ue = UE.getEditor('{$id}', ueditoroption);
- $('#{$id}').data('editor', ue);
- $('#{$id}').parents('form').submit(function() {
- if (ue.queryCommandState('source')) {
- ue.execCommand('source');
- }
- });
- });" : '') . "
- </script>";
- return $s;
- }
- }
- if (!function_exists("html_images")) {
- function html_images($detail = '')
- {
- $detail = htmlspecialchars_decode($detail);
- preg_match_all("/<img.*?src=[\'| \"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]?))[\'|\"].*?[\/]?>/", $detail, $imgs);
- $images = array();
- if (isset($imgs[1])) {
- foreach ($imgs[1] as $img) {
- $im = array(
- "old" => $img,
- "new" => save_media($img)
- );
- $images[] = $im;
- }
- }
- foreach ($images as $img) {
- $detail = str_replace($img['old'], $img['new'], $detail);
- }
- return $detail;
- }
- }
- if (!function_exists("xml_to_array")) {
- function xml_to_array($xml)
- {
- $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
- if (preg_match_all($reg, $xml, $matches)) {
- $count = count($matches[0]);
- for ($i = 0; $i < $count; $i++) {
- $subxml = $matches[2][$i];
- $key = $matches[1][$i];
- if (preg_match($reg, $subxml)) {
- $arr[$key] = xml_to_array($subxml);
- } else {
- $arr[$key] = $subxml;
- }
- }
- }
- return $arr;
- }
- }
- if (!function_exists("tomedia")) {
- /**
- * 获取附件的HTTP绝对路径
- * @param string $src 附件地址
- * @param bool $local_path 是否直接返回本地图片路径
- * @return string
- */
- function tomedia($src, $local_path = false)
- {
- if (empty($src)) {
- return '';
- }
- $local = strtolower($src);
- if (config('app.framework') == 'platform') {
- if (strexists($src, 'storage/')) {
- return request()->getSchemeAndHttpHost() . '/' . substr($src, strpos($src, 'storage/'));
- }
- //判断是否是本地带域名图片地址
- if (strexists($src, '/static/')) {
- if (strexists($local, 'http://') || strexists($local, 'https://') || substr($local, 0, 2) == '//') {
- return $src;
- } else {
- return request()->getSchemeAndHttpHost() . substr($src, strpos($src, '/static/'));
- }
- }
- } elseif (config('app.framework') != 'platform' && strexists($src, 'addons/')) {
- return request()->getSchemeAndHttpHost() . '/' . substr($src, strpos($src, 'addons/'));
- }
- //如果远程地址中包含本地host也检测是否远程图片
- if (strexists($src, request()->getSchemeAndHttpHost()) && !strexists($src, '/addons/')) {
- $urls = parse_url($src);
- $src = $t = substr($urls['path'], strpos($urls['path'], 'image'));
- }
- $t = strtolower($src);
- if (strexists($t, 'http://') || strexists($t, 'https://') || substr($t, 0, 2) == '//') {
- return $src;
- }
- if (config('app.framework') == 'platform') {
- $remote = SystemSetting::settingLoad('remote', 'system_remote');
- // $upload_type = \app\platform\modules\application\models\CoreAttach::where('attachment', $src)->first()['upload_type'];
- if (($local_path || !$remote['type']) && file_exists(base_path() . '/static/upload/' . $src)) {
- $src = request()->getSchemeAndHttpHost() . '/static/upload' . (strpos($src,'/') === 0 ? '':'/') . $src;
- } else {
- if ($remote['type'] == '2') {
- $src = $remote['alioss']['url'] . '/'. $src;
- } elseif ($remote['type'] == '4') {
- $src = $remote['cos']['url'] . '/'. $src;
- }
- }
- } else {
- if (($local_path || empty(YunShop::app()->setting['remote']['type'])) && file_exists(base_path('../../') . '/' . YunShop::app()->config['upload']['attachdir'] . '/' . $src)) {
- $src = request()->getSchemeAndHttpHost() . '/attachment/' . $src;
- } else {
- $src = YunShop::app()->attachurl_remote . $src;
- }
- }
- return $src;
- }
- }
- //内容审核,判断插件是否开启后,抛出事件去审核返回审核结果
- if (!function_exists("do_upload_verificaton")) {
- //file支持传入图片文件,文字,视频url,语音文件(多种类型:仅支持pcm、wav、amr、m4a),
- //type为固定值:img,text,video, audio_pcm(_wav,_amr,_m4a)
- function do_upload_verificaton($file,$type) {
- return event((new Yunshop\UploadVerification\service\UploadVerificationEvent($file,$type)));
- }
- }
- /**
- * 获取附件的HTTP绝对路径
- * @param string $src 附件地址
- * @param bool $local_path 是否直接返回本地图片路径
- * @param null $upload_type 上传图片时的类型,数据表 upload_type 字段(只需要在上传图片时,传参数,获取列表不需要传改参数)
- * @return string
- */
- function yz_tomedia($src, $local_path = false, $upload_type = null,$host = '')
- {
- if (empty($src)) {
- return '';
- }
- $HttpHost = request()->getSchemeAndHttpHost();
- if ($host) {
- $HttpHost = $host;
- }
- $setting = [];
- if (config('app.framework') == 'platform') {
- $systemSetting = app('SystemSetting');
- if ($remote = $systemSetting->get('remote')) {
- $setting[$remote['key']] = unserialize($remote['value']);
- }
- $upload_type = $setting['remote']['type'];
- $addons = '/storage/';
- $attachment = '/static/upload/';
- $file_name = 'photo-mr';
- $file_path = base_path($attachment) . $src;
- if (file_exists($file_path)) {//本地图片存在直接返回 示例图片path image/e3a555295b58e043dbf8ea3eb0434647.png
- return $HttpHost.$attachment . $src;
- }
- if (strexists($src, $attachment)) {//本地图片存在直接返回 示例图片path /static/upload/image/e3a555295b58e043dbf8ea3eb0434647.png
- $relative_path = substr($src, strpos($src, $attachment));
- $file_path = base_path($relative_path);
- if (file_exists($file_path)) {
- return $HttpHost.$relative_path;
- }
- }
- if (strexists($src, $file_name) && file_exists(base_path($src))) { //默认会员头像
- return $HttpHost.$src;
- }
- } else {
- //全局配置
- global $_W;
- //公众号独立配置信息 优先使用公众号独立配置
- $uni_setting = app('WqUniSetting')->get()->toArray();
- if (!empty($uni_setting['remote']) && iunserializer($uni_setting['remote'])['type'] != 0) {
- $setting['remote'] = iunserializer($uni_setting['remote']);
- $upload_type = $setting['remote']['type'];
- } else {
- $setting = $_W['setting'];
- $upload_type = $setting['remote']['type'];
- }
- $addons = '/addons/';
- $attachment = '/attachment/';
- $file_path = base_path('../../attachment/') . $src;
- if (file_exists($file_path)) {//本地图片存在直接返回 示例图片path image/e3a555295b58e043dbf8ea3eb0434647.png
- return $HttpHost.'/attachment/'.$src;
- }
- if (strexists($src, $attachment)) {//本地图片存在直接返回 示例图片path /attachment/image/e3a555295b58e043dbf8ea3eb0434647.png
- $relative_path = substr($src, strpos($src, $attachment));
- $file_path = base_path('../..'.$relative_path);
- if (file_exists($file_path)) {
- return $HttpHost.$relative_path;
- }
- }
- }
- $os = Client::osType();
- if (strexists($src, $addons)) {
- if ($os == Client::OS_TYPE_IOS) {
- $url_dz = $HttpHost . substr($src, strpos($src, $addons));
- return 'https:' . substr($url_dz, strpos($url_dz, '//'));
- }
- return $HttpHost . substr($src, strpos($src, $addons));
- }
- $local = strtolower($src);
- //todo 临时增加如果是插件图片
- if (strexists($src, "plugins/")) {
- $attachment = "/plugins/";
- if ($os == Client::OS_TYPE_IOS) {
- $url_dz = $HttpHost . substr($src, strpos($src, $attachment));
- return 'https:' . substr($url_dz, strpos($url_dz, '//'));
- }
- if (strexists($local, 'http://') || strexists($local, 'https://') || substr($local, 0, 2) == '//') {
- return $src;
- } else {
- return $HttpHost . substr($src, strpos($src, $attachment));
- }
- }
- //装修静态
- if (strexists($src, 'static/') && strexists($src, 'yunshop/')) {
- $path = substr($src, strpos($src, 'static/'));
- if (base_path($path)) {
- return $HttpHost.'/'.$path;
- }
- }
- $attach_url_remote = '';
- if ($upload_type) {
- switch ($upload_type) {
- case 1 :
- $attach_url_remote = $setting['remote']['ftp']['url'];
- break;
- case 2 :
- $attach_url_remote = $setting['remote']['alioss']['url'];
- break;
- case 3 :
- $attach_url_remote = $setting['remote']['qiniu']['url'];
- break;
- case 4 :
- $attach_url_remote = $setting['remote']['cos']['url'];
- break;
- case 5 :
- $attach_url_remote = $setting['remote']['obs']['url'];
- break;
- }
- }
- if (strexists($src, request()->getHost()) && strexists($src, $attachment) && $upload_type) {
- $host_str = $HttpHost.$attachment;
- $str_len = strlen($host_str);
- $relative_path = substr($src, $str_len);
- return $attach_url_remote .'/'. $relative_path;
- }
- //判断是否是本地不带域名图片地址
- if ((strexists($src, $attachment) && (parse_url($src)['scheme'].'://'.parse_url($src)['host']) == $HttpHost) || (strexists($src, $attachment) && !strexists($src, 'http://') && !strexists($src, 'https://'))) {
- if ($os == Client::OS_TYPE_IOS) {
- $url_dz = $HttpHost . substr($src, strpos($src, $attachment));
- return 'https:' . substr($url_dz, strpos($url_dz, '//'));
- }
- return $HttpHost . substr($src, strpos($src, $attachment));
- }
- //如果远程地址中包含本地host也检测是否远程图片
- if (strexists($local, 'http://') || strexists($local, 'https://') || substr($local, 0, 2) == '//') {
- if (strexists($local, 'http://')) {
- return 'http:' . substr($src, strpos($src, '//'));
- }
- if (strexists($local, 'https://')) {
- return 'https:' . substr($src, strpos($src, '//'));
- }
- return 'https:' . substr($src, strpos($src, '//'));
- }
- if ($upload_type) {
- return $attach_url_remote.'/'.$src;
- }
- if (preg_match('/^(\/\/){1}.*/',$src)) {
- return $src;
- }
- if (!config('app.debug')) {
- $src = 'https:' . substr($src, strpos($src, '//'));
- }
- return $src;
- }
- if (!function_exists("replace_yunshop")) {
- function replace_yunshop($url)
- {
- $moduleName = \Config::get('app.module_name');
- return str_replace(DIRECTORY_SEPARATOR . "addons" . DIRECTORY_SEPARATOR . $moduleName, "", $url);
- }
- }
- if (!function_exists("strexists")) {
- /**
- * 判断字符串是否包含子串
- * @param string $string 在该字符串中进行查找
- * @param string $find 需要查找的字符串
- * @return boolean
- */
- function strexists($string, $find)
- {
- return !(strpos($string, $find) === false);
- }
- }
- if (!function_exists("set_medias")) {
- function set_medias($list = array(), $fields = null)
- {
- if (empty($fields)) {
- foreach ($list as &$row) {
- $row = yz_tomedia($row);
- }
- return $list;
- }
- if (!is_array($fields)) {
- $fields = explode(',', $fields);
- }
- if (is_array2($list)) {
- foreach ($list as $key => &$value) {
- foreach ($fields as $field) {
- if (isset($list[$field])) {
- $list[$field] = yz_tomedia($list[$field]);
- }
- if (is_array($value) && isset($value[$field])) {
- $value[$field] = yz_tomedia($value[$field]);
- }
- }
- }
- return $list;
- } else {
- foreach ($fields as $field) {
- if (isset($list[$field])) {
- $list[$field] = yz_tomedia($list[$field]);
- }
- }
- return $list;
- }
- }
- }
- if (!function_exists('is_array2')) {
- function is_array2($array)
- {
- if (is_array($array)) {
- foreach ($array as $k => $v) {
- return is_array($v);
- }
- return false;
- }
- return false;
- }
- }
- if (!function_exists("show_json")) {
- function show_json($status = 1, $return = null, $variable = null)
- {
- $ret = array(
- 'status' => $status
- );
- if ($return) {
- $ret['result'] = $return;
- }
- if (Yunshop::isApi()) {
- return array(
- 'status' => $status,
- 'variable' => $variable,
- 'json' => $return,
- );
- }
- die(json_encode($ret));
- }
- }
- if (!function_exists("array_column")) {
- function array_column($input = null, $columnKey = null, $indexKey = null)
- {
- // Using func_get_args() in order to check for proper number of
- // parameters and trigger errors exactly as the built-in array_column()
- // does in PHP 5.5.
- $argc = func_num_args();
- $params = func_get_args();
- if ($argc < 2) {
- trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);
- return null;
- }
- if (!is_array($params[0])) {
- trigger_error(
- 'array_column() expects parameter 1 to be array, ' . gettype($params[0]) . ' given',
- E_USER_WARNING
- );
- return null;
- }
- if (!is_int($params[1])
- && !is_float($params[1])
- && !is_string($params[1])
- && $params[1] !== null
- && !(is_object($params[1]) && method_exists($params[1], '__toString'))
- ) {
- trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING);
- return false;
- }
- if (isset($params[2])
- && !is_int($params[2])
- && !is_float($params[2])
- && !is_string($params[2])
- && !(is_object($params[2]) && method_exists($params[2], '__toString'))
- ) {
- trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING);
- return false;
- }
- $paramsInput = $params[0];
- $paramsColumnKey = ($params[1] !== null) ? (string)$params[1] : null;
- $paramsIndexKey = null;
- if (isset($params[2])) {
- if (is_float($params[2]) || is_int($params[2])) {
- $paramsIndexKey = (int)$params[2];
- } else {
- $paramsIndexKey = (string)$params[2];
- }
- }
- $resultArray = array();
- foreach ($paramsInput as $row) {
- $key = $value = null;
- $keySet = $valueSet = false;
- if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
- $keySet = true;
- $key = (string)$row[$paramsIndexKey];
- }
- if ($paramsColumnKey === null) {
- $valueSet = true;
- $value = $row;
- } elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
- $valueSet = true;
- $value = $row[$paramsColumnKey];
- }
- if ($valueSet) {
- if ($keySet) {
- $resultArray[$key] = $value;
- } else {
- $resultArray[] = $value;
- }
- }
- }
- return $resultArray;
- }
- }
- if (!function_exists('shop_template_compile')) {
- function shop_template_compile($from, $to, $inmodule = false)
- {
- $path = dirname($to);
- \app\common\services\Utils::mkdirs($path);
- $content = shop_template_parse(file_get_contents($from), $inmodule);
- file_put_contents($to, $content);
- }
- }
- if (!function_exists('shop_template_parse')) {
- function shop_template_parse($str, $inmodule = false)
- {
- $str = template_parse($str, $inmodule);
- $str = preg_replace('/{ifp\s+(.+?)}/', '<?php if(cv($1)) { ?>', $str);
- $str = preg_replace('/{ifpp\s+(.+?)}/', '<?php if(cp($1)) { ?>', $str);
- $str = preg_replace('/{ife\s+(\S+)\s+(\S+)}/', '<?php if( ce($1 ,$2) ) { ?>', $str);
- return $str;
- }
- }
- if (!function_exists('objectArray')) {
- function objectArray($array)
- {
- if (is_object($array)) {
- $array = (array)$array;
- }
- if (is_array($array)) {
- foreach ($array as $key => $value) {
- $array[$key] = objectArray($value);
- }
- }
- return $array;
- }
- }
- if (!function_exists('my_link_extra')) {
- function my_link_extra($type = 'content')
- {
- $content = "";
- $extraContents = [];
- Event::dispatch(new app\common\events\RenderingMyLink($extraContents));
- return $type == 'content' ? $content . implode("\n", $extraContents) : implode("\n",
- array_keys($extraContents));
- }
- }
- if (!function_exists('can')) {
- /**
- * 权限判断
- * @param $item 可以是item 或者是route
- * @param bool $isRoute
- * @return bool
- */
- function can($itemRoute, $isRoute = false)
- {
- /*if(config('app.menu_key') != 'menu'){
- return true;
- }*/
- if ($isRoute == true) {
- $item = \app\common\models\Menu::getItemByRoute($itemRoute);
- } else {
- $item = $itemRoute;
- }
- return PermissionService::can($item);
- }
- }
- if (!function_exists('weAccount')) {
- /**
- * 获取微擎账号体系
- * @return NULL|WeAccount
- */
- function weAccount()
- {
- /* load()->model('account');
- return WeAccount::create();*/
- }
- }
- if (!function_exists('yzWebUrl')) {
- function yzWebUrl($route, $params = [])
- {
- return Url::web($route, $params);
- }
- }
- if (!function_exists('yzAppUrl')) {
- function yzAppUrl($route, $params = [])
- {
- return Url::app($route, $params);
- }
- }
- if (!function_exists('yzApiUrl')) {
- function yzApiUrl($route, $params = [])
- {
- return Url::api($route, $params);
- }
- }
- if (!function_exists('yzPluginUrl')) {
- function yzPluginUrl($route, $params = [])
- {
- return Url::plugin($route, $params);
- }
- }
- if (!function_exists('yzPluginFullUrl')) {
- function yzPluginFullUrl($route, $params = [])
- {
- return Url::absolutePlugin($route, $params);
- }
- }
- if (!function_exists('yzWebFullUrl')) {
- function yzWebFullUrl($route, $params = [])
- {
- return Url::absoluteWeb($route, $params);
- }
- }
- if (!function_exists('yzAppFullUrl')) {
- function yzAppFullUrl($route, $params = [])
- {
- return Url::absoluteApp($route, $params);
- }
- }
- if (!function_exists('yzBusinessFullUrl')) {
- function yzBusinessFullUrl($route, $params = [])
- {
- return request()->getSchemeAndHttpHost() . '/' . yzBusinessUrl($route, $params);
- }
- }
- if (!function_exists('yzBusinessUrl')) {
- function yzBusinessUrl($route, $params = [])
- {
- if (!$params['i']) $params = array_merge(['i' => YunShop::app()->uniacid], $params);
- return 'business/business_font/#/' . $route . '?' . http_build_query($params);
- }
- }
- if (!function_exists('yzDiyFullUrl')) {
- function yzDiyFullUrl($route, $params = [])
- {
- return Url::absoluteDiyApp($route, $params);
- }
- }
- if (!function_exists('yzUrl')) {
- function yzUrl($route, $params = [])
- {
- return Url::web($route, $params);
- }
- }
- if (!function_exists('array_child_kv_exists')) {
- function array_child_kv_exists($array, $childKey, $value)
- {
- $result = false;
- if (is_array($array)) {
- foreach ($array as $v) {
- if (is_array($v) && isset($v[$childKey])) {
- $result += $v[$childKey] == $value;
- }
- }
- }
- return $result;
- }
- }
- if (!function_exists('widget')) {
- function widget($class, $params = [])
- {
- return (new $class($params))->run();
- }
- }
- if (!function_exists('assets')) {
- function assets($relativeUri)
- {
- // add query string to fresh cache
- if (Str::startsWith($relativeUri, 'styles') || Str::startsWith($relativeUri, 'scripts')) {
- return Url::shopUrl("resources/assets/dist/$relativeUri") . "?v=" . config('app.version');
- } elseif (Str::startsWith($relativeUri, 'lang')) {
- return Url::shopUrl("resources/$relativeUri");
- } else {
- return Url::shopUrl("resources/assets/$relativeUri");
- }
- }
- }
- if (!function_exists('static_url')) {
- function static_url($relativeUri)
- {
- return Url::shopUrl('static/' . $relativeUri);
- }
- }
- if (!function_exists('plugin')) {
- function plugin($id)
- {
- return app('plugins')->getPlugin($id);
- }
- }
- if (!function_exists('plugin_assets')) {
- function plugin_assets($id, $relativeUri)
- {
- if ($plugin = plugin($id)) {
- return $plugin->assets($relativeUri);
- } else {
- throw new InvalidArgumentException("No such plugin.");
- }
- }
- }
- if (!function_exists('json')) {
- function json()
- {
- $args = func_get_args();
- if (count($args) == 1 && is_array($args[0])) {
- return Response::json($args[0]);
- } elseif (count($args) == 3 && is_array($args[2])) {
- // the third argument is array of extra fields
- return Response::json(array_merge([
- 'errno' => $args[1],
- 'msg' => $args[0]
- ], $args[2]));
- } else {
- return Response::json([
- 'errno' => Arr::get($args, 1, 1),
- 'msg' => $args[0]
- ]);
- }
- }
- }
- if (!function_exists('yz_footer')) {
- function yz_footer($page_identification = "")
- {
- $content = "";
- /*
- $scripts = [
- assets('scripts/app.min.js'),
- assets('lang/'.config('app.locale').'/locale.js'),
- ];
- if ($page_identification !== "") {
- $scripts[] = assets("scripts/$page_identification.js");
- }
- foreach ($scripts as $script) {
- $content .= "<script type=\"text/javascript\" src=\"$script\"></script>\n";
- }
- */
- $customJs = option("custom_js");
- $customJs && $content .= '<script>' . $customJs . '</script>';
- $extraContents = [];
- Event::dispatch(new app\common\events\RenderingFooter($extraContents));
- return $content . implode("\n", $extraContents);
- }
- }
- if (!function_exists('yz_header')) {
- function yz_header($pageIdentification = "")
- {
- $content = "";
- /*
- $styles = [
- assets('styles/app.min.css'),
- assets('styles/skins/'.Option::get('color_scheme').'.min.css')
- ];
- if ($pageIdentification !== "") {
- $styles[] = assets("styles/$pageIdentification.css");
- }
- foreach ($styles as $style) {
- $content .= "<link rel=\"stylesheet\" href=\"$style\">\n";
- }
- */
- $customCss = option("custom_css");
- $customCss && $content .= '<style>' . option("custom_css") . '</style>';
- $extraContents = [];
- Event::dispatch(new app\common\events\RenderingHeader($extraContents));
- return $content . implode("\n", $extraContents);
- }
- }
- if (!function_exists('yz_menu')) {
- function yz_menu($type)
- {
- $menu = \app\backend\modules\menu\Menu::current()->getItems();
- Event::dispatch($type == "member" ? new app\common\events\ConfigureMemberMenu($menu)
- : new app\common\events\ConfigureAdminMenu($menu));
- if (!isset($menu[$type])) {
- throw new InvalidArgumentException;
- }
- return yz_menu_render($menu[$type]);
- }
- function yz_menu_render($data)
- {
- $content = "";
- foreach ($data as $key => $value) {
- $active = app('request')->is(@$value['link']);
- // also set parent as active if any child is active
- foreach ((array)@$value['children'] as $childKey => $childValue) {
- if (app('request')->is(@$childValue['link'])) {
- $active = true;
- }
- }
- $content .= $active ? '<li class="active">' : '<li>';
- if (isset($value['children'])) {
- $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>';
- // recurse
- $content .= '<ul class="treeview-menu" style="display: none;">' . yz_menu_render($value['children']) . '</ul>';
- } else {
- $content .= '<a href="' . url($value['link']) . '"><i class="fa ' . $value['icon'] . '"></i> <span>' . trans($value['title']) . '</span></a>';
- }
- $content .= '</li>';
- }
- return $content;
- }
- }
- if (!function_exists('option')) {
- /**
- * Get / set the specified option value.
- *
- * If an array is passed as the key, we will assume you want to set an array of values.
- *
- * @param array|string $key
- * @param mixed $default
- * @param raw $raw return raw value without convertion
- * @return mixed
- */
- function option($key = null, $default = null, $raw = false)
- {
- $options = app('options');
- if (is_null($key)) {
- return $options;
- }
- if (is_array($key)) {
- foreach ($key as $innerKey => $innerValue) {
- $options->set($innerKey, $innerValue);
- }
- return;
- }
- //$optionsData = $options->get();
- //return $optionsData[$key]['option_value'];
- return array_get($options->all(),$key, $default)['option_value'];
- }
- }
- if (!function_exists('float_greater')) {
- function float_greater($number, $other_number)
- {
- return bccomp($number, $other_number) === 1;
- }
- }
- if (!function_exists('float_lesser')) {
- function float_lesser($number, $other_number)
- {
- return bccomp($number, $other_number) === -1;
- }
- }
- if (!function_exists('float_equal')) {
- function float_equal($number, $other_number)
- {
- return bccomp($number, $other_number) === 0;
- }
- }
- if (!function_exists('sdd')) {
- function sdd()
- {
- global $testDd;
- $testDd = !$testDd;
- }
- }
- if (!function_exists('tdd')) {
- function tdd()
- {
- global $testDd;
- if ($testDd) {
- dd(func_get_args());
- }
- }
- }
- /*
- * 生成一个随机订单号:如果需要唯一性,请自己验证重复调用
- *
- * @params string $prefix 标示 SN RV
- * @params bool $numeric 是否为纯数字
- *
- * @return mixed
- * @Author yitian */
- if (!function_exists('createNo')) {
- function createNo($prefix, $length = 6, $numeric = FALSE)
- {
- return $prefix . date('YmdHis') . Client::random($length, $numeric);
- }
- }
- if (!function_exists('yz_array_set')) {
- function yz_array_set($array, $key, $value)
- {
- $keys = explode('.', $key);
- while (count($keys) > 1) {
- $key = array_shift($keys);
- // If the key doesn't exist at this depth, we will just create an empty array
- // to hold the next value, allowing us to create the arrays to hold final
- // values at the correct depth. Then we'll keep digging into the array.
- if (!isset($array[$key]) || !is_array($array[$key])) {
- $array[$key] = [];
- }
- $array = &$array[$key];
- }
- $array[array_shift($keys)] = $value;
- return $array;
- }
- }
- if (!function_exists('trace_log')) {
- /**
- * @return \Illuminate\Foundation\Application|mixed
- */
- function trace_log(){
- return app('Log.trace');
- }
- }
- if (!function_exists('debug_log')) {
- /**
- * @return \Illuminate\Foundation\Application|mixed
- */
- function debug_log(){
- return app('Log.debug');
- }
- }
- if (!function_exists('randNum')) {
- /**
- * 获取随机字符串
- * @param number $length 字符串长度
- * @param boolean $numeric 是否为纯数字
- * @return string
- */
- function randNum($length, $numeric = FALSE) {
- $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
- $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
- if ($numeric) {
- $hash = '';
- } else {
- $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
- $length--;
- }
- $max = strlen($seed) - 1;
- for ($i = 0; $i < $length; $i++) {
- $hash .= $seed[mt_rand(0, $max)];
- }
- return $hash;
- }
- }
- if (!function_exists('file_random_name')) {
- function file_random_name($dir, $ext)
- {
- do {
- $filename = random(30) . '.' . $ext;
- } while (file_exists($dir . $filename));
- return $filename;
- }
- }
- if (!function_exists('random')) {
- function random($length, $numeric = FALSE)
- {
- $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
- $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
- if ($numeric) {
- $hash = '';
- } else {
- $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
- $length--;
- }
- $max = strlen($seed) - 1;
- for ($i = 0; $i < $length; $i++) {
- $hash .= $seed[mt_rand(0, $max)];
- }
- return $hash;
- }
- }
- if (!function_exists('is_error')) {
- function is_error($data)
- {
- if (empty($data) || !is_array($data) || !array_key_exists('errno', $data) || (array_key_exists('errno', $data) && $data['errno'] == 0)) {
- return false;
- } else {
- return true;
- }
- }
- }
- if (!function_exists('file_image_quality')) {
- function file_image_quality($src, $to_path, $ext, $global)
- {
- $quality = intval($global['zip_percentage']);
- if ($quality <= 0 || $quality >= 100) {
- return;
- }
- if (filesize($src) / 1024 > 5120) {
- return;
- }
- $result = \app\platform\modules\system\models\Image::create($src, $ext)->saveTo($to_path, $quality);
- return $result;
- }
- }
- if (!function_exists('safe_gpc_path')) {
- function safe_gpc_path($value, $default = '') {
- $path = safe_gpc_string($value);
- $path = str_replace(array('..', '..\\', '\\\\' ,'\\', '..\\\\'), '', $path);
- if (!$path || $path != $value) {
- $path = $default;
- }
- return $path;
- }
- }
- if (!function_exists('safe_gpc_string')) {
- function safe_gpc_string($value, $default = '')
- {
- $value = safe_bad_str_replace($value);
- $value = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $value);
- if (empty($value) && $default != $value) {
- $value = $default;
- }
- return $value;
- }
- }
- if (!function_exists('array_elements')) {
- function array_elements($keys, $src, $default = FALSE)
- {
- $return = array();
- if (!is_array($keys)) {
- $keys = array($keys);
- }
- foreach ($keys as $key) {
- if (isset($src[$key])) {
- $return[$key] = $src[$key];
- } else {
- $return[$key] = $default;
- }
- }
- return $return;
- }
- }
- if (!function_exists('sizecount')) {
- function sizecount($size)
- {
- if ($size >= 1073741824) {
- $size = round($size / 1073741824 * 100) / 100 . ' GB';
- } elseif ($size >= 1048576) {
- $size = round($size / 1048576 * 100) / 100 . ' MB';
- } elseif ($size >= 1024) {
- $size = round($size / 1024 * 100) / 100 . ' KB';
- } else {
- $size = $size . ' Bytes';
- }
- return $size;
- }
- }
- if (!function_exists('file_image_thumb')) {
- function file_image_thumb($srcfile, $desfile = '', $width = 0, $global)
- {
- if (intval($width) == 0) {
- $width = intval($global['thumb_width']);
- }
- if (!$desfile) {
- $ext = pathinfo($srcfile, PATHINFO_EXTENSION);
- $srcdir = dirname($srcfile);
- do {
- $desfile = $srcdir . '/' . random(30) . ".{$ext}";
- } while (file_exists($desfile));
- }
- $des = dirname($desfile);
- if (!file_exists($des)) {
- if (!\app\common\services\Utils::mkdirs($des)) {
- return 1;
- }
- } elseif (!is_writable($des)) {
- return 2;
- }
- $org_info = @getimagesize($srcfile);
- if ($org_info) {
- if ($width == 0 || $width > $org_info[0]) {
- copy($srcfile, $desfile);
- return str_replace(base_path() . '/static/upload/', '', $desfile);
- }
- }
- $scale_org = $org_info[0] / $org_info[1];
- $height = $width / $scale_org;
- $desfile = \app\platform\modules\system\models\Image::create($srcfile)->resize($width, $height)->saveTo($desfile);
- if (!$desfile) {
- return false;
- }
- return str_replace(base_path() . '/static/upload/', '', $desfile);
- }
- }
- if (!function_exists('file_is_image')) {
- function file_is_image($url)
- {
- if (!parse_path($url)) {
- return false;
- }
- $pathinfo = pathinfo($url);
- $extension = strtolower($pathinfo['extension']);
- return !empty($extension) && in_array($extension, array('jpg', 'jpeg', 'gif', 'png'));
- }
- }
- if (!function_exists('file_remote_upload_wq')) {
- function file_remote_upload_wq($filename, $auto_delete_local = true, $remote = [], $frontend = false)
- {
- // $filename 文件名
- // $auto_delete_local 是否自动删除本地资源 true 删除 false 不删除
- // $remote 远程配置信息
- if (!empty($remote)) {
- $remote_setting = $remote;
- $upload_type = $remote['type'];
- } else {
- global $_W;
- $remote_setting = $_W['setting']['remote'];
- $upload_type = $_W['setting']['remote']['type'];
- }
- if (empty($upload_type)) {
- return false;
- }
- if ($upload_type == '1') {
- $ftp_config = array(
- 'hostname' => $remote_setting['ftp']['host'],
- 'username' => $remote_setting['ftp']['username'],
- 'password' => $remote_setting['ftp']['password'],
- 'port' => $remote_setting['ftp']['port'],
- 'ssl' => $remote_setting['ftp']['ssl'],
- 'passive' => $remote_setting['ftp']['pasv'],
- 'timeout' => $remote_setting['ftp']['timeout'],
- 'rootdir' => $remote_setting['ftp']['dir'],
- );
- load()->library('ftp');
- $ftp = new Ftp($ftp_config);
- if (true === $ftp->connect()) {
- $response = $ftp->upload(ATTACHMENT_ROOT . $filename, $filename);
- if ($auto_delete_local) {
- file_deletes($filename);
- }
- if (!empty($response)) {
- return true;
- } else {
- return error(1, '远程附件上传失败,请检查配置并重新上传');
- }
- } else {
- return error(1, '远程附件上传失败,请检查配置并重新上传');
- }
- } elseif ($upload_type == '2') {
- $buckets = attachment_alioss_buctkets($remote_setting['alioss']['key'], $remote_setting['alioss']['secret']);
- $endpoint = 'http://' . $buckets[$remote_setting['alioss']['bucket']]['location'] . '.aliyuncs.com';
- try {
- $ossClient = new \app\common\services\aliyunoss\OssClient($remote_setting['alioss']['key'], $remote_setting['alioss']['secret'], $endpoint);
- $ossClient->uploadFile($remote_setting['alioss']['bucket'], $filename, ATTACHMENT_ROOT . $filename);
- } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
- return error(1, $e->getMessage());
- }
- if ($auto_delete_local) {
- file_deletes($filename);
- }
- } elseif ($upload_type == '3') {
- load()->library('qiniu');
- $auth = new Qiniu\Auth($remote_setting['qiniu']['accesskey'], $remote_setting['qiniu']['secretkey']);
- $config = new Qiniu\Config();
- $uploadmgr = new Qiniu\Storage\UploadManager($config);
- $putpolicy = null;
- $uploadtoken = $auth->uploadToken($remote_setting['qiniu']['bucket'], null, 3600, $putpolicy);
- list($ret, $err) = $uploadmgr->putFile($uploadtoken, $filename, ATTACHMENT_ROOT . $filename);
- if ($auto_delete_local) {
- file_deletes($filename);
- }
- if ($err !== null) {
- return error(1, '远程附件上传失败,请检查配置并重新上传');
- } else {
- return true;
- }
- } elseif ($upload_type == '4') {
- //cosv5
- $result = (new \app\common\services\QcloudCosService(
- $remote_setting['cos']['local'],
- $remote_setting['cos']['secretid'],
- $remote_setting['cos']['secretkey'],
- $remote_setting['cos']['bucket'],
- $remote_setting['cos']['appid']
- ))->upload($filename);
- if ($auto_delete_local) {
- file_deletes($filename);
- }
- if ($result === true) {
- return true;
- } else {
- return error(-1, $result);
- }
- }
- return true;
- }
- }
- if (!function_exists('file_video_remote_upload_wq')) {
- function file_video_remote_upload_wq($filename, $auto_delete_local = true, $remote = '', $frontend = false)
- {
- // $filename 文件名
- // $auto_delete_local 是否自动删除本地资源 true 删除 false 不删除
- // $remote 远程配置信息
- // $frontend 是否前端调用 true 前端 false 后台
- global $_W;
- if (!empty($remote) && $frontend == true) {
- $remote_setting = $remote;
- $upload_type = $remote['type'];
- } else {
- $remote_setting = $_W['setting']['remote'];
- $upload_type = $_W['setting']['remote']['type'];
- }
- if (empty($upload_type)) {
- return false;
- }
- if ($upload_type == '1') {
- $ftp_config = array(
- 'hostname' => $remote_setting['ftp']['host'],
- 'username' => $remote_setting['ftp']['username'],
- 'password' => $remote_setting['ftp']['password'],
- 'port' => $remote_setting['ftp']['port'],
- 'ssl' => $remote_setting['ftp']['ssl'],
- 'passive' => $remote_setting['ftp']['pasv'],
- 'timeout' => $remote_setting['ftp']['timeout'],
- 'rootdir' => $remote_setting['ftp']['dir'],
- );
- load()->library('ftp');
- $ftp = new Ftp($ftp_config);
- if (true === $ftp->connect()) {
- $response = $ftp->upload(ATTACHMENT_ROOT . $filename, $filename);
- if ($auto_delete_local) {
- file_deletes($filename);
- }
- if (!empty($response)) {
- return true;
- } else {
- return error(1, '远程附件上传失败,请检查配置并重新上传');
- }
- } else {
- return error(1, '远程附件上传失败,请检查配置并重新上传');
- }
- } elseif ($upload_type == '2') {
- $buckets = attachment_alioss_buctkets($remote_setting['alioss']['key'], $remote_setting['alioss']['secret']);
- $endpoint = 'http://' . $buckets[$remote_setting['alioss']['bucket']]['location'] . '.aliyuncs.com';
- try {
- $ossClient = new \app\common\services\aliyunoss\OssClient($remote_setting['alioss']['key'], $remote_setting['alioss']['secret'], $endpoint);
- $ossClient->uploadFile($remote_setting['alioss']['bucket'], $filename, ATTACHMENT_ROOT . $filename);
- } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
- return error(1, $e->getMessage());
- }
- if ($auto_delete_local) {
- file_deletes($filename);
- }
- } elseif ($upload_type == '3') {
- load()->library('qiniu');
- $auth = new Qiniu\Auth($remote_setting['qiniu']['accesskey'], $remote_setting['qiniu']['secretkey']);
- $config = new Qiniu\Config();
- $uploadmgr = new Qiniu\Storage\UploadManager($config);
- $putpolicy = null;
- $uploadtoken = $auth->uploadToken($remote_setting['qiniu']['bucket'], null, 3600, $putpolicy);
- list($ret, $err) = $uploadmgr->putFile($uploadtoken, $filename, ATTACHMENT_ROOT . $filename);
- if ($auto_delete_local) {
- file_deletes($filename);
- }
- if ($err !== null) {
- return error(1, '远程附件上传失败,请检查配置并重新上传');
- } else {
- return true;
- }
- } elseif ($upload_type == '4') {
- //cosv5
- $result = (new \app\common\services\QcloudCosService(
- $remote_setting['cos']['local'],
- $remote_setting['cos']['secretid'],
- $remote_setting['cos']['secretkey'],
- $remote_setting['cos']['bucket'],
- $remote_setting['cos']['appid']
- ))->upload($filename);
- if ($auto_delete_local) {
- file_deletes($filename);
- }
- if ($result === true) {
- return true;
- } else {
- return error(-1, $result);
- }
- }
- }
- }
- if (!function_exists('file_remote_upload')) {
- function file_remote_upload($filename, $auto_delete_local = true, $remote)
- {
- if (!$remote['type']) {
- return false;
- }
- if ($remote['type'] == '2') {
- $bucket = rtrim(substr($remote['alioss']['bucket'], 0, strrpos($remote['alioss']['bucket'],'@')), '@');
- $buckets = attachment_alioss_buctkets($remote['alioss']['key'], $remote['alioss']['secret']);
- $host_name = $remote['alioss']['internal'] ? '-internal.aliyuncs.com' : '.aliyuncs.com';
- $endpoint = 'http://' . $buckets[$bucket]['location'] . $host_name;
- try {
- $ossClient = new \app\common\services\aliyunoss\OssClient($remote['alioss']['key'], $remote['alioss']['secret'], $endpoint);
- $result = $ossClient->uploadFile($bucket, $filename, base_path('static/upload/') . $filename);
- } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
- return error(1, $e->getMessage());
- }
- if ($auto_delete_local) {
- file_delete($filename);
- }
- if (!$result) {
- return error(-1, $result);
- }
- return true;
- } elseif ($remote['type'] == '4') {
- $result = (new \app\common\services\QcloudCosService(
- $remote['cos']['local'],
- $remote['cos']['secretid'],
- $remote['cos']['secretkey'],
- $remote['cos']['bucket'],
- $remote['cos']['appid']
- ))->upload($filename);
- if ($auto_delete_local) {
- file_delete($filename);
- }
- if (!$result) {
- return error(-1, '上传远程失败');
- }
- return true;
- } elseif ($remote['type'] == '5') {
- $result = (new \app\common\services\ObsService(
- $remote['obs']['key'],
- $remote['obs']['secret'],
- $remote['obs']['endpoint'],
- $remote['obs']['bucket']
- ))->upload($filename);
- if ($auto_delete_local) {
- file_delete($filename);
- }
- if (!$result) {
- return error(-1, '上传远程失败');
- }
- return true;
- }
- return false;
- }
- }
- if (!function_exists('file_video_remote_upload')) {
- function file_video_remote_upload($filename, $auto_delete_local = true, $remote)
- {
- if (!$remote['type']) {
- return false;
- }
- if ($remote['type'] == '2') {
- $bucket = rtrim(substr($remote['alioss']['bucket'], 0, strrpos($remote['alioss']['bucket'],'@')), '@');
- $buckets = attachment_alioss_buctkets($remote['alioss']['key'], $remote['alioss']['secret']);
- $host_name = $remote['alioss']['internal'] ? '-internal.aliyuncs.com' : '.aliyuncs.com';
- $endpoint = 'http://' . $buckets[$bucket]['location'] . $host_name;
- try {
- $ossClient = new \app\common\services\aliyunoss\OssClient($remote['alioss']['key'], $remote['alioss']['secret'], $endpoint);
- $ossClient->uploadFile($bucket, $filename, base_path() . $filename);
- } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
- \Log::info('-----alioss上传失败信息-----', $e->getMessage());
- return error(1, $e->getMessage());
- }
- if ($auto_delete_local) {
- file_delete($filename);
- }
- } elseif ($remote['type'] == '4') {
- $result = (new \app\common\services\QcloudCosService(
- $remote['cos']['local'],
- $remote['cos']['secretid'],
- $remote['cos']['secretkey'],
- $remote['cos']['bucket'],
- $remote['cos']['appid']
- ))->upload($filename);
- if ($auto_delete_local) {
- file_delete($filename);
- }
- if (!$result) {
- return error(-1, '上传远程失败');
- }
- return true;
- } elseif ($remote['type'] == '5') {
- $result = (new \app\common\services\ObsService(
- $remote['obs']['key'],
- $remote['obs']['secret'],
- $remote['obs']['endpoint'],
- $remote['obs']['bucket']
- ))->upload($filename);
- if ($auto_delete_local) {
- file_delete($filename);
- }
- if (!$result) {
- return error(-1, '上传远程失败');
- }
- return true;
- }
- return false;
- }
- }
- if (!function_exists('file_remote_upload_new')) {
- function file_remote_upload_new($filename, $auto_delete_local = true, $remote)
- {
- if (!$remote['type']) {
- return false;
- }
- if ($remote['type'] == '2') {
- $bucket = rtrim(substr($remote['alioss']['bucket'], 0, strrpos($remote['alioss']['bucket'],'@')), '@');
- $buckets = attachment_alioss_buctkets($remote['alioss']['key'], $remote['alioss']['secret']);
- $host_name = $remote['alioss']['internal'] ? '-internal.aliyuncs.com' : '.aliyuncs.com';
- $endpoint = 'http://' . $buckets[$bucket]['location'] . $host_name;
- try {
- $ossClient = new \app\common\services\aliyunoss\OssClient($remote['alioss']['key'], $remote['alioss']['secret'], $endpoint);
- $ossClient->uploadFile($bucket, $filename, base_path() . '/static/upload/' . $filename);
- } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
- \Log::info('-----alioss上传失败信息-----', $e->getMessage());
- return error(1, $e->getMessage());
- }
- if ($auto_delete_local) {
- file_delete($filename);
- }
- } elseif ($remote['type'] == '4') {
- $result = (new \app\common\services\QcloudCosService(
- $remote['cos']['local'],
- $remote['cos']['secretid'],
- $remote['cos']['secretkey'],
- $remote['cos']['bucket'],
- $remote['cos']['appid']
- ))->upload($filename);
- if ($auto_delete_local) {
- file_delete($filename);
- }
- if (!$result) {
- return error(-1, '上传远程失败');
- }
- return true;
- } elseif ($remote['type'] == '5') {
- $result = (new \app\common\services\ObsService(
- $remote['obs']['key'],
- $remote['obs']['secret'],
- $remote['obs']['endpoint'],
- $remote['obs']['bucket']
- ))->upload($filename);
- if ($auto_delete_local) {
- file_delete($filename);
- }
- if (!$result) {
- return error(-1, '上传远程失败');
- }
- return true;
- }
- return false;
- }
- }
- if (!function_exists('attachment_alioss_buctkets')) {
- function attachment_alioss_buctkets($key, $secret)
- {
- $url = 'http://oss-cn-beijing.aliyuncs.com';
- try {
- $ossClient = new \app\common\services\aliyunoss\OssClient($key, $secret, $url);
- } catch(\app\common\services\aliyunoss\OSS\Core\OssException $e) {
- return error(1, $e->getMessage());
- }
- try {
- $bucketlistinfo = $ossClient->listBuckets();
- } catch(\app\common\services\aliyunoss\OSS\Core\OssException $e) {
- return error(1, $e->getMessage());
- }
- $bucketlistinfo = $bucketlistinfo->getBucketList();
- $bucketlist = array();
- foreach ($bucketlistinfo as &$bucket) {
- $bucketlist[$bucket->getName()] = array('name' => $bucket->getName(), 'location' => $bucket->getLocation());
- }
- return $bucketlist;
- }
- }
- if (!function_exists('file_deletes')) {
- function file_deletes($file)
- {
- if (empty($file)) {
- return false;
- }
- if (file_exists($file)) {
- @unlink($file);
- }
- if (strexists($file, 'image/')) {
- $file = str_replace('image/', '', $file);
- }
- if (file_exists(ATTACHMENT_ROOT . 'image/' . $file)) {
- @unlink(ATTACHMENT_ROOT . 'image/' . $file);
- }
- if (file_exists(ATTACHMENT_ROOT . $file)) {
- @unlink(ATTACHMENT_ROOT . $file);
- }
- return true;
- }
- }
- if (!function_exists('file_delete')) {
- function file_delete($file)
- {
- if (empty($file)) {
- return false;
- }
- if (file_exists($file)) {
- @unlink($file);
- }
- if (file_exists(base_path() . '/static/upload/' . $file)) {
- @unlink(base_path() . '/static/upload/' . $file);
- }
- return true;
- }
- }
- if (!function_exists('safe_gpc_html')) {
- function safe_gpc_html($value, $default = '')
- {
- if (empty($value) || !is_string($value)) {
- return $default;
- }
- $value = safe_bad_str_replace($value);
- $value = safe_remove_xss($value);
- if (!$value && $value != $default) {
- $value = $default;
- }
- return $value;
- }
- }
- if (!function_exists('safe_bad_str_replace')) {
- function safe_bad_str_replace($string)
- {
- if (!$string) {
- return '';
- }
- $badstr = array("\0", "%00", "%3C", "%3E", '<?', '<%', '<?php', '{php', '../');
- $newstr = array('_', '_', '<', '>', '_', '_', '_', '_', '.._');
- $string = str_replace($badstr, $newstr, $string);
- return $string;
- }
- }
- if (!function_exists('safe_remove_xss')) {
- function safe_remove_xss($val)
- {
- $val = preg_replace('/([\x0e-\x19])/', '', $val);
- $search = 'abcdefghijklmnopqrstuvwxyz';
- $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
- $search .= '1234567890!@#$%^&*()';
- $search .= '~`";:?+/={}[]-_|\'\\';
- for ($i = 0; $i < strlen($search); $i++) {
- $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val);
- $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val);
- }
- preg_match_all('/href=[\'|\"](.*?)[\'|\"]|src=[\'|\"](.*?)[\'|\"]/i', $val, $matches);
- $url_list = array_merge($matches[1], $matches[2]);
- $encode_url_list = array();
- if ($url_list) {
- foreach ($url_list as $key => $url) {
- $val = str_replace($url, 'we7_' . $key . '_we7placeholder', $val);
- $encode_url_list[] = $url;
- }
- }
- $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'frameset', 'ilayer', 'bgsound', 'base');
- $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');
- $ra = array_merge($ra1, $ra2);
- $found = true;
- while ($found == true) {
- $val_before = $val;
- for ($i = 0; $i < sizeof($ra); $i++) {
- $pattern = '/';
- for ($j = 0; $j < strlen($ra[$i]); $j++) {
- if ($j > 0) {
- $pattern .= '(';
- $pattern .= '(&#[xX]0{0,8}([9ab]);)';
- $pattern .= '|';
- $pattern .= '|(�{0,8}([9|10|13]);)';
- $pattern .= ')*';
- }
- $pattern .= $ra[$i][$j];
- }
- $pattern .= '/i';
- $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2);
- $val = preg_replace($pattern, $replacement, $val);
- if ($val_before == $val) {
- $found = false;
- }
- }
- }
- if ($encode_url_list && is_array($encode_url_list)) {
- foreach ($encode_url_list as $key => $url) {
- $val = str_replace('we7_' . $key . '_we7placeholder', $url, $val);
- }
- }
- return $val;
- }
- }
- if (!function_exists('file_move')) {
- function file_move($filename, $dest)
- {
- \app\common\services\Utils::mkdirs(dirname($dest));
- if (is_uploaded_file($filename)) {
- move_uploaded_file($filename, $dest);
- } else {
- rename($filename, $dest);
- }
- // @chmod($filename, $_W['config']['setting']['filemode']);
- return is_file($dest);
- }
- }
- if (!function_exists('pagination')) {
- function pagination($total, $pageIndex, $pageSize = 15, $url = '', $context = array('before' => 5, 'after' => 4, 'ajaxcallback' => '', 'callbackfuncname' => ''))
- {
- $pdata = array(
- 'tcount' => 0,
- 'tpage' => 0,
- 'cindex' => 0,
- 'findex' => 0,
- 'pindex' => 0,
- 'nindex' => 0,
- 'lindex' => 0,
- 'options' => ''
- );
- if (!$context['before']) {
- $context['before'] = 5;
- }
- if (!$context['after']) {
- $context['after'] = 4;
- }
- if ($context['ajaxcallback']) {
- $context['isajax'] = true;
- }
- if ($context['callbackfuncname']) {
- $callbackfunc = $context['callbackfuncname'];
- }
- $pdata['tcount'] = $total;
- $pdata['tpage'] = (!$pageSize || $pageSize < 0) ? 1 : intval(ceil($total / $pageSize));
- if ($pdata['tpage'] <= 1) {
- return '';
- }
- $cindex = $pageIndex;
- $cindex = min($cindex, $pdata['tpage']);
- $cindex = max($cindex, 1);
- $pdata['cindex'] = $cindex;
- $pdata['findex'] = 1;
- $pdata['pindex'] = $cindex > 1 ? $cindex - 1 : 1;
- $pdata['nindex'] = $cindex < $pdata['tpage'] ? $cindex + 1 : $pdata['tpage'];
- $pdata['lindex'] = $pdata['tpage'];
- if ($context['isajax']) {
- if (!$url) {
- $url = '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET);
- }
- $pdata['faa'] = 'href="javascript:;" page="' . $pdata['findex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['findex'] . '\', this);"' : '');
- $pdata['paa'] = 'href="javascript:;" page="' . $pdata['pindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['pindex'] . '\', this);"' : '');
- $pdata['naa'] = 'href="javascript:;" page="' . $pdata['nindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['nindex'] . '\', this);"' : '');
- $pdata['laa'] = 'href="javascript:;" page="' . $pdata['lindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['lindex'] . '\', this);"' : '');
- } else {
- if ($url) {
- $pdata['faa'] = 'href="?' . str_replace('*', $pdata['findex'], $url) . '"';
- $pdata['paa'] = 'href="?' . str_replace('*', $pdata['pindex'], $url) . '"';
- $pdata['naa'] = 'href="?' . str_replace('*', $pdata['nindex'], $url) . '"';
- $pdata['laa'] = 'href="?' . str_replace('*', $pdata['lindex'], $url) . '"';
- } else {
- $_GET['page'] = $pdata['findex'];
- $pdata['faa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
- $_GET['page'] = $pdata['pindex'];
- $pdata['paa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
- $_GET['page'] = $pdata['nindex'];
- $pdata['naa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
- $_GET['page'] = $pdata['lindex'];
- $pdata['laa'] = 'href="' . '/index.php/admin/system/upload/image' . '?' . http_build_query($_GET) . '"';
- }
- }
- $html = '<div><ul class="pagination pagination-centered">';
- $html .= "<li><a {$pdata['faa']} class=\"pager-nav\">首页</a></li>";
- empty($callbackfunc) && $html .= "<li><a {$pdata['paa']} class=\"pager-nav\">«上一页</a></li>";
- if (!$context['before'] && $context['before'] != 0) {
- $context['before'] = 5;
- }
- if (!$context['after'] && $context['after'] != 0) {
- $context['after'] = 4;
- }
- if ($context['after'] != 0 && $context['before'] != 0) {
- $range = array();
- $range['start'] = max(1, $pdata['cindex'] - $context['before']);
- $range['end'] = min($pdata['tpage'], $pdata['cindex'] + $context['after']);
- if ($range['end'] - $range['start'] < $context['before'] + $context['after']) {
- $range['end'] = min($pdata['tpage'], $range['start'] + $context['before'] + $context['after']);
- $range['start'] = max(1, $range['end'] - $context['before'] - $context['after']);
- }
- for ($i = $range['start']; $i <= $range['end']; $i++) {
- if ($context['isajax']) {
- $aa = 'href="javascript:;" page="' . $i . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $i . '\', this);"' : '');
- } else {
- if ($url) {
- $aa = 'href="?' . str_replace('*', $i, $url) . '"';
- } else {
- $_GET['page'] = $i;
- $aa = 'href="?' . http_build_query($_GET) . '"';
- }
- }
- if (!empty($context['isajax'])) {
- $html .= ($i == $pdata['cindex'] ? '<li class="active">' : '<li>') . "<a {$aa}>" . $i . '</a></li>';
- } else {
- $html .= ($i == $pdata['cindex'] ? '<li class="active"><a href="javascript:;">' . $i . '</a></li>' : "<li><a {$aa}>" . $i . '</a></li>');
- }
- }
- }
- if ($pdata['cindex'] < $pdata['tpage']) {
- empty($callbackfunc) && $html .= "<li><a {$pdata['naa']} class=\"pager-nav\">下一页»</a></li>";
- $html .= "<li><a {$pdata['laa']} class=\"pager-nav\">尾页</a></li>";
- }
- $html .= '</ul></div>';
- return $html;
- }
- }
- if (!function_exists('http_build_query')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $formdata
- * @param null $numeric_prefix
- * @param null $arg_separator
- * @return bool|string
- */
- function http_build_query($formdata, $numeric_prefix = null, $arg_separator = null)
- {
- if (!is_array($formdata))
- return false;
- if ($arg_separator == null)
- $arg_separator = '&';
- return http_build_recursive($formdata, $arg_separator);
- }
- }
- if (!function_exists('ihttp_get')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $url
- * @return array
- */
- function ihttp_get($url)
- {
- return ihttp_request($url);
- }
- }
- if (!function_exists('ihttp_request')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $url
- * @param string $post
- * @param array $extra
- * @param int $timeout
- * @return array
- */
- function ihttp_request($url, $post = '', $extra = array(), $timeout = 60)
- {
- if (function_exists('curl_init') && function_exists('curl_exec') && $timeout > 0) {
- $ch = ihttp_build_curl($url, $post, $extra, $timeout);
- if (is_error($ch)) {
- return $ch;
- }
- $data = curl_exec($ch);
- $status = curl_getinfo($ch);
- $errno = curl_errno($ch);
- $error = curl_error($ch);
- curl_close($ch);
- if ($errno || !$data) {
- return error($errno, $error);
- } else {
- return ihttp_response_parse($data);
- }
- }
- $urlset = ihttp_parse_url($url, true);
- if ($urlset['ip']) {
- $urlset['host'] = $urlset['ip'];
- }
- $body = ihttp_build_httpbody($url, $post, $extra);
- if ($urlset['scheme'] == 'https') {
- $fp = ihttp_socketopen('ssl://' . $urlset['host'], $urlset['port'], $errno, $error);
- } else {
- $fp = ihttp_socketopen($urlset['host'], $urlset['port'], $errno, $error);
- }
- stream_set_blocking($fp, $timeout > 0 ? true : false);
- stream_set_timeout($fp, ini_get('default_socket_timeout'));
- if (!$fp) {
- return error(1, $error);
- } else {
- fwrite($fp, $body);
- $content = '';
- if ($timeout > 0) {
- while (!feof($fp)) {
- $content .= fgets($fp, 512);
- }
- }
- fclose($fp);
- return ihttp_response_parse($content, true);
- }
- }
- }
- if (!function_exists('ihttp_build_curl')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $url
- * @param $post
- * @param $extra
- * @param $timeout
- * @return resource
- */
- function ihttp_build_curl($url, $post, $extra, $timeout)
- {
- if (!function_exists('curl_init') || !function_exists('curl_exec')) {
- return error(1, 'curl扩展未开启');
- }
- $urlset = ihttp_parse_url($url);
- if (is_error($urlset)) {
- return $urlset;
- }
- if ($urlset['ip']) {
- $extra['ip'] = $urlset['ip'];
- }
- $ch = curl_init();
- if ($extra['ip']) {
- $extra['Host'] = $urlset['host'];
- $urlset['host'] = $extra['ip'];
- unset($extra['ip']);
- }
- curl_setopt($ch, CURLOPT_URL, $urlset['scheme'] . '://' . $urlset['host'] . ($urlset['port'] == '80' || !$urlset['port'] ? '' : ':' . $urlset['port']) . $urlset['path'] . $urlset['query']);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
- curl_setopt($ch, CURLOPT_HEADER, 1);
- @curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
- if ($post) {
- if (is_array($post)) {
- $filepost = false;
- foreach ($post as $name => &$value) {
- if (version_compare(phpversion(), '5.5') >= 0 && is_string($value) && substr($value, 0, 1) == '@') {
- $post[$name] = new CURLFile(ltrim($value, '@'));
- }
- if ((is_string($value) && substr($value, 0, 1) == '@') || (class_exists('CURLFile') && $value instanceof CURLFile)) {
- $filepost = true;
- }
- }
- if (!$filepost) {
- $post = http_build_query($post);
- }
- }
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
- }
- if ($GLOBALS['_W']['config']['setting']['proxy']) {
- $urls = parse_url($GLOBALS['_W']['config']['setting']['proxy']['host']);
- if (!empty($urls['host'])) {
- curl_setopt($ch, CURLOPT_PROXY, "{$urls['host']}:{$urls['port']}");
- $proxytype = 'CURLPROXY_' . strtoupper($urls['scheme']);
- if ($urls['scheme'] && defined($proxytype)) {
- curl_setopt($ch, CURLOPT_PROXYTYPE, constant($proxytype));
- } else {
- curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
- curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
- }
- if ($GLOBALS['_W']['config']['setting']['proxy']['auth']) {
- curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['_W']['config']['setting']['proxy']['auth']);
- }
- }
- }
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
- curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- curl_setopt($ch, CURLOPT_SSLVERSION, 1);
- if (defined('CURL_SSLVERSION_TLSv1')) {
- curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
- }
- curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
- if ($extra && is_array($extra)) {
- $headers = array();
- foreach ($extra as $opt => $value) {
- if (strexists($opt, 'CURLOPT_')) {
- curl_setopt($ch, constant($opt), $value);
- } elseif (is_numeric($opt)) {
- curl_setopt($ch, $opt, $value);
- } else {
- $headers[] = "{$opt}: {$value}";
- }
- }
- if ($headers) {
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- }
- }
- return $ch;
- }
- }
- if (!function_exists('ihttp_parse_url')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $url
- * @param bool $set_default_port
- * @return array|mixed
- */
- function ihttp_parse_url($url, $set_default_port = false)
- {
- if (!$url) {
- return error(1);
- }
- $urlset = parse_url($url);
- if ($urlset['scheme'] && !in_array($urlset['scheme'], array('http', 'https'))) {
- return error(1, '只能使用 http 及 https 协议');
- }
- if (!$urlset['path']) {
- $urlset['path'] = '/';
- }
- if ($urlset['query']) {
- $urlset['query'] = "?{$urlset['query']}";
- }
- if (strexists($url, 'https://') && !extension_loaded('openssl')) {
- if (!extension_loaded("openssl")) {
- return error(1, '请开启您PHP环境的openssl', '');
- }
- }
- if (!$urlset['host']) {
- $current_url = parse_url($GLOBALS['_W']['siteroot']);
- $urlset['host'] = $current_url['host'];
- $urlset['scheme'] = $current_url['scheme'];
- $urlset['path'] = $current_url['path'] . 'web/' . str_replace('./', '', $urlset['path']);
- $urlset['ip'] = '127.0.0.1';
- } else if (!ihttp_allow_host($urlset['host'])) {
- return error(1, 'host 非法');
- }
- if ($set_default_port && !$urlset['port']) {
- $urlset['port'] = $urlset['scheme'] == 'https' ? '443' : '80';
- }
- return $urlset;
- }
- }
- if (!function_exists('error')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $errno
- * @param string $message
- * @return array
- */
- function error($errno, $message = '')
- {
- return array(
- 'errno' => $errno,
- 'message' => $message,
- );
- }
- }
- if (!function_exists('http_build_recursive')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $formdata
- * @param $separator
- * @param string $key
- * @param string $prefix
- * @return string
- */
- function http_build_recursive($formdata, $separator, $key = '', $prefix = '')
- {
- $rlt = '';
- foreach ($formdata as $k => $v) {
- if (is_array($v)) {
- if ($key)
- $rlt .= http_build_recursive($v, $separator, $key . '[' . $k . ']', $prefix);
- else
- $rlt .= http_build_recursive($v, $separator, $k, $prefix);
- } else {
- if ($key)
- $rlt .= $prefix . $key . '[' . urlencode($k) . ']=' . urldecode($v) . '&';
- else
- $rlt .= $prefix . urldecode($k) . '=' . urldecode($v) . '&';
- }
- }
- return $rlt;
- }
- }
- if (!function_exists('ihttp_response_parse')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $data
- * @param bool $chunked
- * @return array
- */
- function ihttp_response_parse($data, $chunked = false)
- {
- $rlt = array();
- $headermeta = explode('HTTP/', $data);
- if (count($headermeta) > 2) {
- $data = 'HTTP/' . array_pop($headermeta);
- }
- $pos = strpos($data, "\r\n\r\n");
- $split1[0] = substr($data, 0, $pos);
- $split1[1] = substr($data, $pos + 4, strlen($data));
- $split2 = explode("\r\n", $split1[0], 2);
- preg_match('/^(\S+) (\S+) (.*)$/', $split2[0], $matches);
- $rlt['code'] = $matches[2] ? : 200;
- $rlt['status'] = $matches[3] ? : 'OK';
- $rlt['responseline'] = $split2[0] ? : '';
- $header = explode("\r\n", $split2[1]);
- $isgzip = false;
- $ischunk = false;
- foreach ($header as $v) {
- $pos = strpos($v, ':');
- $key = substr($v, 0, $pos);
- $value = trim(substr($v, $pos + 1));
- if (is_array($rlt['headers'][$key])) {
- $rlt['headers'][$key][] = $value;
- } elseif ($rlt['headers'][$key]) {
- $temp = $rlt['headers'][$key];
- unset($rlt['headers'][$key]);
- $rlt['headers'][$key][] = $temp;
- $rlt['headers'][$key][] = $value;
- } else {
- $rlt['headers'][$key] = $value;
- }
- if (!$isgzip && strtolower($key) == 'content-encoding' && strtolower($value) == 'gzip') {
- $isgzip = true;
- }
- if (!$ischunk && strtolower($key) == 'transfer-encoding' && strtolower($value) == 'chunked') {
- $ischunk = true;
- }
- }
- if ($chunked && $ischunk) {
- $rlt['content'] = ihttp_response_parse_unchunk($split1[1]);
- } else {
- $rlt['content'] = $split1[1];
- }
- if ($isgzip && function_exists('gzdecode')) {
- $rlt['content'] = gzdecode($rlt['content']);
- }
- $rlt['meta'] = $data;
- if ($rlt['code'] == '100') {
- return ihttp_response_parse($rlt['content']);
- }
- return $rlt;
- }
- }
- if (!function_exists('ihttp_response_parse_unchunk')) {
- /**
- * 为了兼容微擎使用此方法
- * @param null $str
- * @return bool|string|null
- */
- function ihttp_response_parse_unchunk($str = null)
- {
- if (!is_string($str) or strlen($str) < 1) {
- return false;
- }
- $eol = "\r\n";
- $add = strlen($eol);
- $tmp = $str;
- $str = '';
- do {
- $tmp = ltrim($tmp);
- $pos = strpos($tmp, $eol);
- if ($pos === false) {
- return false;
- }
- $len = hexdec(substr($tmp, 0, $pos));
- if (!is_numeric($len) or $len < 0) {
- return false;
- }
- $str .= substr($tmp, ($pos + $add), $len);
- $tmp = substr($tmp, ($len + $pos + $add));
- $check = trim($tmp);
- } while ($check);
- unset($tmp);
- return $str;
- }
- }
- if (!function_exists('ihttp_build_httpbody')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $url
- * @param $post
- * @param $extra
- * @return array|mixed|string
- */
- function ihttp_build_httpbody($url, $post, $extra)
- {
- $urlset = ihttp_parse_url($url, true);
- if (is_error($urlset)) {
- return $urlset;
- }
- if ($urlset['ip']) {
- $extra['ip'] = $urlset['ip'];
- }
- $body = '';
- if ($post && is_array($post)) {
- $filepost = false;
- $boundary = random(40);
- foreach ($post as $name => &$value) {
- if ((is_string($value) && substr($value, 0, 1) == '@') && file_exists(ltrim($value, '@'))) {
- $filepost = true;
- $file = ltrim($value, '@');
- $body .= "--$boundary\r\n";
- $body .= 'Content-Disposition: form-data; name="' . $name . '"; filename="' . basename($file) . '"; Content-Type: application/octet-stream' . "\r\n\r\n";
- $body .= file_get_contents($file) . "\r\n";
- } else {
- $body .= "--$boundary\r\n";
- $body .= 'Content-Disposition: form-data; name="' . $name . '"' . "\r\n\r\n";
- $body .= $value . "\r\n";
- }
- }
- if (!$filepost) {
- $body = http_build_query($post, '', '&');
- } else {
- $body .= "--$boundary\r\n";
- }
- }
- $method = !$post ? 'GET' : 'POST';
- $fdata = "{$method} {$urlset['path']}{$urlset['query']} HTTP/1.1\r\n";
- $fdata .= "Accept: */*\r\n";
- $fdata .= "Accept-Language: zh-cn\r\n";
- if ($method == 'POST') {
- $fdata .= !$filepost ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data; boundary=$boundary\r\n";
- }
- $fdata .= "Host: {$urlset['host']}\r\n";
- $fdata .= "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1\r\n";
- if (function_exists('gzdecode')) {
- $fdata .= "Accept-Encoding: gzip, deflate\r\n";
- }
- $fdata .= "Connection: close\r\n";
- if ($extra && is_array($extra)) {
- foreach ($extra as $opt => $value) {
- if (!strexists($opt, 'CURLOPT_')) {
- $fdata .= "{$opt}: {$value}\r\n";
- }
- }
- }
- if ($body) {
- $fdata .= 'Content-Length: ' . strlen($body) . "\r\n\r\n{$body}";
- } else {
- $fdata .= "\r\n";
- }
- return $fdata;
- }
- }
- if (!function_exists('ihttp_socketopen')) {
- function ihttp_socketopen($hostname, $port = 80, &$errno, &$errstr, $timeout = 15)
- {
- $fp = '';
- if (function_exists('fsockopen')) {
- $fp = @fsockopen($hostname, $port, $errno, $errstr, $timeout);
- } elseif (function_exists('pfsockopen')) {
- $fp = @pfsockopen($hostname, $port, $errno, $errstr, $timeout);
- } elseif (function_exists('stream_socket_client')) {
- $fp = @stream_socket_client($hostname . ':' . $port, $errno, $errstr, $timeout);
- }
- return $fp;
- }
- }
- if (!function_exists('ihttp_allow_host')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $host
- * @return bool
- */
- function ihttp_allow_host($host)
- {
- if (strexists($host, '@')) {
- return false;
- }
- $pattern = "/^(10|172|192|127)/";
- $global = YunShop::app();
- if (preg_match($pattern, $host) && isset($global['setting']['ip_white_list'])) {
- $ip_white_list = $global['setting']['ip_white_list'];
- if ($ip_white_list && isset($ip_white_list[$host]) && !$ip_white_list[$host]['status']) {
- return false;
- }
- }
- return true;
- }
- }
- if (!function_exists('attachment_obs_auth')) {
- function attachment_obs_auth($key, $secret, $endpoint, $bucket)
- {
- $filename = '/static/logo.png';
- $result = (new \app\common\services\ObsService($key, $secret, $endpoint, $bucket))->upload($filename, true);
- if (!$result) {
- return error(-1, '测试上传失败');
- }
- return true;
- }
- }
- if (!function_exists('attachment_cos_auth')) {
- function attachment_cos_auth($bucket, $appid, $key, $secret, $bucket_local = '')
- {
- if (!is_numeric($appid)) {
- return error(-1, '传入appid值不合法, 请重新输入');
- }
- if (!preg_match('/^[a-zA-Z0-9]{36}$/', $key)) {
- return error(-1, '传入secretid值不合法,请重新传入');
- }
- if (!preg_match('/^[a-zA-Z0-9]{32}$/', $secret)) {
- return error(-1, '传入secretkey值不合法,请重新传入');
- }
- $filename = 'logo.png';
- $result = (new \app\common\services\QcloudCosService($bucket_local, $key, $secret, $bucket, $appid))->uploadTest($filename);
- if ($result === true) {
- return true;
- } else {
- return error(-1, $result);
- }
- }
- }
- if (!function_exists('file_tree')) {
- function file_tree($path, $include = array()) {
- $files = array();
- if ($include) {
- $ds = glob($path . '/{' . implode(',', $include) . '}', GLOB_BRACE);
- } else {
- $ds = glob($path . '/*');
- }
- if (is_array($ds)) {
- foreach ($ds as $entry) {
- if (is_file($entry)) {
- $files[] = $entry;
- }
- if (is_dir($entry)) {
- $rs = file_tree($entry);
- foreach ($rs as $f) {
- $files[] = $f;
- }
- }
- }
- }
- return $files;
- }
- }
- if (!function_exists('parse_path')) {
- function parse_path($path)
- {
- $danger_char = array('../', '{php', '<?php', '<%', '<?', '..\\', '\\\\', '\\', '..\\\\', '%00', '\0', '\r');
- foreach ($danger_char as $char) {
- if (strexists($path, $char)) {
- return false;
- }
- }
- return $path;
- }
- }
- if (!function_exists('bytecount')) {
- function bytecount($str)
- {
- if (strtolower($str[strlen($str) - 1]) == 'b') {
- $str = substr($str, 0, -1);
- }
- if (strtolower($str[strlen($str) - 1]) == 'k') {
- return floatval($str) * 1024;
- }
- if (strtolower($str[strlen($str) - 1]) == 'm') {
- return floatval($str) * 1048576;
- }
- if (strtolower($str[strlen($str) - 1]) == 'g') {
- return floatval($str) * 1073741824;
- }
- }
- }
- if (!function_exists('attachment_alioss_datacenters')) {
- function attachment_alioss_datacenters()
- {
- $bucket_datacenter = array(
- 'oss-cn-hangzhou' => '杭州数据中心',
- 'oss-cn-qingdao' => '青岛数据中心',
- 'oss-cn-beijing' => '北京数据中心',
- 'oss-cn-hongkong' => '香港数据中心',
- 'oss-cn-shenzhen' => '深圳数据中心',
- 'oss-cn-shanghai' => '上海数据中心',
- 'oss-us-west-1' => '美国硅谷数据中心',
- );
- return $bucket_datacenter;
- }
- }
- if (!function_exists('attachment_newalioss_auth')) {
- function attachment_newalioss_auth($key, $secret, $bucket, $internal = false)
- {
- $buckets = attachment_alioss_buctkets($key, $secret);
- $host = $internal ? '-internal.aliyuncs.com' : '.aliyuncs.com';
- $url = 'http://' . $buckets[$bucket]['location'] . $host;
- $filename = 'logo.png';
- try {
- $ossClient = new \app\common\services\aliyunoss\OssClient($key, $secret, $url);
- $ossClient->uploadFile($bucket, $filename, base_path() . '/static/' . $filename);
- } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
- return error(1, $e->getMessage());
- }
- return 1;
- }
- }
- if (!function_exists('getimagesizefromstring')) {
- function getimagesizefromstring($string_data) {
- $uri = 'data://application/octet-stream;base64,' . base64_encode($string_data);
- return getimagesize($uri);
- }
- }
- if (!function_exists('yz_buildCustomPostFields')) {
- /**
- * Build custom post fields for safe multipart POST request for php before 5.5.
- * @param $fields array of key -> value fields to post.
- * @return $boundary and encoded post fields.
- */
- function yz_buildCustomPostFields($fields)
- {
- // invalid characters for "name" and "filename"
- static $disallow = array("\0", "\"", "\r", "\n");
- // initialize body
- $body = array();
- // build normal parameters
- foreach ($fields as $key => $value) {
- $key = str_replace($disallow, "_", $key);
- $body[] = implode("\r\n", array(
- "Content-Disposition: form-data; name=\"{$key}\"",
- '',
- filter_var($value),
- ));
- }
- // generate safe boundary
- do {
- $boundary = "---------------------" . md5(mt_rand() . microtime());
- } while (preg_grep("/{$boundary}/", $body));
- // add boundary for each parameters
- foreach ($body as &$part) {
- $part = "--{$boundary}\r\n{$part}";
- }
- unset($part);
- // add final boundary
- $body[] = "--{$boundary}--";
- $body[] = '';
- return array($boundary, implode("\r\n", $body));
- }
- }
- if (!function_exists('resource_get')) {
- function resource_get($file, $depth=2)
- {
- if (config('app.framework') == 'platform') {
- return '/' . $file;
- }
- $path = $depth == 2 ? '../..' : '..';
- return $path . '/addons/yun_shop/' . $file;
- }
- }
- if (!function_exists('tpl_form_field_image')) {
- function tpl_form_field_image($name, $value = '', $default = '', $options = array())
- {
- if (empty($default)) {
- $default = static_url('resource/images/nopic.jpg');
- }
- $val = $default;
- if (!empty($value)) {
- $val = tomedia($value);
- }
- if (!empty($options['global'])) {
- $options['global'] = true;
- } else {
- $options['global'] = false;
- }
- if (empty($options['class_extra'])) {
- $options['class_extra'] = '';
- }
- if (isset($options['dest_dir']) && !empty($options['dest_dir'])) {
- if (!preg_match('/^\w+([\/]\w+)?$/i', $options['dest_dir'])) {
- exit('图片上传目录错误,只能指定最多两级目录,如: "yz_store","yz_store/d1"');
- }
- }
- $options['direct'] = true;
- $options['multiple'] = false;
- if (isset($options['thumb'])) {
- $options['thumb'] = !empty($options['thumb']);
- }
- $param = uploadParam();
- $options['fileSizeLimit'] = $param['fileSizeLimit'];
- $s = '';
- if (!defined('TPL_INIT_IMAGE')) {
- $s = '
- <script type="text/javascript">
- function showImageDialog(elm, opts, options) {
- require(["'.$param['util'].'"], function(util){
- var btn = $(elm);
- var ipt = btn.parent().prev();
- var val = ipt.val();
- var img = ipt.parent().next().children();
- options = '.str_replace('"', '\'', json_encode($options)).';
- util.image(val, function(url){
- if(url.url){
- if(img.length > 0){
- img.get(0).src = url.url;
- }
- ipt.val(url.attachment);
- ipt.attr("filename",url.filename);
- ipt.attr("url",url.url);
- }
- if(url.media_id){
- if(img.length > 0){
- img.get(0).src = "";
- }
- ipt.val(url.media_id);
- }
- }, options);
- });
- }
- function deleteImage(elm){
- $(elm).prev().attr("src", "static/resource/images/nopic.jpg");
- $(elm).parent().prev().find("input").val("");
- }
- </script>';
- define('TPL_INIT_IMAGE', true);
- }
- $s .= '
- <div class="input-group ' . $options['class_extra'] . '">
- <input type="text" name="' . $name . '" value="' . $value . '"' . ($options['extras']['text'] ? $options['extras']['text'] : '') . ' class="form-control" autocomplete="off">
- <span class="input-group-btn">
- <button class="btn btn-default" type="button" onclick="showImageDialog(this);">选择图片</button>
- </span>
- </div>
- <div class="input-group ' . $options['class_extra'] . '" style="margin-top:.5em;">
- <img src="' . $val . '" onerror="this.src=\'' . $default . '\'; this.title=\'图片未找到.\'" class="img-responsive img-thumbnail" ' . ($options['extras']['image'] ? $options['extras']['image'] : '') . ' width="150" />
- <em class="close" style="position:absolute; top: 0px; right: -14px;" title="删除这张图片" onclick="deleteImage(this)">×</em>
- </div>';
- return $s;
- }
- }
- if (!function_exists('tpl_form_field_color')) {
- function tpl_form_field_color($name, $value = '')
- {
- $s = '';
- if (!defined('TPL_INIT_COLOR')) {
- $s = '
- <script type="text/javascript">
- $(function(){
- $(".colorpicker").each(function(){
- var elm = this;
- util.colorpicker(elm, function(color){
- $(elm).parent().prev().prev().val(color.toHexString());
- $(elm).parent().prev().css("background-color", color.toHexString());
- });
- });
- $(".colorclean").click(function(){
- $(this).parent().prev().prev().val("");
- $(this).parent().prev().css("background-color", "#FFF");
- });
- });
- </script>';
- define('TPL_INIT_COLOR', true);
- }
- $s .= '
- <div class="row row-fix">
- <div class="col-xs-8 col-sm-8" style="padding-right:0;">
- <div class="input-group">
- <input class="form-control" type="text" name="'.$name.'" placeholder="请选择颜色" value="'.$value.'">
- <span class="input-group-addon" style="width:35px;border-left:none;background-color:'.$value.'"></span>
- <span class="input-group-btn">
- <button class="btn btn-default colorpicker" type="button">选择颜色 <i class="fa fa-caret-down"></i></button>
- <button class="btn btn-default colorclean" type="button"><span><i class="fa fa-remove"></i></span></button>
- </span>
- </div>
- </div>
- </div>
- ';
- return $s;
- }
- }
- if (!function_exists('safe_gpc_array')) {
- function safe_gpc_array($value, $default = array())
- {
- if (!$value || !is_array($value)) {
- return $default;
- }
- foreach ($value as &$row) {
- if (is_numeric($row)) {
- $row = safe_gpc_int($row);
- } elseif (is_array($row)) {
- $row = safe_gpc_array($row, $default);
- } else {
- $row = safe_gpc_string($row);
- }
- }
- return $value;
- }
- }
- if (!function_exists('safe_gpc_int')) {
- function safe_gpc_int($value, $default = 0)
- {
- if (strpos($value, '.') !== false) {
- $value = floatval($value);
- $default = floatval($default);
- } else {
- $value = intval($value);
- $default = intval($default);
- }
- if (!$value && $default != $value) {
- $value = $default;
- }
- return $value;
- }
- }
- if (!function_exists('file_remote_delete')) {
- function file_remote_delete($file, $upload_type, $remote)
- {
- if (!$file) {
- return true;
- }
- if ($upload_type == '2') {
- $bucket = rtrim(substr($remote['alioss']['bucket'], 0, strrpos($remote['alioss']['bucket'],'@')), '@');
- $buckets = attachment_alioss_buctkets($remote['alioss']['key'], $remote['alioss']['secret']);
- $endpoint = 'https://' . $buckets[$bucket]['location'] . '.aliyuncs.com';
- try {
- $ossClient = new \app\common\services\aliyunoss\OssClient($remote['alioss']['key'], $remote['alioss']['secret'], $endpoint);
- $ossClient->deleteObject($bucket, $file);
- } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
- return error(1, '删除oss远程文件失败');
- }
- } elseif ($upload_type == '4') {
- $result = (new \app\common\services\QcloudCosService(
- $remote['cos']['local'],
- $remote['cos']['secretid'],
- $remote['cos']['secretkey'],
- $remote['cos']['bucket'],
- $remote['cos']['appid']
- ))->delete($file);
- if (!$result) {
- return error(-1, '删除cos远程文件失败');
- }
- } elseif ($upload_type == '5') {
- try {
- $result = (new \app\common\services\ObsService())->delete($file);
- } catch (\app\common\services\aliyunoss\OSS\Core\OssException $e) {
- return error(1, '删除oss远程文件失败');
- }
- }
- return true;
- }
- }
- if (!function_exists('material_list')) {
- function material_list($type = '', $server = '', $page = array('page_index' => 1, 'page_size' => 24), $uniacid = 0, $offset)
- {
- $core_attach = array('local' => new \app\platform\modules\application\models\CoreAttach, 'perm' => new app\platform\modules\application\models\WechatAttachment);
- $conditions['uniacid'] = $uniacid;
- $core_attach = $core_attach[$server];
- switch ($type) {
- case 'voice' :
- $conditions['type'] = $server == 'local' ? 2 : 'voice';
- break;
- case 'video' :
- $conditions['type'] = $server == 'local' ? 3 : 'video';
- break;
- default :
- $conditions['type'] = $server == 'local' ? 1 : 'image';
- break;
- }
- if ($server == 'local') {
- $core_attach = $core_attach->where($conditions)->orderBy('created_at', 'desc');
- $total = $core_attach->count();
- $core_attach = $core_attach->offset($offset)->limit($page['page_size'])->get();
- } else {
- $conditions['model'] = 'perm';
- $core_attach = $core_attach->where($conditions)->orderBy('created_at', 'desc');
- $total = $core_attach->count();
- $core_attach = $core_attach->offset($offset)->limit($page['page_size'])->get();
- if ($type == 'video') {
- foreach ($core_attach as &$row) {
- $row['tag'] = $row['tag'] == '' ? array() : iunserializer($row['tag']);
- }
- unset($row);
- }
- }
- $pager = pagination($total, $page['page_index'], $page['page_size'], '', $context = array('before' => 5, 'after' => 4, 'isajax' => '1'));
- $material_news = array('material_list' => $core_attach, 'page' => $pager);
- return $material_news;
- }
- }
- if (!function_exists('iunserializer')) {
- function iunserializer($value)
- {
- if (!$value) {
- return array();
- }
- if (!is_serialized($value)) {
- return $value;
- }
- $result = unserialize($value);
- if ($result === false) {
- $temp = preg_replace_callback('!s:(\d+):"(.*?)";!s', function ($matchs) {
- return 's:' . strlen($matchs[2]) . ':"' . $matchs[2] . '";';
- }, $value);
- return unserialize($temp);
- } else {
- return $result;
- }
- }
- }
- if (!function_exists('is_serialized')) {
- function is_serialized($data, $strict = true)
- {
- if (!is_string($data)) {
- return false;
- }
- $data = trim($data);
- if ('N;' == $data) {
- return true;
- }
- if (strlen($data) < 4) {
- return false;
- }
- if (':' !== $data[1]) {
- return false;
- }
- if ($strict) {
- $lastc = substr($data, -1);
- if (';' !== $lastc && '}' !== $lastc) {
- return false;
- }
- } else {
- $semicolon = strpos($data, ';');
- $brace = strpos($data, '}');
- if (false === $semicolon && false === $brace)
- return false;
- if (false !== $semicolon && $semicolon < 3)
- return false;
- if (false !== $brace && $brace < 4)
- return false;
- }
- $token = $data[0];
- switch ($token) {
- case 's' :
- if ($strict) {
- if ('"' !== substr($data, -2, 1)) {
- return false;
- }
- } elseif (false === strpos($data, '"')) {
- return false;
- }
- case 'a' :
- return (bool)preg_match("/^{$token}:[0-9]+:/s", $data);
- case 'O' :
- return false;
- case 'b' :
- case 'i' :
- case 'd' :
- $end = $strict ? '$' : '';
- return (bool)preg_match("/^{$token}:[0-9.E-]+;$end/", $data);
- }
- return false;
- }
- }
- if (!function_exists('ver_compare')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $version1
- * @param $version2
- * @return mixed
- */
- function ver_compare($version1, $version2)
- {
- $version1 = str_replace('.', '', $version1);
- $version2 = str_replace('.', '', $version2);
- $oldLength = istrlen($version1);
- $newLength = istrlen($version2);
- if (is_numeric($version1) && is_numeric($version2)) {
- if ($oldLength > $newLength) {
- $version2 .= str_repeat('0', $oldLength - $newLength);
- }
- if ($newLength > $oldLength) {
- $version1 .= str_repeat('0', $newLength - $oldLength);
- }
- $version1 = intval($version1);
- $version2 = intval($version2);
- }
- return version_compare($version1, $version2);
- }
- }
- if (!function_exists('istrlen')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $string
- * @param string $charset
- * @return int
- */
- function istrlen($string, $charset = '')
- {
- if (!$charset) {
- $charset = \YunShop::app()['charset'];
- }
- if (strtolower($charset) == 'gbk') {
- $charset = 'gbk';
- } else {
- $charset = 'utf8';
- }
- if (function_exists('mb_strlen') && extension_loaded('mbstring')) {
- return mb_strlen($string, $charset);
- } else {
- $n = $noc = 0;
- $strlen = strlen($string);
- if ($charset == 'utf8') {
- while ($n < $strlen) {
- $t = ord($string[$n]);
- if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
- $n++;
- $noc++;
- } elseif (194 <= $t && $t <= 223) {
- $n += 2;
- $noc++;
- } elseif (224 <= $t && $t <= 239) {
- $n += 3;
- $noc++;
- } elseif (240 <= $t && $t <= 247) {
- $n += 4;
- $noc++;
- } elseif (248 <= $t && $t <= 251) {
- $n += 5;
- $noc++;
- } elseif ($t == 252 || $t == 253) {
- $n += 6;
- $noc++;
- } else {
- $n++;
- }
- }
- } else {
- while ($n < $strlen) {
- $t = ord($string[$n]);
- if ($t > 127) {
- $n += 2;
- $noc++;
- } else {
- $n++;
- $noc++;
- }
- }
- }
- return $noc;
- }
- }
- }
- if (!function_exists('mb_strlen')) {
- function mb_strlen($string, $charset = '') {
- return istrlen($string, $charset);
- }
- }
- if (!function_exists('tpl_form_field_daterange')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $name
- * @param array $value
- * @param bool $time
- * @return string
- */
- function tpl_form_field_daterange($name, $value = array(), $time = false) {
- $s = '';
- if (empty($time) && !defined('TPL_INIT_DATERANGE_DATE')) {
- $s = '
- <script type="text/javascript">
- require(["daterangepicker"], function(){
- $(function(){
- $(".daterange.daterange-date").each(function(){
- var elm = this;
- $(this).daterangepicker({
- startDate: $(elm).prev().prev().val(),
- endDate: $(elm).prev().val(),
- format: "YYYY-MM-DD"
- }, function(start, end){
- $(elm).find(".date-title").html(start.toDateStr() + " 至 " + end.toDateStr());
- $(elm).prev().prev().val(start.toDateStr());
- $(elm).prev().val(end.toDateStr());
- });
- });
- });
- });
- </script>
- ';
- define('TPL_INIT_DATERANGE_DATE', true);
- }
- if (!empty($time) && !defined('TPL_INIT_DATERANGE_TIME')) {
- $s = '
- <script type="text/javascript">
- require(["daterangepicker"], function(){
- $(function(){
- $(".daterange.daterange-time").each(function(){
- var elm = this;
- $(this).daterangepicker({
- startDate: $(elm).prev().prev().val(),
- endDate: $(elm).prev().val(),
- format: "YYYY-MM-DD HH:mm",
- timePicker: true,
- timePicker12Hour : false,
- timePickerIncrement: 1,
- minuteStep: 1
- }, function(start, end){
- $(elm).find(".date-title").html(start.toDateTimeStr() + " 至 " + end.toDateTimeStr());
- $(elm).prev().prev().val(start.toDateTimeStr());
- $(elm).prev().val(end.toDateTimeStr());
- });
- });
- });
- });
- </script>
- ';
- define('TPL_INIT_DATERANGE_TIME', true);
- }
- if ($value['starttime'] !== false && $value['start'] !== false) {
- if($value['start']) {
- $value['starttime'] = empty($time) ? date('Y-m-d',strtotime($value['start'])) : date('Y-m-d H:i',strtotime($value['start']));
- }
- $value['starttime'] = empty($value['starttime']) ? (empty($time) ? date('Y-m-d') : date('Y-m-d H:i') ): $value['starttime'];
- } else {
- $value['starttime'] = '请选择';
- }
- if ($value['endtime'] !== false && $value['end'] !== false) {
- if($value['end']) {
- $value['endtime'] = empty($time) ? date('Y-m-d',strtotime($value['end'])) : date('Y-m-d H:i',strtotime($value['end']));
- }
- $value['endtime'] = empty($value['endtime']) ? $value['starttime'] : $value['endtime'];
- } else {
- $value['endtime'] = '请选择';
- }
- $s .= '
- <input name="'.$name . '[start]'.'" type="hidden" value="'. $value['starttime'].'" />
- <input name="'.$name . '[end]'.'" type="hidden" value="'. $value['endtime'].'" />
- <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>
- ';
- return $s;
- }
- }
- if (!function_exists('tpl_ueditor')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $id
- * @param string $value
- * @param array $options
- * @return string
- */
- function tpl_ueditor($id, $value = '', $options = array())
- {
- $s = '';
- $options['height'] = empty($options['height']) ? 200 : $options['height'];
- $options['allow_upload_video'] = isset($options['allow_upload_video']) ? $options['allow_upload_video'] : true;
- $param = uploadParam();
- $s .= !empty($id) ? "<textarea id=\"{$id}\" name=\"{$id}\" type=\"text/plain\" style=\"height:{$options['height']}px;\">{$value}</textarea>" : '';
- $s .= "
- <script type=\"text/javascript\">
- require(['".$param['util']."'], function(util){
- util.editor('" . ($id ? $id : "") . "', {
- height : {$options['height']},
- dest_dir : '" . ($options['dest_dir'] ? $options['dest_dir'] : "") . "',
- image_limit : " . (intval($param['global']['image_limit']) * 1024) . ",
- allow_upload_video : " . ($options['allow_upload_video'] ? 'true' : 'false') . ",
- audio_limit : " . (intval($param['global']['audio_limit']) * 1024) . ",
- callback : ''
- });
- });
- </script>";
- return $s;
- }
- }
- if (!function_exists('image_put_path')) {
- function image_put_path()
- {
- if (config('app.framework') == 'platform') {
- return base_path('static/upload/');
- }
- return IA_ROOT . '/attachment/';
- }
- }
- if (!function_exists('iserializer')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $value
- * @return string
- */
- function iserializer($value) {
- return serialize($value);
- }
- }
- if (!function_exists('tpl_form_field_date')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $name
- * @param string $value
- * @param bool $withtime
- * @return string
- */
- function tpl_form_field_date($name, $value = '', $withtime = false)
- {
- return _tpl_form_field_date($name, $value, $withtime);
- }
- }
- if (!function_exists('_tpl_form_field_date')) {
- /**
- * 为了兼容微擎使用此方法
- * @param $name
- * @param string $value
- * @param bool $withtime
- * @return string
- */
- function _tpl_form_field_date($name, $value = '', $withtime = false)
- {
- $s = '';
- $withtime = !$withtime ? false : true;
- if ($value) {
- $value = strexists($value, '-') ? strtotime($value) : $value;
- } else {
- $value = TIMESTAMP;
- }
- $value = ($withtime ? date('Y-m-d H:i:s', $value) : date('Y-m-d', $value));
- $s .= '<input type="text" name="' . $name . '" value="' . $value . '" placeholder="请选择日期时间" readonly="readonly" class="datetimepicker form-control" style="padding-left:12px;" />';
- $s .= '
- <script type="text/javascript">
- require(["datetimepicker"], function(){
- var option = {
- lang : "zh",
- step : 5,
- timepicker : ' . (!empty($withtime) ? "true" : "false") . ',
- closeOnDateSelect : true,
- format : "Y-m-d' . (!empty($withtime) ? ' H:i"' : '"') . '
- };
- $(".datetimepicker[name = \'' . $name . '\']").datetimepicker(option);
- });
- </script>';
- return $s;
- }
- }
- if (!function_exists('user_register')) {
- /**
- * 添加用户(为了兼容微擎使用此方法)
- * @param $user
- * @return mixed
- */
- function user_register ($user, $default = null)
- {
- $data = [
- 'username' => trim($user['username']),
- 'password' => bcrypt($user['password']),
- 'salt' => randNum(8),
- 'lastvisit' => time(),
- 'lastip' => Utils::getClientIp(),
- 'joinip' => Utils::getClientIp(),
- 'status' => 2,
- 'remark' => '',
- 'owner_uid' => 0
- ];
- $users_model = new WeiQingUsers;
- $users_model->fill($data);
- $users_model->save();
- $user_uid = $users_model['uid'];
- return $user_uid;
- }
- }
- if (!function_exists('user_hash')) {
- /**
- * 密码加密(为了兼容微擎使用此方法)
- * @param $new_pwd
- * @param $salt
- * @return string
- */
- function user_hash($new_pwd, $salt)
- {
- if (config('app.framework') == 'platform') {
- $password = bcrypt($new_pwd);
- } else {
- global $_W;
- $password = sha1("{$new_pwd}-{$salt}-{$_W['config']['setting']['authkey']}");
- }
- return $password;
- }
- }
- if (!function_exists('uploadUrl')) {
- /**
- * 上传 相关组件 使用的url
- * @return mixed
- */
- function uploadUrl($type = 'default')
- {
- $rand_str = randNum(4, true);
- if (config('app.framework') == 'platform') {
- $url['upload_url'] = '/admin/shop?route=upload.upload.jsUpload&upload_type=';
- $url['image_url'] = '/admin/shop?route=upload.upload.jsImage';
- $url['fetch_url'] = '/admin/shop?route=upload.upload.fetch';
- $url['delet_url'] = '/admin/shop?route=upload.upload.delete';
- $url['video_url'] = '/admin/system/upload/video?local=local&type=video&pagesize=5';
- } else {
- $url['upload_url'] = './index.php?c=site&a=entry&m=yun_shop&do='.$rand_str.'&route=upload.upload.jsUpload&upload_type=';
- if ($type == 'new') {
- $image_url = str_replace('/web','.',yzWebUrl('upload.uploadImage.getImage'));
- $url['image_url'] = $image_url;
- } elseif($type == 'default') {
- $url['image_url'] = './index.php?c=site&a=entry&m=yun_shop&do='.$rand_str.'&route=upload.upload.jsImage';
- }
- $url['fetch_url'] = './index.php?c=site&a=entry&m=yun_shop&do='.$rand_str.'&route=upload.upload.fetch';
- $url['delet_url'] = './index.php?c=site&a=entry&m=yun_shop&do='.$rand_str.'&route=upload.upload.delete';
- $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';
- }
- return $url;
- }
- }
- if (!function_exists('uploadParam')) {
- /**
- * ImageHelper 上传需要的变量
- * @return mixed
- */
- function uploadParam()
- {
- $util = 'util';
- $u_url = 'static/resource/js/app/';
- if (config('app.framework') == 'platform') {
- $global = SystemSetting::settingLoad('global', 'system_global');
- $result['fileSizeLimitImage'] = intval($global['image_limit']) * 1024;
- $result['fileSizeLimitAudio'] = intval($global['audio_limit']) * 1024;
- $util = 'utils';
- $util_url = '/' . $u_url . $util;
- } else {
- $util_url = '/addons/yun_shop/' . $u_url . $util;
- $global = \YunShop::app()->setting['upload'];
- $result['fileSizeLimitImage'] = intval($global['image']['limit']) * 1024;
- $result['fileSizeLimitAudio'] = intval($global['audio']['limit']) * 1024;
- }
- $result['util'] = $util;
- $result['global'] = $global;
- $result['util_url'] = $util_url;
- return $result;
- }
- }
- if (!function_exists('resource_absolute')) {
- function resource_absolute($file)
- {
- if (config('app.framework') == 'platform') {
- return '/' . $file;
- }
- return '/addons/yun_shop/' . $file;
- }
- }
- if (!function_exists('upload_image_local')) {
- function upload_image_local($file)
- {
- if (config('app.framework') == 'platform') {
- if (strexists($file, 'newimage')) {
- $file = ImageHelper::getImageUrl('static/upload/' . substr($file,strripos($file,"newimage")));
- }else {
- $file = ImageHelper::getImageUrl('static/upload/' . substr($file,strripos($file,"image")));
- }
- } else {
- $file = ImageHelper::getImageUrl('attachment/' . substr($file,strripos($file,"image")));
- }
- return $file;
- }
- }
- if (!function_exists('change_to_local_url')) {
- function change_to_local_url($file)
- {
- if (strexists($file, 'storage')) {
- $file = strstr($file, 'storage');
- return request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . $file;
- }
- if (strexists($file, 'static/upload/')) {
- $file = strstr($file, 'static/upload/');
- return request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . $file;
- }
- if (strexists($file, 'attachment/')) {
- $file = strstr($file, 'attachment/');
- return request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . $file;
- }
- $disks = config('filesystems.disks');
- foreach ($disks as $key => $disk) {
- if (strexists($file, $key)) {
- $file = strstr($file, $key);
- break;
- }
- }
- if (config('app.framework') == 'platform') {
- $file = request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . 'static/upload/' . $file;
- } else {
- $file = request()->getSchemeAndHttpHost() . DIRECTORY_SEPARATOR . 'attachment/' . $file;
- }
- return $file;
- }
- }
- if (!function_exists('setSystemVersion')) {
- function setSystemVersion($version, $file)
- {
- $str = file_get_contents(base_path('config/') . $file);
- $str = preg_replace('/"[\d\.]+"/', '"'. $version . '"', $str);
- file_put_contents(base_path('config/') . $file, $str);
- }
- }
- if (!function_exists('changeUmImgPath')) {
- function changeUmImgPath($str = '')
- {
- $details = htmlspecialchars_decode($str);
- preg_match_all("/(\s+src\s?\=)\s?[\'|\"]([^\'|\"]*)/is", $details, $imgs);
- $old_arr = [];
- $new_arr = [];
- if (isset($imgs[2])) {
- foreach ($imgs[2] as $img) {
- $old_arr[] = $img;
- $new_arr[] = yz_tomedia($img);
- }
- }
- $str = str_replace($old_arr, $new_arr, $details);
- return $str;
- }
- }
- //bc计算金额比例
- if (!function_exists('proportionMath')) {
- function proportionMath($money, $proportion)
- {
- return bcdiv(bcmul($money, $proportion, 2), 100, 2);
- }
- }
- if (!function_exists('changeSpecialSymbols')) {
- function changeSpecialSymbols($str = '')
- {
- $regex = "/\/|\~|\,|\。|\!|\?|\“|\”|\【|\】|\『|\』|\:|\;|\《|\》|\’|\‘|\ |\·|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
- return preg_replace($regex,'', $str);
- }
- }
- if (!function_exists('verifyPasswordStrength')) {
- /**
- * 校验密码强度(更多用于操作员之类的密码效验)
- * @param string $password
- * @return bool|\Illuminate\Http\JsonResponse
- */
- function verifyPasswordStrength($password = '')
- {
- // if (preg_match('/[\x{4e00}-\x{9fa5}]/u', $password)>0) {
- // return '密码不能含有中文';
- // }
- $is_check = 0;
- if (config('app.APP_Framework', false) == 'platform') {
- //独立版
- $loginset = SystemSetting::settingLoad('loginset', 'system_loginset');
- $is_check = $loginset['password_verify'];
- }elseif(config('app.APP_Framework', false) != 'platform'){
- //微擎版
- if (\Illuminate\Support\Facades\Schema::hasTable('core_settings')) {
- $setting = \Illuminate\Support\Facades\DB::table('core_settings')->where('key','register')->first();
- if($setting){
- $value = unserialize($setting['value']);
- $is_check = $value['safe']?:0;
- }
- }
- }
- if ($is_check == 1) {
- // if (!preg_match('/(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,30}/', $password)) {
- // return '密码至少为8-16个字符,至少1个大写字母,1个小写字母和一个数字,其他可以任意字符';
- // }
- if (!preg_match('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[.!~@#$%^&*?\(\)+_-]).{8,18}$/', $password)) {
- return '密码长度至少为8位,最多18位,要求包括数字,大小写字母和特殊字符';
- }
- }
- return true;
- }
- }
- if (!function_exists('getMiniAccessToken')) {
- /**
- * 获取小程序全局access_token
- * @param false $force_refresh 强制刷新
- * @return false|mixed
- * @throws \GuzzleHttp\Exception\GuzzleException
- */
- function getMiniAccessToken($force_refresh = false)
- {
- $set = \Setting::get('plugin.min_app');
- $cache_key = 'mini_token:'.$set['key'];
- $token = Redis::get($cache_key);
- if ($force_refresh || empty($token)) {
- $get_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
- $get_token_url = sprintf($get_token_url, $set['key'],$set['secret']);
- $res = (new \GuzzleHttp\Client)->request('GET', $get_token_url);
- $token = json_decode($res->getBody()->getContents(), JSON_FORCE_OBJECT);
- if (isset($token['errcode'])) {
- \Log::debug('------生成小程序二维码获取token出错------', $token);
- return false;
- }
- Redis::setex($cache_key,$token['expires_in']-1500,$token['access_token']);
- return $token['access_token'];
- }
- return $token;
- }
- }
- if (!function_exists('miniVersionCompare')) {
- /**
- * 小程序版本比较,小于传入版本返回false,其他返回true
- * @param string $version
- * @return bool
- */
- function miniVersionCompare($version = '')
- {
- //不是小程序直接返回
- if (request()->type != 2) {
- return true;
- }
- $mini_version = request()->mini_version;
- $mini_version = str_replace('v','',$mini_version);
- $mini_version = explode('.',$mini_version);
- $version = explode('.',$version);
- //版本验证
- foreach ($mini_version as $key=>$value) {
- if ($mini_version[$key] < $version[$key]) {
- return false;
- }
- }
- return true;
- }
- }
- if (!function_exists('versionCompare')) {
- /**
- * H5版本比较,小于传入版本返回false,其他返回true
- * @param string $version
- * @return bool
- */
- function versionCompare($version = '')
- {
- if (request()->type == 2) {
- return true;
- }
- $front_version = request()->version;
- $front_version = str_replace('v','',$front_version);
- $front_version = explode('.',$front_version);
- $version = explode('.',$version);
- //版本验证
- foreach ($front_version as $key=>$value) {
- if ($front_version[$key] < $version[$key]) {
- return false;
- }
- }
- return true;
- }
- }
- if (!function_exists('substrCut')) {
- /**
- * 只保留字符串首尾字符,隐藏中间用*代替(两个字符时只显示第一个)
- * @param string $user_name 姓名
- * @return string 格式化后的姓名
- */
- function substrCut($user_name) {
- $strlen = mb_strlen($user_name, 'utf-8');
- $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
- $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
- if ($strlen < 2) {
- return $user_name;
- } else {
- return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
- }
- }
- }
- if (!function_exists('validatePassword')) {
- /**
- * 密码强度效验统一规则(更多用于平台的密码强度效验)
- * @param $password
- * @return string
- */
- function validatePassword($password) {
- $is_check = 0;
- if (config('app.APP_Framework', false) == 'platform') {
- //独立版
- $loginset = SystemSetting::settingLoad('loginset', 'system_loginset');
- $is_check = $loginset['password_verify'];
- }elseif(config('app.APP_Framework', false) != 'platform'){
- //微擎版
- if (\Illuminate\Support\Facades\Schema::hasTable('core_settings')) {
- $setting = \Illuminate\Support\Facades\DB::table('core_settings')->where('key','register')->first();
- if($setting){
- $value = unserialize($setting['value']);
- $is_check = $value['safe']?:0;
- }
- }
- }
- if ($is_check == 1) {
- if (!preg_match('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[.!~@#$%^&*?\(\)+_-]).{8,18}$/', $password)) {
- return '密码长度至少为8位,要求包括数字,大小写字母和特殊字符';
- }
- }
- return true;
- }
- /*
- if (!function_exists("yz_tpl_ueditor")) {
- function yz_tpl_ueditor($id, $value = '', $options = array()){
- $upload_url1 = yzWebFullUrl('upload.uploadV2.upload-vue');
- if (config('app.framework') == 'platform') {
- $file_dir = '';
- } else {
- $file_dir = '../addons/yun_shop';
- }
- $s = '';
- $s .= '<script src="'.$file_dir.'/static/yunshop/tinymce4.7.5/tinymce.min.js"></script>
- <script>
- tinymce.init({
- selector: \'#textarea\',
- fontsize_formats: "8px 10px 12px 14px 18px 24px 36px",
- 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 \'],
- 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 \'],
- language:\'zh_CN\',
- height: "500px",
- file_picker_callback: function(callback, value, meta) {
- //文件分类
- var filetype = \'.pdf, .jpg, .jpeg, .png, .gif, .mp3, .mp4\';
- //后端接收上传文件的地址
- var upurl = \''.$upload_url1.'\' +\'&upload_type=video\';
- //为不同插件指定文件类型及后端地址
- switch (meta.filetype) {
- case \'image\':
- upurl = \''.$upload_url1.'\' +\'&upload_type=image\';
- filetype = \'.jpg, .jpeg, .png, .gif\';
- break;
- case \'media\':
- filetype = \'.mp3, .mp4\';
- break;
- case \'file\':
- default:
- }
- //模拟出一个input用于添加本地文件
- var input = document.createElement(\'input\');
- input.setAttribute(\'type\', \'file\');
- input.setAttribute(\'accept\', filetype);
- input.click();
- input.onchange = function(F) {
- var file = this.files[0];
- // const loading = component.$loading({
- // lock: true,
- // text: \'正在上传\',
- // spinner: \'el-icon-loading\',
- // background: \'rgba(0, 0, 0, 0.7)\'
- // });
- var xhr, formData;
- // console.log(file, file.name);
- xhr = new XMLHttpRequest();
- xhr.withCredentials = false;
- xhr.open(\'POST\', upurl);
- xhr.onload = function() {
- var json;
- if (xhr.status != 200) {
- loading.close();
- // failure(\'HTTP Error: \' + xhr.status);
- return;
- }
- json = JSON.parse(xhr.responseText);
- if (!json || typeof json.location != \'string\') {
- // failure(\'Invalid JSON: \' + xhr.responseText);
- return;
- }
- // loading.close();
- callback(encodeURI(json.location), {
- title: file.name
- });
- };
- formData = new FormData();
- formData.append(\'file\', file, file.name);
- xhr.send(formData);
- };
- },
- media_url_resolver: (data, resolve)=> {
- try {
- let videoUri = encodeURI(data.url);
- if(data.url.indexOf(\'.mp4\')>-1) {
- // 判断是否mp4 否则用ifarme嵌套
- let embedHtml = `<p>
- <video src=${ data.url } width="100%" height="auto" style="max-width: 100%;" allowfullscreen="false" controls="controls" controlslist="nodownload">
- </video>
- </p>`;
- resolve({ html: embedHtml });
- }else {
- let embedHtml = `<p>
- <iframe frameborder="0" src=${ data.url } width="100%" height="100%" style="max-width: 100%;">
- </iframe>
- </p>`;
- resolve({ html: embedHtml });
- }
- } catch (e) {
- resolve({ html: "" });
- }
- },
- });
- </script>
- ';
- $s .= '
- <form method="post">
- <textarea id="textarea" name="'.$id.'" style="height:500px;">'.$value.'</textarea>
- </form>';
- return $s;
- }
- }
- */
- }
- if (!function_exists('passwordVerifyStatus')) {
- /**
- * @return bool|string
- */
- function passwordVerifyStatus()
- {
- $is_check = 0;
- if (config('app.APP_Framework', false) == 'platform') {
- //独立版
- $loginset = SystemSetting::settingLoad('loginset', 'system_loginset');
- $is_check = $loginset['password_verify'];
- }elseif(config('app.APP_Framework', false) != 'platform'){
- //微擎版
- if (\Illuminate\Support\Facades\Schema::hasTable('core_settings')) {
- $setting = \Illuminate\Support\Facades\DB::table('core_settings')->where('key','register')->first();
- if($setting){
- $value = unserialize($setting['value']);
- $is_check = $value['safe']?:0;
- }
- }
- }
- if ($is_check == 1) {
- return true;//开启了密码强度效验
- }
- return false;
- }
- /**
- * 四舍六入五成双规则、银行进位法
- * 被修约的数字等于5时,要看5前面的数字,
- * 若是奇数则进位,若是偶数则将5舍掉,即修约后末尾数字都成为偶数;
- * 若5的后面还有不为'0'的任何数,则此时无论5的前面是奇数还是偶数,均应进位
- */
- if (!function_exists('bankerRounding')) {
- function bankerRounding($money, $precision = 2)
- {
- return round($money,$precision,PHP_ROUND_HALF_EVEN);
- }
- }
- }
|