FileHelper.php 5.73 KB
<?php

namespace common\helpers;

use Yii;
use common\exts\wechat\PHPSDK;
use common\models\BindDeviceApplyImg;
use common\helpers\Log as AppLog;
use function dirname;
use function fopen;
use function fwrite;
use function is_dir;
use function mkdir;
use function move_uploaded_file;
use function strlen;
use function substr;
use function time;
use function unlink;

/**
 * 文件操作助手类
 * Class FileHelper
 * @package common\helpers
 */
class FileHelper
{
    const TMP_PASTE_PATH    = 'tmp_paste/'; //服务器图片库临时目录
    const TMP_PASTE_PRE     = 'LOCAL_'; //服务器图片库临时目录里面图片前缀

    public static function getUploadPath($path)
    {
        if (!is_dir($path)) {
            @mkdir($path, 0777);
        }
    }


    public static function getUploadQuestionPath($path)
    {
        FileHelper::getUploadPath(dirname($path));
        if (!is_dir($path)) {
            @mkdir($path, 0777);
        }
    }

    /**
     * 移动文件 到上传目录
     * @param $tmp
     * @param $path
     */
    public static function moveUploadFile($tmpFile,$path)
    {
        FileHelper::getUploadQuestionPath(dirname($path));
        if (move_uploaded_file($tmpFile, $path)) {
           return true;
        } else {
            return false;
        }
    }

    /**
     * @param $wechat 微信基础类
     * @param string $media_id 微信公众号的 media_id
     * @param string $imgPathId 可以是applyId 或者 qrcode
     * @return bool|string  返回保存到数据库里面的文件名称是的带URL的,同时会把图片传到阿里云的图片服务器上面
     */
    public static function saveWxImgToRemoveServer(PHPSDK $wechat, $media_id = '', $imgPathId)
    {
        if (empty($media_id)) return false;
        if (empty($wechat)) return false;
        //$media_id ='eMybdyIrotir5myoxiM-le-5wcl6z2Sj1zsN2iwuedza6JgcStey8EziRDZxkLUS';

        $qrcodeArr = $wechat->getMedia($media_id, 1);

        if (empty($qrcodeArr['body'])) {
            //WxLog::init();
            AppLog::DEBUG("=========== saveWxImgToRemoveServer wx error ===============");
            AppLog::DEBUG("=========== errorCode =============== mediaId: {$media_id} ". $wechat->errCode.' errMsg:'. $wechat->errMsg);
            AppErrorLog::error("== saveWxImgToRemoveServer mediaId: {$media_id} WxErrorCode:==".$wechat->errCode. ' errMsg:'. $wechat->errMsg);
            $imgModel = BindDeviceApplyImg::findOne(['wx_server_id'=>$media_id]);
            if ($imgModel) {
                $imgModel->error_msg = $wechat->errCode .":".$wechat->errMsg;
                $imgModel->save();
            }
            //WxLog::ERROR("=========== errorMsg ===============". $wechat->errMsg."\r\n");
            return false;
        }
        
        $filename_root = Yii::getAlias('@app/wx') . "/web/";

        $path = $filename_root.'/tmp';

        if(!is_dir($path))
            @mkdir($path, 0777);
        $fileStr = $media_id;
        $filename = $path.'/'.time().'_'.$fileStr.'.jpg';
        $local_file = fopen($filename, 'w');
        if (false !== $local_file) {
            if (false !== fwrite($local_file, $qrcodeArr['body'])) {
                fclose($local_file);
            }
        }

        // 若未保存记录, imgPathId 应该是二维码
        $stat_path  = ImageManager::getBindApplyImgPath($imgPathId, $fileStr);
        if (!file_exists($filename)) {
            return null;
        }
        $fileSize = filesize($filename);
        if ($fileSize < 2) {
            return null;
        }
        $res = ImageManager::add($filename, $stat_path);
        if (empty($res)) {
            return false;
        } else {
            // 删除缓存文件,这里会出现同时操作删除,结果一个报错,在前面加@
            if (file_exists($filename)) {
                //@unlink($filename);
            }
        }
        return $stat_path;
    }

    /**
     *
     */
    public static function saveBase64ImgFileToLocal($imageStr, $tmpPath = 'tmp/')
    {
        if ($tmpPath) {
            $tmpPastePath = $tmpPath;
        } else {
            $tmpPastePath = 'tmp/';
        }

        $somePath = $dir = Yii::getAlias('@site') . "/".$tmpPastePath;
        if (!is_dir($somePath)) {
            mkdir($somePath, 0777, true);
        }
        if (!is_writable($somePath)) {
            chmod($somePath, 0777);
        }
        $image = imagecreatefromstring($imageStr);
        $fileNameId = self::TMP_PASTE_PRE. date('YmdHis').'_'.mt_rand(100000, 999999);
        $filename = $fileNameId.'.jpg';
        $pathFile = $somePath .$filename;
        imagejpeg($image, $pathFile);
        $tmpPathName = $tmpPastePath.$filename;
        return ['fileNameId' => $fileNameId, 'tmpPathName' => $tmpPathName];
    }

    /**
     *  直接本地传都OSS
     */
    public static function saveLocalImgToRemoveServer($fileNameId = '', $applyId)
    {
        $tmpPastePath = self::TMP_PASTE_PATH;
        $somePath = Yii::getAlias('@app/wx') . "/web/".$tmpPastePath;
        $filename = $somePath.$fileNameId.'.jpg';

        if (!file_exists($filename)) {
            return null;
        }
        $stat_path  = ImageManager::getBindApplyImgPath($applyId, $fileNameId);
        $res = ImageManager::add($filename, $stat_path);
        if (empty($res)) {
            return false;
        }
        return $stat_path;
    }

    /**
     * 筛选出wx 图片和本地图片的id
     */
    public static function filterImage($applyImgIds)
    {
        $resultArr = [];
        foreach ($applyImgIds as $k => $v) {
            if ( FileHelper::TMP_PASTE_PRE == substr($v, 0, strlen(FileHelper::TMP_PASTE_PRE))) {
                $resultArr['local'][] = $v;
            } else {
                $resultArr['wx'][] = $v;
            }
        }
        return $resultArr;
    }
}