天使漫步IT工作室

【ACI教程】用实例学习ACI(十)


Beditor.php 代码清单:

<?php
//header('Access-Control-Allow-Origin: http://www.baidu.com'); //设置http://www.baidu.com允许跨域访问
//header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header
date_default_timezone_set("Asia/Chongqing");
error_reporting(E_ERROR);
header("Content-Type: text/html; charset=utf-8");
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * AutoCodeIgniter.com
 *
 * 基于CodeIgniter核心模块自动生成程序
 *
 * 源项目       AutoCodeIgniter
 * 作者:       AutoCodeIgniter.com Dev Team EMAIL:hubinjie@outlook.com QQ:5516448
 * 版权:       Copyright (c) 2015 , AutoCodeIgniter com.
 * 项目名称:百度编辑器
 * 版本号:1 
 * 最后生成时间:2016-01-19 22:18:24 
 */
class Beditor extends Member_Controller
{
    var $method_config;
    public $CONFIG;
    function __construct()
    {
        parent::__construct();
        $this->load->library('Uploader');
        $this->load->model(array('Beditor_model'));
        $this->load->helper(array('auto_codeIgniter_helper', 'array'));
        //保证排序安全性
        $this->method_config['sort_field'] = array(
            'upfile_id' => 'upfile_id',
            'user_id' => 'user_id',
            'file_url' => 'file_url',
            'file_name' => 'file_name',
            'm_time' => 'm_time',
            'file_type' => 'file_type',
            'path_type' => 'path_type',
        );
        $this->CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("config.json")), true);
    }
    /**
     * 默认首页列表
     * @param int $pageno 当前页码
     * @return void
     */
    function index()
    {
        $action = $_GET['action'];
        $CONFIG = $this->CONFIG;
        switch ($action) {
            case 'config':
                $result =  json_encode($CONFIG);
                break;
            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                $result = $this->action_upload();
                /* result返回值示例:'{"state":"SUCCESS","url":"\\/aci\\/uploadfile\\/images\\/20160130\\/1454162164348987.gif",
                "title":"1454162164348987.gif","original":"17_avatar_middle.jpg.gif","type":".gif","size":8887}'*/
                /* 将上传成功的文件信息入库 */
                $_arr = json_decode($result, true);
                $upload = array();
                $path_type = "attachment";
                if($_arr['state'] == 'SUCCESS')
                {
                    $upload['user_id'] = $_SESSION['user_id'];
                    $upload['file_url'] = safe_replace($_arr['url']);
                    $upload['file_name'] = safe_replace($_arr['title']);
                    $upload['m_time'] = time();
                    $upload['file_type'] = safe_replace(str_replace('.','',$_arr['type']));
                    $upload['path_type'] = $action;
                    $this->Beditor_model->insert($upload);
                }
                break;
            /* 列出图片 */
            case 'listimage':
                $result = $this->action_list();
                break;
            /* 列出文件 */
            case 'listfile':
                $result = $this->action_list();
                break;
            /* 抓取远程文件 */
            case 'catchimage':
                $result = $this->action_crawler();
                /* result值示例:'{"state":"SUCCESS","list":[{"state":"SUCCESS","url":"\\/aci\\/uploadfile\\/images\\/20160130\\/1454161529124396.gif",
                "size":9166,"title":"1454161529124396.gif","original":"aliyun300.gif","source":"http:\\/\\/files.jb51.net\\/image\\/aliyun300.gif"}]}'*/
                /* 将上传成功的文件信息入库 */
                $_arr = json_decode($result, true);
                $upload = array();
                for($i = 0;$i < count($_arr['list']);$i++)
                {
                    if($_arr['list'][$i]['state'] == 'SUCCESS')
                    {
                        $upload['user_id'] = $_SESSION['user_id'];
                        $upload['file_url'] = safe_replace($_arr['list'][$i]['url']);
                        $upload['file_name'] = safe_replace($_arr['list'][$i]['title']);
                        $upload['m_time'] = time();
                        $upload['file_type'] = safe_replace(pathinfo($_arr['list'][$i]['title'], PATHINFO_EXTENSION));
                        $upload['path_type'] = $action;
                        $this->Beditor_model->insert($upload);
                    }
                }
                break;
            default:
                $result = json_encode(array(
                    'state'=> '请求地址出错'
                ));
                break;
        }
        /* 输出结果 */
        if (isset($_GET["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
            } else {
                echo json_encode(array(
                    'state' => 'callback参数不合法'
                ));
            }
        } else {
            echo $result;
        }
    }
    function action_upload()
    {
        /* 上传配置 */
        $base64 = "upload";
        $CONFIG = $this->CONFIG;
        switch (htmlspecialchars($_GET['action'])) {
            case 'uploadimage':
                $config = array(
                    "pathFormat" => $CONFIG['imagePathFormat'],
                    "maxSize" => $CONFIG['imageMaxSize'],
                    "allowFiles" => $CONFIG['imageAllowFiles']
                );
                $fieldName = $CONFIG['imageFieldName'];
                break;
            case 'uploadscrawl':
                $config = array(
                    "pathFormat" => $CONFIG['scrawlPathFormat'],
                    "maxSize" => $CONFIG['scrawlMaxSize'],
                    "allowFiles" => $CONFIG['scrawlAllowFiles'],
                    "oriName" => "scrawl.png"
                );
                $fieldName = $CONFIG['scrawlFieldName'];
                $base64 = "base64";
                break;
            case 'uploadvideo':
                $config = array(
                    "pathFormat" => $CONFIG['videoPathFormat'],
                    "maxSize" => $CONFIG['videoMaxSize'],
                    "allowFiles" => $CONFIG['videoAllowFiles']
                );
                $fieldName = $CONFIG['videoFieldName'];
                break;
            case 'uploadfile':
            default:
                $config = array(
                    "pathFormat" => $CONFIG['filePathFormat'],
                    "maxSize" => $CONFIG['fileMaxSize'],
                    "allowFiles" => $CONFIG['fileAllowFiles']
                );
                $fieldName = $CONFIG['fileFieldName'];
                break;
        }
        /* 生成上传实例对象并完成上传 */
        $up = new Uploader($fieldName, $config, $base64);
        /**
         * 得到上传文件所对应的各个参数,数组结构
         * array(
         *     "state" => "",          //上传状态,上传成功时必须返回"SUCCESS"
         *     "url" => "",            //返回的地址
         *     "title" => "",          //新文件名
         *     "original" => "",       //原始文件名
         *     "type" => ""            //文件类型
         *     "size" => "",           //文件大小
         * )
         */
        /* 返回数据 */
        return json_encode($up->getFileInfo());
    }
    function action_crawler()
    {
        /**
         * 抓取远程图片
         * User: Jinqn
         * Date: 14-04-14
         * Time: 下午19:18
         */
        set_time_limit(0);
        $CONFIG = $this->CONFIG;
        /* 上传配置 */
        $config = array(
            "pathFormat" => $CONFIG['catcherPathFormat'],
            "maxSize" => $CONFIG['catcherMaxSize'],
            "allowFiles" => $CONFIG['catcherAllowFiles'],
            "oriName" => "remote.png"
        );
        $fieldName = $CONFIG['catcherFieldName'];
        /* 抓取远程图片 */
        $list = array();
        if (isset($_POST[$fieldName])) {
            $source = $_POST[$fieldName];
        } else {
            $source = $_GET[$fieldName];
        }
        foreach ($source as $imgUrl) {
            $item = new Uploader($imgUrl, $config, "remote");
            $info = $item->getFileInfo();
            array_push($list, array(
                "state" => $info["state"],
                "url" => $info["url"],
                "size" => $info["size"],
                "title" => htmlspecialchars($info["title"]),
                "original" => htmlspecialchars($info["original"]),
                "source" => htmlspecialchars($imgUrl)
            ));
        }
        /* 返回抓取数据 */
        return json_encode(array(
            'state'=> count($list) ? 'SUCCESS':'ERROR',
            'list'=> $list
        ));
    }
    function action_list()
    {
        /* 数组格式示例
        array (
          'state' => 'SUCCESS',
          'list' =>
          array (
            0 =>
            array (
              'url' => '/aci/uploadfile/images/20160131/1454169939434233.png',
              'mtime' => 1454169938,
            ),
            1 =>
            array (
              'url' => '/aci/uploadfile/images/20160131/1454169939256899.png',
              'mtime' => 1454169939,
            ),
          ),
          'start' => '20',
          'total' => 39,
        )*/
        $CONFIG = $this->CONFIG;
        /* 判断类型 */
        switch ($_GET['action']) {
            /* 列出文件 */
            case 'listfile':
                $allowFiles = $CONFIG['fileManagerAllowFiles']; /* 列出的文件类型 */
                $listSize = $CONFIG['fileManagerListSize'];/* 每次列出文件数量 */
                $path = $CONFIG['fileManagerListPath'];/* 指定要列出文件的目录 */
                $path_type = "(path_type='uploadfile')";
                break;
            /* 列出图片 */
            case 'listimage':
            default:
                $allowFiles = $CONFIG['imageManagerAllowFiles'];
                $listSize = $CONFIG['imageManagerListSize'];
                $path = $CONFIG['imageManagerListPath'];
                $path_type = "(path_type='uploadimage' or path_type='catchimage')";
        }
        /* 结果示例 'png|jpg|jpeg|gif|bmp'*/
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);
        /* 获取参数 $start 翻页后,提交过来的参数就是 $listSize  */
        $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
        $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
        $end = $start + $size;
        /* 原先的本地硬盘获取文件列表 如果想使用,去掉屏蔽即可
        $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "":"/") . $path;
        $files = $this->getfiles($path, $allowFiles);
        if (!count($files)) {
            return json_encode(array(
                "state" => "no match file",
                "list" => array(),
                "start" => $start,
                "total" => count($files)
            ));
        }
         获取指定范围的列表
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
            $list[] = $files[$i];
        }*/
//倒序
//for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
//    $list[] = $files[$i];
//      $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
//      $txt=var_export($_arr,true);
//      fwrite($myfile, $txt);
//      fclose($myfile);
//
//}
        /* 数据库方式 文件扩展名也可以用in不用or */
        $Ext = explode('|', $allowFiles);
        $file_type = "(file_type='";
        for($i = 0;$i < count($Ext);$i++)
        {
            if($i == count($Ext)-1)
            {
                $file_type .= $Ext[$i]."')";
            }
            else
            {
                $file_type .= $Ext[$i]."' OR file_type='";
            }
        }
        $list = array();
        $where = 'user_id='.$this->user_id.' AND '.$path_type.' AND '.$file_type;
        $limit = $start.','.$end;
        $count =  $this->Beditor_model->count($where);;
        $data_info = $this->Beditor_model->select($where,['file_url','m_time'],$limit,'upfile_id DESC','','');
        if ($count == 0) {
            return json_encode(array(
                "state" => "no match file",
                "list" => $list,
                "start" => $start,
                "total" => $count
            ));
        }
        else
        {
            $j = 0;
            foreach ($data_info as $rs)
            {
                $list[$j]['url'] = $rs['file_url'];
                $list[$j]['mtime'] = $rs['m_time'];
                $j++;
            }
            /* 返回数据 */
            $result = json_encode(array(
                "state" => "SUCCESS",
                "list" => $list,
                "start" => $start,
                "total" => $count
            ));
        }
        return $result;
    }
    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    function getfiles($path, $allowFiles, &$files = array())
    {
        if (!is_dir($path)) return null;
        if(substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->getfiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(".$allowFiles.")$/i", $file)) {
                        $files[] = array(
                            'url'=> substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
                            'mtime'=> filemtime($path2)
                        );
                    }
                }
            }
        }
        return $files;
    }
}
// END Beditor class
/* End of file Beditor.php */
/* Location: ./Beditor.php */
?>

