12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514 |
- <?php
- //搜索参数编码转换
- function search_data($str) {
- if (CHARSET=='utf-8') return $str;
- if (CHARSET=='gbk') return iconv("gb2312","utf-8",$str);
- }
- //ajax请求时候的编码转换
- function ajax_data($str) {
- if (CHARSET=='utf-8') return $str;
- if (CHARSET=='gbk') return iconv("utf-8","gb2312",$str);
- }
- //检查模型是否存在,不存在抛出404错误
- function check_record_exists($model)
- {
- if(empty($model))
- {
- if (Yii::$app->request->isAjax) {
- $msgdata = ['error' => 1,'msg' => Yii::t('admin','the record does not exist')];
- echo_json($msgdata);
- }
- else
- {
- throw new \Exception(Yii::t('admin','the record does not exist'),404);
- }
- }
- else
- {
- return true;
- }
- }
- //判断文档是否被删除
- function check_record_delete($model)
- {
- if($model->is_delete)
- {
- if (Yii::$app->request->isAjax) {
- $msgdata = ['error' => 1,'msg' => Yii::t('admin','the record does not exist')];
- echo_json($msgdata);
- }
- else
- {
- throw new \Exception(Yii::t('admin','the record does not exist'),404);
- }
- }
- else
- {
- return true;
- }
- }
- //判断文档是否包含敏感词
- function check_record_badwords($model)
- {
- //过滤时段设置
- $filter = true;
- $hournow = get_date(TIMESTAMP,'H');
- if(Yii::$app->controller->module->badwordconfig['hours'])
- {
- $hours = explode(",",Yii::$app->controller->module->badwordconfig['hours']);
- if(!in_array($hournow,$hours))
- {
- $filter = false;
- }
- }
- if($filter==true)
- {
- $badwords = getRecordBadWords();
- //设定过滤条件(爬虫过滤)
- if(isSpider()&&Yii::$app->controller->module->badwordconfig['open_spider'])
- {
- if(is_array($badwords))foreach($badwords as $badword)
- {
- if(strpos($model->title,$badword)!==false||strpos($model->description,$badword)!==false)
- {
- if (Yii::$app->request->isAjax) {
- $msgdata = ['error' => 1,'msg' => Yii::t('admin','the record does not exist')];
- echo_json($msgdata);
- }
- else
- {
- throw new \Exception(Yii::t('admin','the record does not exist'),404);
- }
- }
- }
- }
- //设定过滤条件(手机站)
- if(!isSpider()&&defined('IN_WAP')&&IN_WAP==TRUE&&Yii::$app->controller->module->badwordconfig['open_wap'])
- {
- if(is_array($badwords))foreach($badwords as $badword)
- {
- if(strpos($model->title,$badword)!==false||strpos($model->description,$badword)!==false)
- {
- if (Yii::$app->request->isAjax) {
- $msgdata = ['error' => 1,'msg' => Yii::t('admin','the record does not exist')];
- echo_json($msgdata);
- }
- else
- {
- throw new \Exception(Yii::t('admin','the record does not exist'),404);
- }
- }
- }
- }
- //设定过滤条件(PC站)
- if(!isSpider()&&defined('REQUEST_FROM')&&REQUEST_FROM==1&&Yii::$app->controller->module->badwordconfig['open_pc'])
- {
- if(is_array($badwords))foreach($badwords as $badword)
- {
- if(strpos($model->title,$badword)!==false||strpos($model->description,$badword)!==false)
- {
- if (Yii::$app->request->isAjax) {
- $msgdata = ['error' => 1,'msg' => Yii::t('admin','the record does not exist')];
- echo_json($msgdata);
- }
- else
- {
- throw new \Exception(Yii::t('admin','the record does not exist'),404);
- }
- }
- }
- }
- return true;
- }
- else
- {
- return true;
- }
- }
- //列表过滤敏感词
- function check_doclist_badwords()
- {
- $badwords1 = getBadWords(1);
- if(!empty($badwords1))
- {
- $units[] = " is_badcom=0 ";
- }
- if(!\app\common\helpers\Identify::hasLogined())
- {
- $badwords2 = getBadWords(2);
- if(!empty($badwords2))
- {
- $units[] = " is_badlogin=0 ";
- }
- }
- if(!\app\common\helpers\Identify::hasLogined()||(\app\common\helpers\Identify::hasLogined()&&!\app\common\helpers\Identify::getUserInfo(NULL,'vip_info')))
- {
- $badwords3 = getBadWords(3);
- if(!empty($badwords3))
- {
- $units[] = " is_badvip=0 ";
- }
- }
- if(!empty($units))
- {
- $sql = ' and '.join(' and ',$units);
- }
- else
- {
- $sql = '';
- }
- //过滤时段设置
- $filter = true;
- $hournow = get_date(TIMESTAMP,'H');
- if(Yii::$app->controller->module->badwordconfig['hours'])
- {
- $hours = explode(",",Yii::$app->controller->module->badwordconfig['hours']);
- if(!in_array($hournow,$hours))
- {
- $filter = false;
- }
- }
- if($filter==true)
- {
- //设定过滤条件(爬虫过滤)
- if(isSpider()&&Yii::$app->controller->module->badwordconfig['open_spider'])
- {
- return $sql;
- }
- //设定过滤条件(手机站)
- if(!isSpider()&&defined('IN_WAP')&&IN_WAP==TRUE&&Yii::$app->controller->module->badwordconfig['open_wap'])
- {
- return $sql;
- }
- //设定过滤条件(PC站)
- if(!isSpider()&&defined('REQUEST_FROM')&&REQUEST_FROM==1&&Yii::$app->controller->module->badwordconfig['open_pc'])
- {
- return $sql;
- }
- return '';
- }
- else
- {
- return '';
- }
- }
- //获取OSS访问绝对URL;
- function getOssUrl()
- {
- if(Yii::$app->params['oss']['OSS_DOMAIN'])
- {
- return SITE_PROTOCOL.Yii::$app->params['oss']['OSS_DOMAIN'].'/';
- }
- else
- {
- return SITE_PROTOCOL.Yii::$app->params['oss']['OSS_BUCKET'].'.'.Yii::$app->params['oss']['OSS_ENDPOINT'].'/';
- }
- }
- //获取OSS内网访问绝对URL;
- function getOssInterUrl()
- {
- return SITE_PROTOCOL.Yii::$app->params['oss']['OSS_BUCKET'].'.'.Yii::$app->params['oss']['OSS_INTERNAL_ENDPOINT'].'/';
- }
- /*
- * $type 1:封面 2:头像
- */
- function getThumb($filepath,$width,$height,$type=1)
- {
- $hash = md5($filepath);
- $img = \app\modules\admin\models\Attachment::find()->where("hash='".$hash."'")->limit(1)->one();
- if($type==1)
- {
- if(empty($img)) $hash = 'noimage';
- $flag = 'p';
- }
- if($type==2)
- {
- if(empty($img)) $hash = 'noavatar';
- $flag = 'avt';
- }
- return APP_URL.$flag.'/'.$width.'/'.$height.'/'.$hash.'.jpg';
- }
- //获取系统配置单个值
- function getSysconfigValue($name,$key=null)
- {
- $sysconfig = \app\modules\admin\models\Sysconfig::find()->where("name='".$name."'")->one();
- if($sysconfig->type==3)
- {
- return $sysconfig->value;
- }
- else
- {
- if($key===null)
- {
- return json_decode($sysconfig->value,true);
- }
- else
- {
- if($sysconfig->type==1)
- {
- $result = json_decode($sysconfig->value,true);
- return $result[$key];
- }
- else
- {
- return $key;
- }
- }
- }
- }
- //获取用户模型下的默认用户组
- function getDefaultUserGroup($contentModelId)
- {
- $userGroup = \app\modules\ucenter\models\UserGroup::find()->where("content_model_id='".$contentModelId."' and is_default=1")->orderBy(['group_id'=>SORT_ASC])->one();
- return $userGroup->group_id;
- }
- //获取用户模型下的默认用户等级
- function getDefaultUserGroupLevel($contentModelId)
- {
- $userGroup = \app\modules\ucenter\models\UserGroup::find()->where("content_model_id='".$contentModelId."' and is_default=1")->orderBy(['group_id'=>SORT_ASC])->one();
- if($userGroup->group_id)
- {
- $userGroupLevel = \app\modules\ucenter\models\UserGroupLevel::find()->where("user_group_id='".$userGroup->group_id."' and is_default=1")->orderBy(['id'=>SORT_ASC])->one();
- return $userGroupLevel->id;
- }
- }
- /**合并搜索参数*
- * $params 表单传递参数
- * $initParams 初始化参数
- * $otherParams 其他参数
- */
- function mergeParams($query,$params,$initParams=[],$otherParams=[])
- {
- $params = count($params)>0?array_merge($initParams,$params):$initParams;
- if (count($params) > 0) {
- $i=0;
- foreach ($params as $key => $value) {
- $value = trim($value);
- if ($value != null) {
- $flag = is_numeric($value)?'=':'like';
- if($i==0){
- $query = $query->where(array($flag, $key, $value));
- }else{
- $query = $query->andWhere(array($flag, $key, $value));
- }
- $i++;
- }
- }
- }
- if(count($otherParams)>0)
- {
- $k=0;
- foreach($otherParams as $v)
- {
- if(count($initParams)==0&&count($params)==0&&$k==0)
- {
- $query = $query->where($v);
- }
- else
- {
- $query = $query->andWhere($v);
- }
- $k++;
- }
- }
- return $query;
- }
- function getLastInsertId()
- {
- return Yii::$app->db->getLastInsertID();
- }
- //CMS权限检测
- function check_rights($id, $ids = '', $s = ',') {
- if(!$ids) return false;
- $ids = explode($s, $ids);
- return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
- }
- //获取用户模型附表名称
- function userDetailTable($content_model_id)
- {
- $contentModel = \app\models\ContentModel::findOne($content_model_id);
- $tablename = Yii::$app->db->tablePrefix.$contentModel->table_name;
- return $tablename;
- }
- //通过分享码获取父级用户
- function getReferIdsByShareNo($share_no)
- {
- $sharelogModel = \app\modules\ucenter\models\ShareLog::find()->where("share_no='".$share_no."'")->one();
- $referer_id = intval($sharelogModel->agent_id);
- $parentUser = \app\modules\ucenter\models\User::findOne($sharelogModel->agent_id);
- if(!empty($parentUser->referer_ids))
- {
- $referer_ids[] = $parentUser->user_id;
- $referer_tempids = explode(",",trim($parentUser->referer_ids,","));
- $referer_ids = array_merge($referer_ids,$referer_tempids);
- }
- else
- {
- $referer_ids[] = $parentUser->user_id;
- }
- return ['referer_id'=>$referer_id,'referer_ids'=>",".join(",",$referer_ids).","];
- }
- /**
- * @todo 敏感词过滤,返回结果
- * @param array $list 定义敏感词一维数组
- * @param string $string 要过滤的内容
- * @return string $log 处理结果
- */
- function sensitive($string){
- $badwordList = Yii::$app->db->createCommand("select * from {{%bad_word}}")->queryAll();
- if($badwordList)foreach($badwordList as $badword)
- {
- if($badword['type']==99) { $list1[] = $badword['bad_word'];$list1_all[] = $badword;}//全局替换
- if($badword['type']==4) $list2[] = $badword['bad_word'];//禁止搜索
- if($badword['type']==88) $list3[] = $badword['bad_word'];//禁止发布
- }
- $count1 = 0; //违规替换词的个数
- $stringAfter = $string; //替换后的内容
- if(!empty($list1))
- {
- $sensitiveWord1 = ''; //违规词
- $pattern = "/".implode("|",$list1)."/i"; //定义正则表达式
- if(preg_match_all($pattern, $string, $matches)){ //匹配到了结果
- $patternList = $matches[0]; //匹配到的数组
- $count1 = count($patternList);
- $sensitiveWord1 = implode(',', $patternList); //敏感词数组转字符串
- $replaceWords = [];
- if($patternList)foreach($patternList as $sesword)
- {
- if($list1_all)foreach($list1_all as $badword)
- {
- if($badword['bad_word']==$sesword)
- {
- $replaceWords[] = $badword['replace_word']?$badword['replace_word']:'*';
- continue;
- }
- }
- }
- if(!empty($replaceWords)&&count($patternList)==count($replaceWords))
- {
- $replaceArray = array_combine($patternList,$replaceWords); //把匹配到的数组进行合并,替换使用
- //$replaceArray = array_combine($patternList,array_fill(0,count($patternList),'*')); //把匹配到的数组进行合并,替换使用
- $stringAfter = strtr($string, $replaceArray); //结果替换
- }
- }
- }
- $count2 = 0; //违规禁止搜索词的个数
- if(!empty($list2))
- {
- $sensitiveWord2 = '';
- $pattern2 = "/".implode("|",$list2)."/i";
- if(preg_match_all($pattern2, $string, $matches)){
- $patternList2 = $matches[0];
- $count2 = count($patternList2);
- $sensitiveWord2 = implode(',', $patternList2);
- }
- }
- $count3 = 0; //违规禁止发布词的个数
- if(!empty($list3))
- {
- $sensitiveWord3 = '';
- $pattern3 = "/".implode("|",$list3)."/i";
- if(preg_match_all($pattern3, $string, $matches)){
- $patternList3 = $matches[0];
- $count3 = count($patternList3);
- $sensitiveWord3 = implode(',', $patternList3);
- }
- }
- if($count1==0&&$count2==0&&$count3==0)
- {
- $result = [];
- }
- else
- {
- $result['after'] = $stringAfter;
- if($count1) {
- $result['log1'] = "全局替换敏感词:[ {$sensitiveWord1} ]";
- }
- else
- {
- $result['log1'] = '';
- }
- if($count2) {
- $result['log2'] = "禁止搜索敏感词:[ {$sensitiveWord2} ]";
- }
- else
- {
- $result['log2'] = '';
- }
- if($count3) {
- $result['log3'] = "禁止发布敏感词:[ {$sensitiveWord3} ]";
- }
- else
- {
- $result['log3'] = '';
- }
- }
- return $result;
- }
- //通过数据库表名获得对应的模型名称
- function getModelName($table)
- {
- $modelName = str_replace('_', ' ', $table);
- $modelName = ucwords($modelName);
- $modelName = str_replace(' ', '', $modelName);
- return $modelName;
- }
- //本地化存储文件到临时目录
- function locateFile($file,$folder='temp')
- {
- $result = parse_url($file);
- $result['path'] = str_replace('/upload/','',$result['path']);
- $relativeFile = ltrim(str_replace('/',DIRECTORY_SEPARATOR,$result['path']),DIRECTORY_SEPARATOR);
- $targetFile = UPLOAD_PATH.$folder.DIRECTORY_SEPARATOR.$relativeFile;
- dir_create(dirname($targetFile));
- if(Yii::$app->params['oss']['OPEN_OSS']==1)
- {
- if(!file_exists($targetFile))
- {
- if(Yii::$app->params['oss']['OPEN_INTERNAL'])
- {
- file_put_contents($targetFile,file_get_contents(str_replace(Yii::$app->params['oss']['OSS_ENDPOINT'],Yii::$app->params['oss']['OSS_INTERNAL_ENDPOINT'],$file)));
- }
- else
- {
- file_put_contents($targetFile,file_get_contents($file));
- }
- }
- }
- else
- {
- if(!file_exists($targetFile))
- {
- file_put_contents($targetFile,file_get_contents($file));
- }
- }
- return $targetFile;
- }
- //合辑下载时候归档所有文档
- function locateColFile($col,$docList)
- {
- $targetPath = UPLOAD_PATH.'download'.DIRECTORY_SEPARATOR.md5($col['id']).DIRECTORY_SEPARATOR;
- dir_create($targetPath);
- if(is_array($docList))foreach($docList as $doc)
- {
- $file = getFileUrl($doc['file']);
- $targetFile = $targetPath.$doc['title'].'.'.$doc['ext'];
- if(Yii::$app->params['oss']['OPEN_OSS']==1)
- {
- if(!file_exists($targetFile))
- {
- if(Yii::$app->params['oss']['OPEN_INTERNAL'])
- {
- file_put_contents($targetFile,file_get_contents(str_replace(Yii::$app->params['oss']['OSS_ENDPOINT'],Yii::$app->params['oss']['OSS_INTERNAL_ENDPOINT'],$file)));
- }
- else
- {
- file_put_contents($targetFile,file_get_contents($file));
- }
- }
- }
- else
- {
- if(!file_exists($targetFile))
- {
- file_put_contents($targetFile,file_get_contents($file));
- }
- }
- }
- $zipFile = dirname($targetPath).DIRECTORY_SEPARATOR.md5($col['id']).'.zip';
- if(!file_exists($zipFile))
- {
- new \app\common\components\Dozip($targetPath,$zipFile);
- }
- return $zipFile;
- }
- //大文件生成下载说明
- function initBigfileTorent($bigfile,$doc,$docConfig)
- {
- $savePath = dirname(str_replace(UPLOAD_PATH,'',$bigfile)).DIRECTORY_SEPARATOR;
- $bigfileUrl = UPLOAD_URL.str_replace(DIRECTORY_SEPARATOR,'/',$savePath).basename($bigfile);
- $torenFile = UPLOAD_PATH.$savePath.$doc['title'].'【下载说明】.txt';
- $torenContents = "【下载地址】".$bigfileUrl.",该地址有效期仅".$docConfig['bigfilesize_time']."小时,请尽快下载!";
- file_put_contents($torenFile,$torenContents);
- $torenUrl = UPLOAD_URL.str_replace(DIRECTORY_SEPARATOR,'/',$savePath).basename($torenFile);
- return $torenUrl;
- }
- //生成网盘资源种子文件
- function initPanfile($doc,$docConfig,$folder='download')
- {
- $savePath = $folder.DIRECTORY_SEPARATOR.get_date(TIMESTAMP,'Ymd').DIRECTORY_SEPARATOR;
- $targetPath = UPLOAD_PATH.$savePath;
- dir_create($targetPath);
- $torenFile = $targetPath.$doc['title'].'【提取说明】.txt';
- $contents = "【提取地址】".$doc['pan_url']."\r\n";
- if($doc['pan_pwd']) $contents .= "【提取密码】".$doc['pan_pwd']."\r\n";
- $contents .= "该地址有效期仅".$docConfig['bigfilesize_time']."小时,请尽快下载!";
- file_put_contents($torenFile,$contents);
- $torenUrl = UPLOAD_URL.str_replace(DIRECTORY_SEPARATOR,'/',$savePath).basename($torenFile);
- return $torenUrl;
- }
- //自动根据文档标题和摘要返回标签(通用)
- function initTags($model)
- {
- $tags = [];
- $tagResultList = \app\models\Tag::find()->where("disabled=0")->all();
- if(is_array($tagResultList))foreach($tagResultList as $tagResult)
- {
- if(strpos($model->title,$tagResult->tag)!==false) $tags[] = $tagResult->tag;
- if(strpos($model->description,$tagResult->tag)!==false) $tags[] = $tagResult->tag;
- }
- if(!empty($tags))
- {
- return join(",",array_unique($tags));
- }
- else
- {
- return '';
- }
- }
- //更新标签
- function refreshTag($tags,$table_name,$data_id,$user_id)
- {
- //清空当前记录关联标签
- \app\models\TagData::deleteAll("table_name='".$table_name."' and data_id=".$data_id);
- $tags = str_replace(",",",",$tags);
- $tagList = explode(",",$tags);
- if(is_array($tagList))foreach($tagList as $tag)
- {
- //更新标签库
- $tagModel = \app\models\Tag::find()->where("tag='".$tag."'")->one();
- if(empty($tagModel))
- {
- $tagModel = new \app\models\Tag();
- $tagModel->tag = $tag;
- $pinyin = new \app\common\components\PinYin();
- $tagModel->pinyin = $pinyin->encode($tagModel->tag);
- $tagModel->create_time = TIMESTAMP;
- $tagModel->user_id = $user_id;
- $tagModel->save();
- }
- //记录关联标签
- $tagDataModel = \app\models\TagData::find()->where("tag_id='".$tagModel->id."' and table_name='".$table_name."' and data_id=".$data_id)->one();
- if(empty($tagDataModel))
- {
- $tagDataModel = new \app\models\TagData();
- $tagDataModel->tag_id = $tagModel->id;
- $tagDataModel->table_name = $table_name;
- $tagDataModel->data_id = $data_id;
- $tagDataModel->user_id = $user_id;
- $tagDataModel->create_time = TIMESTAMP;
- $tagDataModel->save();
- }
- //更新标签被引用数量
- $quote_num = \app\models\TagData::find()->where("tag_id='".$tagModel->id."'")->count();
- $tagModel->quote_num = $quote_num;
- $tagModel->save();
- }
- }
- //获取周期数据
- function getTimeList($stamp=0)
- {
- //昨天
- $predayStart = get_date(mktime(0,0,0,date('m'),date('d')-1,date('Y')),'Y-m-d H:i:s');
- $predayEnd = get_date(mktime(0,0,0,date('m'),date('d'),date('Y'))-1,'Y-m-d H:i:s');
- //今天
- $dayStart = get_date(mktime(0,0,0,date('m'),date('d'),date('Y')),'Y-m-d H:i:s');
- $dayEnd = get_date(mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1,'Y-m-d H:i:s');
- //上周
- $preweekStart = get_date(str_to_time('last week monday'),'Y-m-d 00:00:00');
- $preweekEnd = get_date( str_to_time('last week sunday'),'Y-m-d 23:59:59');
- //$preweekStart = get_date(mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y")),"Y-m-d H:i:s");
- //$preweekEnd = get_date(mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y")),"Y-m-d H:i:s");
- //本周
- $weekStart = get_date(str_to_time('this week monday'),'Y-m-d 00:00:00');
- $weekEnd = get_date( str_to_time('this week sunday'),'Y-m-d 23:59:59');
- //$weekStart = get_date(mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")),"Y-m-d H:i:s");
- //$weekEnd = get_date(mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")),"Y-m-d H:i:s");
- //上月
- $premonthStart = get_date(mktime(0, 0 , 0,date("m")-1,1,date("Y")),"Y-m-d H:i:s");
- $premonthEnd = get_date(mktime(23,59,59,date("m") ,0,date("Y")),"Y-m-d H:i:s");
- //本月
- $monthStart = get_date(mktime(0, 0 , 0,date("m"),1,date("Y")),"Y-m-d H:i:s");
- $monthEnd = get_date(mktime(23,59,59,date("m"),date("t"),date("Y")),"Y-m-d H:i:s");
- //上季度
- $season = ceil((date('n'))/3)-1;//上季度是第几季度
- $presesStart = get_date(mktime(0, 0, 0,$season*3-3+1,1,date('Y')),'Y-m-d H:i:s');
- $presesEnd = get_date(mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y')),'Y-m-d H:i:s');
- //本季度
- $season = ceil((date('n'))/3);//当月是第几季度
- $sesStart = get_date( mktime(0, 0, 0,$season*3-3+1,1,date('Y')),'Y-m-d H:i:s');
- $sesEnd = get_date( mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y')),'Y-m-d H:i:s');
- //去年
- $preyearStart = get_date(mktime(0,0,0,1,1,date("Y",time())-1),"Y-m-d H:i:s");
- $preyearEnd = get_date(mktime(23,59,59,12,31,date("Y",time())-1),"Y-m-d H:i:s");
- //今年
- $yearStart = get_date(mktime(0,0,0,1,1,date("Y",time())),"Y-m-d H:i:s");
- $yearEnd = get_date(mktime(23,59,59,12,31,date("Y",time())),"Y-m-d H:i:s");
- $stampList = array(
- 'predayStart'=>str_to_time($predayStart),
- 'predayEnd'=>str_to_time($predayEnd),
- 'dayStart'=>str_to_time($dayStart),
- 'dayEnd'=>str_to_time($dayEnd),
- 'preweekStart'=>str_to_time($preweekStart),
- 'preweekEnd'=>str_to_time($preweekEnd),
- 'weekStart'=>str_to_time($weekStart),
- 'weekEnd'=>str_to_time($weekEnd),
- 'premonthStart'=>str_to_time($premonthStart),
- 'premonthEnd'=>str_to_time($premonthEnd),
- 'monthStart'=>str_to_time($monthStart),
- 'monthEnd'=>str_to_time($monthEnd),
- 'presesStart'=>str_to_time($presesStart),
- 'presesEnd'=>str_to_time($presesEnd),
- 'sesStart'=>str_to_time($sesStart),
- 'sesEnd'=>str_to_time($sesEnd),
- 'preyearStart'=>str_to_time($preyearStart),
- 'preyearEnd'=>str_to_time($preyearEnd),
- 'yearStart'=>str_to_time($yearStart),
- 'yearEnd'=>str_to_time($yearEnd),
- );
- $list = array(
- 'predayStart'=>($predayStart),
- 'predayEnd'=>($predayEnd),
- 'dayStart'=>($dayStart),
- 'dayEnd'=>($dayEnd),
- 'preweekStart'=>($preweekStart),
- 'preweekEnd'=>($preweekEnd),
- 'weekStart'=>($weekStart),
- 'weekEnd'=>($weekEnd),
- 'premonthStart'=>($premonthStart),
- 'premonthEnd'=>($premonthEnd),
- 'monthStart'=>($monthStart),
- 'monthEnd'=>($monthEnd),
- 'presesStart'=>($presesStart),
- 'presesEnd'=>($presesEnd),
- 'sesStart'=>($sesStart),
- 'sesEnd'=>($sesEnd),
- 'preyearStart'=>($preyearStart),
- 'preyearEnd'=>($preyearEnd),
- 'yearStart'=>($yearStart),
- 'yearEnd'=>($yearEnd),
- );
- return $stamp==1?$stampList:$list;
- }
- /**
- * 获取指定月的前N个月数据
- * @param $number 前number个月
- * @param $time 指定的月份2021-05
- * @return array 结果数据 ["2021-01", "2021-02", "2021-03"]
- */
- function getLastAllMonthByNumber($number, $time) {
- $months = [$time];
- for ($i = 1; $i < $number; $i++) {
- $beforeMonth = get_date(strtotime( $time. '-01' . " -{$i} months"),"Y-m");
- array_unshift($months, $beforeMonth);
- }
- return array_reverse($months);
- }
- //获取当月所有日期
- function get_days( $date ,$rtype = '1')
- {
- $tem = explode('-' , $date); //切割日期 得到年份和月份
- $year = $tem['0'];
- $month = $tem['1'];
- if( in_array($month , array( 1,3 , 5 , 7 , 8 , '01' , '03' ,'05' , '07' ,'08' , 10 , 12)))
- {
- // $text = $year.'年的'.$month.'月有31天';
- $text = '31';
- }
- elseif( $month == 2 )
- {
- if ( $year%400 == 0 || ($year%4 == 0 && $year%100 !== 0) ) //判断是否是闰年
- {
- // $text = $year.'年的'.$month.'月有29天';
- $text = '29';
- }
- else{
- // $text = $year.'年的'.$month.'月有28天';
- $text = '28';
- }
- }
- else{
- // $text = $year.'年的'.$month.'月有30天';
- $text = '30';
- }
- if ($rtype == '2') {
- for ($i = 1; $i <= $text ; $i ++ ) {
- $r[] = $year."-".$month."-".$i;
- }
- } else {
- $r = $text;
- }
- return $r;
- }
- /**
- * @param int $num 要转换的阿拉伯数字
- * @return string 转换成的字符串
- */
- function docnumConvert($num)
- {
- if($num<=1000000)
- {
- return '共<b>'.$num.'</b>份';
- }
- if ($num >= 100000000) {
- $num = '共<b>'.round($num / 100000000, 1).'</b><i class="total">亿</i>份</span>';
- } else if ($num >= 10000000) {
- $num = '共<b>'.round($num / 10000000, 1).'</b><i class="total">千万</i>份</span>';
- }else if ($num >= 100000) {
- $num = '共<b>'.round($num / 10000, 1).'</b><i class="total">万</i>份</span>';
- }
- return $num;
- }
- //美化时长显示
- function secondTime($seconds=0){
- $duration = '';
- $seconds = (int) $seconds;
- if ($seconds <= 0) {
- return $duration.'0秒';
- }
- list($day, $hour, $minute, $second) = explode(' ', gmstrftime('%j %H %M %S', $seconds));
- $day -= 1;
- if ($day > 0) {
- $duration .= (int) $day.'天';
- }
- if ($hour > 0) {
- $duration .= (int) $hour.'小时';
- }
- if ($minute > 0) {
- $duration .= (int) $minute.'分钟';
- }
- if ($second > 0) {
- $duration .= (int) $second.'秒';
- }
- return $duration;
- }
- //生成下载码
- function getDowncode($id)
- {
- $code = rand(100000,999999);
- $exist = \app\modules\doc\models\DocDowncode::find()->where("downcode='".$code."' and doc_id=".$id)->one();
- if(!$exist)
- {
- return $code;
- }
- else
- {
- return getDowncode($id);
- }
- }
- function getMimes()
- {
- $mimes = array(
- 'hqx' => 'application/mac-binhex40',
- 'cpt' => 'application/mac-compactpro',
- 'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel'),
- 'bin' => 'application/macbinary',
- 'dms' => 'application/octet-stream',
- 'lha' => 'application/octet-stream',
- 'lzh' => 'application/octet-stream',
- 'exe' => array('application/octet-stream', 'application/x-msdownload'),
- 'class' => 'application/octet-stream',
- 'psd' => 'application/x-photoshop',
- 'so' => 'application/octet-stream',
- 'sea' => 'application/octet-stream',
- 'dll' => 'application/octet-stream',
- 'oda' => 'application/oda',
- 'pdf' => array('application/pdf', 'application/x-download'),
- 'ai' => 'application/postscript',
- 'eps' => 'application/postscript',
- 'ps' => 'application/postscript',
- 'smi' => 'application/smil',
- 'smil' => 'application/smil',
- 'mif' => 'application/vnd.mif',
- 'xls' => array('application/excel', 'application/vnd.ms-excel', 'application/msexcel'),
- 'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint'),
- 'wbxml' => 'application/wbxml',
- 'wmlc' => 'application/wmlc',
- 'dcr' => 'application/x-director',
- 'dir' => 'application/x-director',
- 'dxr' => 'application/x-director',
- 'dvi' => 'application/x-dvi',
- 'gtar' => 'application/x-gtar',
- 'gz' => 'application/x-gzip',
- 'php' => 'application/x-httpd-php',
- 'php4' => 'application/x-httpd-php',
- 'php3' => 'application/x-httpd-php',
- 'phtml' => 'application/x-httpd-php',
- 'phps' => 'application/x-httpd-php-source',
- 'js' => 'application/x-javascript',
- 'swf' => 'application/x-shockwave-flash',
- 'sit' => 'application/x-stuffit',
- 'tar' => 'application/x-tar',
- 'tgz' => array('application/x-tar', 'application/x-gzip-compressed'),
- 'xhtml' => 'application/xhtml+xml',
- 'xht' => 'application/xhtml+xml',
- 'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed'),
- 'mid' => 'audio/midi',
- 'midi' => 'audio/midi',
- 'mpga' => 'audio/mpeg',
- 'mp2' => 'audio/mpeg',
- 'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'),
- 'aif' => 'audio/x-aiff',
- 'aiff' => 'audio/x-aiff',
- 'aifc' => 'audio/x-aiff',
- 'ram' => 'audio/x-pn-realaudio',
- 'rm' => 'audio/x-pn-realaudio',
- 'rpm' => 'audio/x-pn-realaudio-plugin',
- 'ra' => 'audio/x-realaudio',
- 'rv' => 'video/vnd.rn-realvideo',
- 'wav' => 'audio/x-wav',
- 'bmp' => 'image/bmp',
- 'gif' => 'image/gif',
- 'jpeg' => array('image/jpeg', 'image/pjpeg'),
- 'jpg' => array('image/jpeg', 'image/pjpeg'),
- 'jpe' => array('image/jpeg', 'image/pjpeg'),
- 'png' => array('image/png', 'image/x-png'),
- 'tiff' => 'image/tiff',
- 'tif' => 'image/tiff',
- 'css' => 'text/css',
- 'html' => 'text/html',
- 'htm' => 'text/html',
- 'shtml' => 'text/html',
- 'txt' => 'text/plain',
- 'text' => 'text/plain',
- 'log' => array('text/plain', 'text/x-log'),
- 'rtx' => 'text/richtext',
- 'rtf' => 'text/rtf',
- 'xml' => 'text/xml',
- 'xsl' => 'text/xml',
- 'mpeg' => 'video/mpeg',
- 'mpg' => 'video/mpeg',
- 'mp4' => 'video/mp4',
- 'mpe' => 'video/mpeg',
- 'qt' => 'video/quicktime',
- 'mov' => 'video/quicktime',
- 'avi' => 'video/x-msvideo',
- 'movie' => 'video/x-sgi-movie',
- 'doc' => 'application/msword',
- 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- 'word' => array('application/msword', 'application/octet-stream'),
- 'xl' => 'application/excel',
- 'eml' => 'message/rfc822',
- 'json' => array('application/json', 'text/json')
- );
- return $mimes;
- }
- //获取数据库连接中的数据库名称
- function getDsnAttribute($name, $dsn)
- {
- if (preg_match('/' . $name . '=([^;]*)/', $dsn, $match)) {
- return $match[1];
- } else {
- return null;
- }
- }
- //根据表名(不含前缀名)获取主键名
- function getPrikeyByTableName($table_name)
- {
- $db = Yii::$app->getDb();
- $dbName = getDsnAttribute('dbname', $db->dsn);
- $sqlbuf ="SELECT cu.Column_Name FROM INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` cu
- WHERE CONSTRAINT_NAME = 'PRIMARY' AND cu.Table_Name = '".Yii::$app->db->tablePrefix.$table_name."' AND CONSTRAINT_SCHEMA='".$dbName."';";
- $result = Yii::$app->db->createCommand($sqlbuf)->queryOne();
- return $result['Column_Name'];
- }
- //返回不同内容的详情页链接
- function getContentLink($result)
- {
- if($result['table_name']=='doc_real')
- {
- $url = $result['doc_type']==2?\app\common\components\SiteUrl::colDetail($result['data_id']):\app\common\components\SiteUrl::docDetail($result['data_id']);
- }
- return $url;
- }
- //返回文档详情页链接
- function getDocLink($result)
- {
- $url = $result['doc_type']==2?\app\common\components\SiteUrl::colDetail($result['id']):\app\common\components\SiteUrl::docDetail($result['id']);
- return $url;
- }
- //生成分享分享单号
- function getShareNo()
- {
- $share_no = getProUniOrderNo();
- $exist = \app\modules\ucenter\models\ShareLog::find()->where("share_no='".$share_no."'")->one();
- if(!$exist)
- {
- return $share_no;
- }
- else
- {
- return getShareNo();
- }
- }
- //返回用户提现账户
- function getWithdrawBank($userInfo,$k=0)
- {
- $bankTypes = [];
- if($userInfo['alipay_name']&&$userInfo['alipay_account'])
- {
- $bankTypes[1] = array('title'=>'支付宝','real_name'=>$userInfo['alipay_name'],'account'=>$userInfo['alipay_account'],'desc'=>'支付宝【'.$userInfo['alipay_name'].':'.$userInfo['alipay_account'].'】');
- }
- if($userInfo['bank_real_name']&&$userInfo['bank_name']&&$userInfo['bank_no'])
- {
- $bankTypes[2] = array('title'=>$userInfo['bank_name'],'real_name'=>$userInfo['bank_real_name'],'account'=>$userInfo['bank_no'],'desc'=>$userInfo['bank_name'].'【'.$userInfo['bank_real_name'].':'.$userInfo['bank_no'].'】');
- }
- return $k==0?$bankTypes:$bankTypes[$k];
- }
- //生成海报
- function createPoster($config=array(),$filename=""){
- //如果要看报什么错,可以先注释调这个header
- if(empty($filename)) header("content-type: image/png");
- $imageDefault = array(
- 'left'=>0,
- 'top'=>0,
- 'right'=>0,
- 'bottom'=>0,
- 'width'=>100,
- 'height'=>100,
- 'opacity'=>100
- );
- $textDefault = array(
- 'text'=>'',
- 'left'=>0,
- 'top'=>0,
- 'fontSize'=>32, //字号
- 'fontColor'=>'255,255,255', //字体颜色
- 'angle'=>0,
- );
- $background = $config['background'];//海报最底层得背景
- //背景方法
- $backgroundInfo = getimagesize($background);
- $backgroundFun = 'imagecreatefrom'.image_type_to_extension($backgroundInfo[2], false);
- $background = $backgroundFun($background);
- $backgroundWidth = imagesx($background); //背景宽度
- $backgroundHeight = imagesy($background); //背景高度
- $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight);
- $bg = imagecolorallocatealpha($imageRes, 255, 255, 255, 127);
- imagefill($imageRes, 0, 0, $bg);
- imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));
- //处理了图片
- if(!empty($config['image'])){
- foreach ($config['image'] as $key => $val) {
- $val = array_merge($imageDefault,$val);
- $info = getimagesize($val['url']);
- $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
- if($val['stream']){ //如果传的是字符串图像流
- $info = getimagesizefromstring($val['url']);
- $function = 'imagecreatefromstring';
- }
- $res = $function($val['url']);
- $resWidth = $info[0];
- $resHeight = $info[1];
- //建立画板 ,缩放图片至指定尺寸
- $canvas=imagecreatetruecolor($val['width'], $val['height']);
- //imagefill($canvas, 0, 0, $color);
- //关键函数,参数(目标资源,源,目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h)
- imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight);
- $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
- $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];
- //放置图像
- imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左,上,右,下,宽度,高度,透明度
- }
- }
- //处理头像
- if(!empty($config['avatar'])){
- foreach ($config['avatar'] as $key => $val) {
- if(empty($val))continue;
- $val = array_merge($imageDefault,$val);
- list($res,$resWidth,$resHeight) = toCircleImg($val['url']);
- $res = getNewImgSize($res,$val['width'],$val['height'],$resWidth);
- //关键函数,参数(目标资源,源,目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h)
- $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
- $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];
- imageantialias($imageRes, true);
- imagecopy($imageRes, $res, $val['left'], $val['top'],$val['right'],$val['bottom'], $val['width'], $val['height']);
- }
- }
- //处理缩略图
- if(!empty($config['thumb'])){
- foreach ($config['thumb'] as $key => $val) {
- $info = getimagesize($val['url']);
- $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
- if($val['stream']){ //如果传的是字符串图像流
- $info = getimagesizefromstring($val['url']);
- $function = 'imagecreatefromstring';
- }
- $res = $function($val['url']);
- $info = getimagesize($val['url']);
- $resWidth = $info[0];
- $resHeight = $info[1];
- $canvas=imagecreatetruecolor($val['width'], $val['height']);
- //imagefill($canvas, 0, 0, $color);
- //关键函数,参数(目标资源,源,目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h)
- imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight);
- imagecopy($imageRes, $canvas, $val['left'], $val['top'],$val['right'],$val['bottom'], $val['width'], $val['height']);
- }
- }
- //处理文字
- if(!empty($config['text'])){
- foreach ($config['text'] as $key => $val) {
- if(empty($val))continue;
- $val = array_merge($textDefault,$val);
- list($R,$G,$B) = explode(',', $val['fontColor']);
- $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
- $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
- $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
- imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
- }
- }
- if(!empty($config['text1'])){
- foreach ($config['text1'] as $key => $val) {
- if(empty($val))continue;
- $val = array_merge($textDefault,$val);
- list($R,$G,$B) = explode(',', $val['fontColor']);
- $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
- $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
- $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
- imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
- }
- }
- if(!empty($config['nickname'])){
- foreach ($config['nickname'] as $key => $val) {
- if(empty($val))continue;
- $val = array_merge($textDefault,$val);
- list($R,$G,$B) = explode(',', $val['fontColor']);
- $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
- $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
- $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
- imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
- }
- }
- imagesavealpha($imageRes , true);
- //生成图片
- if(!empty($filename)){
- $res = imagepng ($imageRes,$filename); //保存到本地
- imagedestroy($imageRes);
- if(!$res) return false;
- return $filename;
- }else{
- imagepng ($imageRes); //在浏览器上显示
- imagedestroy($imageRes);
- }
- }
- /*
- * 转换为圆形
- */
- function toCircleImg($imgpath)
- {
- $wh = getimagesize($imgpath);//pathinfo()不准
- $src_img = null;
- switch ($wh[2]) {
- case 1:
- //gif
- $src_img = imagecreatefromgif($imgpath);
- break;
- case 2:
- //jpg
- $src_img = imagecreatefromjpeg($imgpath);
- break;
- case 3:
- //png
- $src_img = imagecreatefrompng($imgpath);
- break;
- }
- $w = $wh[0];
- $h = $wh[1];
- $w = min($w, $h);
- $h = $w;
- $img = imagecreatetruecolor($w, $h);
- imageantialias($img, true);
- //这一句一定要有
- imagesavealpha($img, true);
- //拾取一个完全透明的颜色,最后一个参数127为全透明
- $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
- imagefill($img, 0, 0, $bg);
- //拾取一个完全透明的颜色,最后一个参数127为全透明
- /*$bg=imagecolorallocate($img,255,255,255);
- imagecolortransparent($img,$bg);
- imagefill($img, 0, 0, $bg);*/
- $r = $w / 2; //圆半径
- $y_x = $r; //圆心X坐标
- $y_y = $r; //圆心Y坐标
- for ($x = 0; $x < $w; $x++) {
- for ($y = 0; $y < $h; $y++) {
- $rgbColor = imagecolorat($src_img, $x, $y);
- if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
- imagesetpixel($img, $x, $y, $rgbColor);
- }
- }
- }
- return [$img,$w,$h];
- }
- /*
- * 根据指定尺寸裁剪目标图片,这里统一转成132*132的
- * 注意第一个参数,为了简便,直接传递的是图片资源,如果是绝对地址图片路径,可以加以改造
- */
- function getNewImgSize($imgpath,$new_width,$new_height,$w)
- {
- $image_p = imagecreatetruecolor($new_width, $new_height);//新画布
- $bg = imagecolorallocatealpha($image_p, 255, 255, 255, 127);
- imagefill($image_p, 0, 0, $bg);
- imagecopyresampled($image_p, $imgpath, 0, 0, 0, 0, $new_width, $new_height, $w, $w);
- return $image_p;
- }
- //生成分享单
- function createShareNo($table_name,$data_id,$agent_id)
- {
- $shareLog = \app\modules\ucenter\models\ShareLog::find()->where("table_name='".$table_name."' and data_id=$data_id and agent_id=$agent_id")->one();
- if(empty($shareLog))
- {
- $shareLog = new \app\modules\ucenter\models\ShareLog();
- $shareLog->table_name = $table_name;
- $shareLog->data_id = $data_id;
- $shareLog->agent_id = $agent_id;
- $shareLog->share_no = getShareNo();
- $shareLog->create_time = TIMESTAMP;
- $shareLog->status = 1;
- $shareLog->save();
- }
- return $shareLog;
- }
- //获取搜索敏感词
- function getSearchBadWords()
- {
- $badwords = [];
- $resultList = \app\models\BadWord::find()->where("type=4")->all();
- if(is_array($resultList))foreach($resultList as $result)
- {
- $badwords[] = $result->bad_word;
- }
- if(!\app\common\helpers\Identify::hasLogined())
- {
- $resultList = \app\models\BadWord::find()->where("type=5")->all();
- if(is_array($resultList))foreach($resultList as $result)
- {
- $badwords[] = $result->bad_word;
- }
- }
- if(!\app\common\helpers\Identify::hasLogined()||(\app\common\helpers\Identify::hasLogined()&&!\app\common\helpers\Identify::getUserInfo(NULL,'vip_info')))
- {
- $resultList = \app\models\BadWord::find()->where("type=6")->all();
- if(is_array($resultList))foreach($resultList as $result)
- {
- $badwords[] = $result->bad_word;
- }
- }
- $badwords = array_unique($badwords);
- return $badwords;
- }
- //获取详情页显示敏感词
- function getRecordBadWords()
- {
- $badwords = [];
- $resultList = \app\models\BadWord::find()->where("type=1")->all();
- if(is_array($resultList))foreach($resultList as $result)
- {
- $badwords[] = $result->bad_word;
- }
- if(!\app\common\helpers\Identify::hasLogined())
- {
- $resultList = \app\models\BadWord::find()->where("type=2")->all();
- if(is_array($resultList))foreach($resultList as $result)
- {
- $badwords[] = $result->bad_word;
- }
- }
- if(!\app\common\helpers\Identify::hasLogined()||(\app\common\helpers\Identify::hasLogined()&&!\app\common\helpers\Identify::getUserInfo(NULL,'vip_info')))
- {
- $resultList = \app\models\BadWord::find()->where("type=3")->all();
- if(is_array($resultList))foreach($resultList as $result)
- {
- $badwords[] = $result->bad_word;
- }
- }
- $badwords = array_unique($badwords);
- return $badwords;
- }
- //获取敏感词 type:类型
- function getBadWords($type)
- {
- $badwords = [];
- $resultList = \app\models\BadWord::find()->where("type=$type")->all();
- if(is_array($resultList))foreach($resultList as $result)
- {
- $badwords[] = $result->bad_word;
- }
- $badwords = array_unique($badwords);
- return $badwords;
- }
- //给文本添加锚链接(TAG集合)
- function anchorLinks($str)
- {
- $arr = array();
- $keyLinks = \app\models\Tag::find()->all();
- foreach($keyLinks as $keylink)
- {
- $arr[] = array(
- 'id' => $keylink->key_link_id,
- 'name' => $keylink->word,
- 'url' => $keylink->url,
- );
- }
- $newArr = array();
- foreach ($arr as $k=>$v) {
- $arr[$k]['length'] = abslength($v['name']);
- }
- $newArr = array_sort($arr);
- $array = array($str);
- foreach ($newArr as $vo) {
- $res = preg_replace('/' . $vo['name'] . '/', '|||' . $vo['id'] . '|||', $array[0], 1);
- if($res !== null){
- $array[0] = $res;
- }
- }
- foreach ($newArr as $vo) {
- $array[0] = str_replace('|||' . $vo['id'] . '|||', '<a href="'.$vo['url'].'" target="_blank" title="'.$vo['name'].'">' . $vo['name'] . '</a>', $array[0]);
- }
- return $array[0];
- }
- //上传文件到远程服务器
- function remoteUpload($url,$file,$name='file')
- {
- //$file = UPLOAD_PATH.str_replace("/",DIRECTORY_SEPARATOR,$fileRealPath))
- $ch = curl_init();
- //post数据,使用@符号,curl就会认为是有文件上传
- $curlPost = array($name=> new \CURLFile($file));
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_POST, 1); //POST提交
- curl_setopt($ch, CURLOPT_POSTFIELDS,$curlPost);
- $data =curl_exec($ch);
- curl_close($ch);
- return json_decode($data,true);
- }
- //发送短信通知
- function sendMobileMsg($action,$array)
- {
- extract($array);
- require_once BASE_PATH.'vendor/alimsg/AliMsg.php';
- $tplResult = \app\modules\admin\models\MobileMsgTpl::find()->asArray()->all();
- if(is_array($tplResult))foreach($tplResult as $tpl)
- {
- $tplList[$tpl['key']] = $tpl;
- }
- $configInfo = \app\models\Config::find()->where("name='msg'")->limit(1)->one();
- $config = string2array($configInfo->value);
- $config['tpl'] = $tplList[$action]['code'];
- $argsInfos = explode('\r\n',$tplList[$action]['args']);
- $args = [];
- if(is_array($argsInfos))foreach($argsInfos as $argInfo)
- {
- if(empty($argInfo))continue;
- $tmp = explode("|",$argInfo);
- $args[$tmp[0]] = eval("return $tmp[1];");
- }
- $msgtitle = $tplList[$action]['name'];
- $msgcontent = $tplList[$action]['tpl'];
- foreach($args as $k=>$v)
- {
- $msgcontent = str_replace('${'.$k.'}',$v,$msgcontent);
- }
- Yii::$app->db->createCommand("insert into {{%mobile_msg}} set mobile='".$mobile."',title='".$msgtitle."',content='".$msgcontent."',remarks='".$msgcontent."',sent_time=".TIMESTAMP.",real_sent_time=".TIMESTAMP."")->query();
- $alimsg = \AliMsg::getInitCls($config);
- if($mobile)
- {
- return $alimsg::sendMsg($mobile,$action,$args);
- }
- }
- //剩余时间
- function left_time_str($sale_time,$full=0){
- $left_time = $sale_time - TIMESTAMP;
- if($left_time <= 0){
- return '';
- }
- $str = '';
- $day = floor($left_time/86400);
- $hour = floor(($left_time - $day * 86400)/3600);
- $min = floor((($left_time - $day * 86400) - $hour * 3600)/60);
- if($full)
- {
- if ($day > 0) $str .= $day . '天';
- if ($hour > 0) $str .= $hour . '小时';
- if ($min > 0) $str .= $min . '分钟';
- return $str;
- }
- else
- {
- if ($day > 0) return $day . '天';
- if ($hour > 0) return $hour . '小时';
- if ($min > 0) return $min . '分钟';
- }
- }
- //文档类型封面
- function docTypeThumb($assetsUrl,$ext)
- {
- $agent = check_mobile()?'wap':'web';
- if(!empty(Yii::$app->params['style']))
- {
- $sourcePath = Yii::$app->params['themePath'].Yii::$app->params['theme'].'/'.$agent.'/assets/'.Yii::$app->params['style'];
- }
- else
- {
- $sourcePath = Yii::$app->params['themePath'].Yii::$app->params['theme'].'/'.$agent.'/assets';
- }
- if(file_exists($sourcePath.'/images/icon/'.$ext.'.png'))
- {
- return $assetsUrl.'/images/icon/'.$ext.'.png';
- }
- else
- {
- return $assetsUrl.'/images/icon/null.png';
- }
- }
- ?>
|