Beditor_model.php代码清单:

<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * AutoCodeIgniter.com
 *
 * 基于CodeIgniter核心模块自动生成程序
 *
 * 源项目       AutoCodeIgniter
 * 作者:       AutoCodeIgniter.com Dev Team
 * 版权:       Copyright (c) 2015 , AutoCodeIgniter com.
 * 项目名称:百度编辑器 MODEL
 * 版本号:1 
 * 最后生成时间:2016-01-19 22:18:24 
 */
class Beditor_model extends Base_Model {
    
    var $page_size = 10;
    function __construct()
    {
        $this->db_tablepre = 't_aci_';
        $this->table_name = 'upfile';
        parent::__construct();
    }
    
    /**
     * 初始化默认值
     * @return array
     */
    function default_info()
    {
        return array(
        'upfile_id'=>0,
        'file_url'=>'',
        'file_name'=>'',
        'user_id'=>0,
        'm_time'=>0,
        'file_type'=>'',
        'path_type'=>'',
        );
    }
    
    /**
     * 安装SQL表
     * @return void
     */
    function init()
    {
        $this->query("CREATE TABLE  IF NOT EXISTS `t_aci_upfile`
        (
          `upfile_id` int(12) NOT NULL,
          `user_id` mediumint(8) NOT NULL DEFAULT '0' COMMENT '用户id',
          `file_url` varchar(250) NULL DEFAULT NULL COMMENT '文件url',
          `file_name` varchar(150) NULL DEFAULT NULL COMMENT '文件名称'
          `m_time` int(20) NOT NULL DEFAULT '0' COMMENT '建立时间',
          `file_type` varchar(10) NULL DEFAULT NULL COMMENT '文件类型',
          `path_type` varchar(20) NULL DEFAULT NULL COMMENT '上传类型',
        PRIMARY KEY (`upfile_id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
      ");
    }
    
        }
// END news_model class
/* End of file news_model.php */
/* Location: ./news_model.php */
?>

ACI.php中添加的代码:

   'beditor' =>
    array (
        'version' => '1',
        'charset' => 'utf-8',
        'lastUpdate' => '2016-01-19 23:05:51',
        'moduleName' => 'beditor',
        'modulePath' => 'adminpanel',
        'moduleCaption' => '百度编辑器',
        'description' => '由青蛙手动添加的模块',
        'fileList' =>
            array (
                0 => 'application/controllers/adminpanel/Beditor.php',
            ),
        'works' => true,
        'moduleUrl' => 'adminpanel/beditor',
        'system' => false,
        'coder' => '胡子锅',
        'website' => 'http://',
        'moduleDetails' =>
            array (
                0 =>
                    array (
                        'folder' => 'adminpanel',
                        'controller' => 'beditor',
                        'method' => 'index',
                        'menu_name' => '百度编辑器',
                        'caption' => '百度编辑器',
                    ),
                1 =>
                    array (
                        'folder' => 'adminpanel',
                        'controller' => 'beditor',
                        'method' => 'getfiles',
                        'menu_name' => '获取文件列表',
                        'caption' => '获取文件列表',
                    ),
                2 =>
                    array (
                        'folder' => 'adminpanel',
                        'controller' => 'beditor',
                        'method' => 'action_upload',
                        'menu_name' => '文件上传',
                        'caption' => '文件上传',
                    ),
                3 =>
                    array (
                        'folder' => 'adminpanel',
                        'controller' => 'beditor',
                        'method' => 'action_list',
                        'menu_name' => '文件列表',
                        'caption' => '文件列表',
                    ),
                4 =>
                    array (
                        'folder' => 'adminpanel',
                        'controller' => 'beditor',
                        'method' => 'action_crawler',
                        'menu_name' => '获取远程图片',
                        'caption' => '获取远程图片',
                    ),
            ),
    ),

当前页面是本站的「Baidu MIP」版。查看和发表评论请点击:完整版 »