李浩杰 4 năm trước cách đây
commit
1bb46e68f9
100 tập tin đã thay đổi với 9484 bổ sung0 xóa
  1. 32 0
      .env.example
  2. 3 0
      .gitattributes
  3. 14 0
      .gitignore
  4. 40 0
      app/Console/Kernel.php
  5. 65 0
      app/Exceptions/Handler.php
  6. 210 0
      app/Helper/AttachmentHelper.php
  7. 71 0
      app/Helper/LogHelper.php
  8. 44 0
      app/Helper/SmsHelper.php
  9. 33 0
      app/Helper/constants.inc.php
  10. 735 0
      app/Helper/functions.inc.php
  11. 106 0
      app/Http/Controllers/Admin/AdminRoleController.php
  12. 151 0
      app/Http/Controllers/Admin/AdminUserController.php
  13. 32 0
      app/Http/Controllers/Admin/Auth/ForgotPasswordController.php
  14. 101 0
      app/Http/Controllers/Admin/Auth/LoginController.php
  15. 71 0
      app/Http/Controllers/Admin/Auth/RegisterController.php
  16. 86 0
      app/Http/Controllers/Admin/Auth/ResetPasswordController.php
  17. 69 0
      app/Http/Controllers/Admin/Base/ActionlogController.php
  18. 192 0
      app/Http/Controllers/Admin/Base/AttachmentController.php
  19. 58 0
      app/Http/Controllers/Admin/Base/ClassController.php
  20. 97 0
      app/Http/Controllers/Admin/Base/CrudController.php
  21. 138 0
      app/Http/Controllers/Admin/Base/DictionaryController.php
  22. 66 0
      app/Http/Controllers/Admin/Base/IndexController.php
  23. 41 0
      app/Http/Controllers/Admin/Base/LogsController.php
  24. 120 0
      app/Http/Controllers/Admin/Base/MenusController.php
  25. 123 0
      app/Http/Controllers/Admin/Base/PhotosController.php
  26. 185 0
      app/Http/Controllers/Admin/Base/RoleController.php
  27. 41 0
      app/Http/Controllers/Admin/Base/SystemController.php
  28. 123 0
      app/Http/Controllers/Admin/Base/ToolController.php
  29. 195 0
      app/Http/Controllers/Admin/Base/UserController.php
  30. 11 0
      app/Http/Controllers/Admin/BaseController.php
  31. 167 0
      app/Http/Controllers/Admin/Controller.php
  32. 18 0
      app/Http/Controllers/Admin/TestController.php
  33. 139 0
      app/Http/Controllers/Admin/User/InfoController.php
  34. 166 0
      app/Http/Controllers/Api/V1/AttachmentController.php
  35. 152 0
      app/Http/Controllers/Api/V1/AuthController.php
  36. 102 0
      app/Http/Controllers/Api/V1/Controller.php
  37. 13 0
      app/Http/Controllers/Controller.php
  38. 38 0
      app/Http/Controllers/Web/AttachmentController.php
  39. 23 0
      app/Http/Controllers/Web/AuthController.php
  40. 14 0
      app/Http/Controllers/Web/Controller.php
  41. 65 0
      app/Http/Kernel.php
  42. 34 0
      app/Http/Middleware/Authenticate.php
  43. 41 0
      app/Http/Middleware/AuthenticateAdmin.php
  44. 47 0
      app/Http/Middleware/Cors.php
  45. 17 0
      app/Http/Middleware/EncryptCookies.php
  46. 26 0
      app/Http/Middleware/RedirectIfAuthenticated.php
  47. 18 0
      app/Http/Middleware/TrimStrings.php
  48. 20 0
      app/Http/Middleware/VerifyCsrfToken.php
  49. 89 0
      app/Models/AccountLog.php
  50. 74 0
      app/Models/AdminAccessModel.php
  51. 41 0
      app/Models/AdminMenusModel.php
  52. 34 0
      app/Models/AdminRoleModel.php
  53. 66 0
      app/Models/AdminUserModel.php
  54. 43 0
      app/Models/BaseAreaModel.php
  55. 32 0
      app/Models/BaseAttachmentModel.php
  56. 40 0
      app/Models/BaseDictionaryModel.php
  57. 104 0
      app/Models/BaseModel.php
  58. 22 0
      app/Models/ClassModel.php
  59. 58 0
      app/Models/UserInfoModel.php
  60. 28 0
      app/Providers/AppServiceProvider.php
  61. 31 0
      app/Providers/AuthServiceProvider.php
  62. 21 0
      app/Providers/BroadcastServiceProvider.php
  63. 32 0
      app/Providers/EventServiceProvider.php
  64. 82 0
      app/Providers/RouteServiceProvider.php
  65. 14 0
      app/Repositories/Base/Criteria.php
  66. 45 0
      app/Repositories/Base/Criteria/MultiWhere.php
  67. 52 0
      app/Repositories/Base/Criteria/OrderBy.php
  68. 21 0
      app/Repositories/Base/DictionaryRepository.php
  69. 358 0
      app/Repositories/Base/Repository.php
  70. 41 0
      app/Repositories/Contracts/CriteriaInterface.php
  71. 78 0
      app/Repositories/Contracts/RepositoryInterface.php
  72. 48 0
      app/Repositories/User/Criteria/MultiWhere.php
  73. 21 0
      app/Repositories/User/InfoRepository.php
  74. 128 0
      app/Services/Admin/Acl.php
  75. 288 0
      app/Services/Admin/AdminUser.php
  76. 150 0
      app/Services/Admin/Menus.php
  77. 181 0
      app/Services/Admin/Role.php
  78. 58 0
      app/Services/Base/AbstractService.php
  79. 309 0
      app/Services/Base/Attachment.php
  80. 18 0
      app/Services/Base/BaseProcess.php
  81. 145 0
      app/Services/Base/DictData.php
  82. 207 0
      app/Services/Base/Dictionary.php
  83. 128 0
      app/Services/Base/ErrorCode.php
  84. 274 0
      app/Services/Base/Routes.php
  85. 71 0
      app/Services/Base/System.php
  86. 197 0
      app/Services/Base/Tree.php
  87. 502 0
      app/Services/CRUD/CRUD.php
  88. 138 0
      app/Services/CRUD/tpl/controller.tpl
  89. 42 0
      app/Services/CRUD/tpl/creteriaMultiWhere.tpl
  90. 35 0
      app/Services/CRUD/tpl/model.tpl
  91. 21 0
      app/Services/CRUD/tpl/repositories.tpl
  92. 118 0
      app/Services/CRUD/tpl/service.tpl
  93. 76 0
      app/Services/CRUD/tpl/view/check.blade.php
  94. 59 0
      app/Services/CRUD/tpl/view/edit.blade.php
  95. 91 0
      app/Services/CRUD/tpl/view/index.blade.php
  96. 11 0
      app/Services/CRUD/tpl/view/view.blade.php
  97. 61 0
      app/Services/Log/LogRemark.php
  98. 187 0
      app/Services/OSS.php
  99. 132 0
      app/Services/User/Info.php
  100. 29 0
      app/User.php

+ 32 - 0
.env.example

xqd
@@ -0,0 +1,32 @@
+APP_ENV=local
+APP_KEY=
+APP_DEBUG=true
+APP_LOG_LEVEL=debug
+APP_URL=http://localhost
+
+DB_CONNECTION=mysql
+DB_HOST=127.0.0.1
+DB_PORT=3306
+DB_DATABASE=homestead
+DB_USERNAME=homestead
+DB_PASSWORD=secret
+
+BROADCAST_DRIVER=log
+CACHE_DRIVER=file
+SESSION_DRIVER=file
+QUEUE_DRIVER=sync
+
+REDIS_HOST=127.0.0.1
+REDIS_PASSWORD=null
+REDIS_PORT=6379
+
+MAIL_DRIVER=smtp
+MAIL_HOST=smtp.mailtrap.io
+MAIL_PORT=2525
+MAIL_USERNAME=null
+MAIL_PASSWORD=null
+MAIL_ENCRYPTION=null
+
+PUSHER_APP_ID=
+PUSHER_APP_KEY=
+PUSHER_APP_SECRET=

+ 3 - 0
.gitattributes

xqd
@@ -0,0 +1,3 @@
+* text=auto
+*.css linguist-vendored
+*.scss linguist-vendored

+ 14 - 0
.gitignore

xqd
@@ -0,0 +1,14 @@
+/node_modules
+/public/storage
+/public/hot
+/storage/*.key
+/vendor
+/.idea
+Homestead.json
+Homestead.yaml
+.env
+.phpstorm.meta.php
+_ide_helper*
+*.lock
+/storage/logs
+/public/upload

+ 40 - 0
app/Console/Kernel.php

xqd
@@ -0,0 +1,40 @@
+<?php
+
+namespace App\Console;
+
+use Illuminate\Console\Scheduling\Schedule;
+use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
+
+class Kernel extends ConsoleKernel
+{
+    /**
+     * The Artisan commands provided by your application.
+     *
+     * @var array
+     */
+    protected $commands = [
+        //
+    ];
+
+    /**
+     * Define the application's command schedule.
+     *
+     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
+     * @return void
+     */
+    protected function schedule(Schedule $schedule)
+    {
+        // $schedule->command('inspire')
+        //          ->hourly();
+    }
+
+    /**
+     * Register the Closure based commands for the application.
+     *
+     * @return void
+     */
+    protected function commands()
+    {
+        require base_path('routes/console.php');
+    }
+}

+ 65 - 0
app/Exceptions/Handler.php

xqd
@@ -0,0 +1,65 @@
+<?php
+
+namespace App\Exceptions;
+
+use Exception;
+use Illuminate\Auth\AuthenticationException;
+use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
+
+class Handler extends ExceptionHandler
+{
+    /**
+     * A list of the exception types that should not be reported.
+     *
+     * @var array
+     */
+    protected $dontReport = [
+        \Illuminate\Auth\AuthenticationException::class,
+        \Illuminate\Auth\Access\AuthorizationException::class,
+        \Symfony\Component\HttpKernel\Exception\HttpException::class,
+        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
+        \Illuminate\Session\TokenMismatchException::class,
+        \Illuminate\Validation\ValidationException::class,
+    ];
+
+    /**
+     * Report or log an exception.
+     *
+     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
+     *
+     * @param  \Exception  $exception
+     * @return void
+     */
+    public function report(Exception $exception)
+    {
+        parent::report($exception);
+    }
+
+    /**
+     * Render an exception into an HTTP response.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  \Exception  $exception
+     * @return \Illuminate\Http\Response
+     */
+    public function render($request, Exception $exception)
+    {
+        return parent::render($request, $exception);
+    }
+
+    /**
+     * Convert an authentication exception into an unauthenticated response.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  \Illuminate\Auth\AuthenticationException  $exception
+     * @return \Illuminate\Http\Response
+     */
+    protected function unauthenticated($request, AuthenticationException $exception)
+    {
+        if ($request->expectsJson()) {
+            return response()->json(['error' => 'Unauthenticated.'], 401);
+        }
+
+        return redirect()->guest(route('login'));
+    }
+}

+ 210 - 0
app/Helper/AttachmentHelper.php

xqd
@@ -0,0 +1,210 @@
+<?php
+namespace App\Helper;
+
+use Illuminate\Http\Request;
+use Illuminate\Http\UploadedFile;
+use Symfony\Component\HttpFoundation\File\Exception\FileException;
+use App\Services\Base\ErrorCode;
+use App\Models\BaseAttachmentModel;
+
+trait AttachmentHelper
+{
+    /**
+     * 上传附件
+     *
+     * @param Request $request  laravel's http request
+     * @param string|array $key 文件key
+     * @param string $tag       文件tag
+     * @param int $size         文件size限制,默认2M
+     * @param array $mimeType   文件mime类型限制,默认不限
+     * @return array|string|int 返回:md5字串|ErrorCode或[md5字串|ErrorCode]
+     */
+    public function uploadAttachment(Request $request, $key, $tag = 'files', $size = 10 * 1024 * 1024, array $mimeType = []) {
+        if ($request->hasFile($key)) {
+            $rel_path = '/upload/' . $tag . '/' . date('Ymd');
+            $path = public_path() . $rel_path;
+            if (!file_exists($path)) {
+                if (!@mkdir($path, 0755, true)) {
+                    return ErrorCode::ATTACHMENT_MKDIR_FAILED;
+                }
+            }
+
+            $files = $request->file($key);
+            if ($files === null) {
+                return ErrorCode::ATTACHMENT_UPLOAD_INVALID;
+            }
+            if ($files instanceof UploadedFile) {
+                $files = [$files];
+            }
+
+            $result = [];
+            foreach ($files as $idx => $file) {
+                if (!$file->isValid()) {
+                    $result[$idx] = ErrorCode::ATTACHMENT_UPLOAD_INVALID;
+                    continue;
+                }
+
+                $fileSize = $file->getSize();
+                if ($fileSize > $size) {
+                    $result[$idx] = ErrorCode::ATTACHMENT_SIZE_EXCEEDED;
+                    continue;
+                }
+
+                $fileMimeType = $file->getMimeType();
+                \Log::info("fileMimeType:".$fileMimeType);
+                if (!empty($mimeType) && !in_array($fileMimeType, $mimeType)) {
+                    $result[$idx] = ErrorCode::ATTACHMENT_MIME_NOT_ALLOWED;
+                    continue;
+                }
+
+                $clientName = $file->getClientOriginalName();
+                $md5 = md5($clientName . time());
+                $md5_filename = $md5 . '.' . $file->getClientOriginalExtension();
+
+                try {
+                    $file->move($path, $md5_filename);
+
+                    $real_path = $path . '/' . $md5_filename;
+                    $url_path = $rel_path . '/' . $md5_filename;
+
+                    $attachment = new BaseAttachmentModel();
+                    $attachment->name = $clientName;
+                    $attachment->md5 = $md5;
+                    $attachment->path = $real_path;
+                    $attachment->url = $url_path;
+                    $attachment->size = $fileSize;
+                    $attachment->file_type = $fileMimeType;
+                    if ($attachment->save()) {
+                        $result[$idx] = $md5;
+                    } else {
+                        @unlink($real_path);
+                        $result[$idx] = ErrorCode::ATTACHMENT_SAVE_FAILED;
+                    }
+                } catch (FileException $e) {
+                    $result[$idx] = ErrorCode::ATTACHMENT_MOVE_FAILED;
+                }
+            }
+            if (count($result) == 1) {
+                return array_shift($result);
+            }
+            return $result;
+        } else {
+            return ErrorCode::ATTACHMENT_UPLOAD_INVALID;
+        }
+
+    }
+
+    public function aliUpload(Request $request, $key, $tag = 'files', $size = 10 * 1024 * 1024, array $mimeType = []){
+
+        if ($request->hasFile($key)) {
+            $rel_path = '/upload/' . $tag . '/' . date('Ymd');
+            $path = public_path() . $rel_path;
+            if (!file_exists($path)) {
+                if (!@mkdir($path, 0755, true)) {
+                    return ErrorCode::ATTACHMENT_MKDIR_FAILED;
+                }
+            }
+
+            $files = $request->file($key);
+            if ($files === null) {
+                return ErrorCode::ATTACHMENT_UPLOAD_INVALID;
+            }
+            if ($files instanceof UploadedFile) {
+                $files = [$files];
+            }
+
+            $result = [];
+            foreach ($files as $idx => $file) {
+                if (!$file->isValid()) {
+                    $result[$idx] = ErrorCode::ATTACHMENT_UPLOAD_INVALID;
+                    continue;
+                }
+
+                $fileSize = $file->getSize();
+                if ($fileSize > $size) {
+                    $result[$idx] = ErrorCode::ATTACHMENT_SIZE_EXCEEDED;
+                    continue;
+                }
+
+                $fileMimeType = $file->getMimeType();
+                \Log::info("fileMimeType:".$fileMimeType);
+                if (!empty($mimeType) && !in_array($fileMimeType, $mimeType)) {
+                    $result[$idx] = ErrorCode::ATTACHMENT_MIME_NOT_ALLOWED;
+                    continue;
+                }
+
+                $clientName = $file->getClientOriginalName();
+                $md5 = md5($clientName . time());
+                $md5_filename = $md5 . '.' . $file->getClientOriginalExtension();
+
+                try {
+                    $file_Path = $file->getRealPath();
+                    OSS::publicUpload(config('alioss.BucketName'),$md5_filename, $file_Path);
+
+                    $attachment = new BaseAttachmentModel();
+                    $attachment->name = $clientName;
+                    $attachment->md5 = $md5;
+                    $attachment->path = config('alioss.FileUrl').$md5_filename;
+                    $attachment->url = config('alioss.FileUrl').$md5_filename;
+                    $attachment->size = $fileSize;
+                    $attachment->file_type = $fileMimeType;
+
+                    if ($attachment->save()) {
+                        $result[$idx] = $md5;
+                    } else {
+                        OSS::publicDeleteObject(config('alioss.BucketName'),$md5_filename);
+                        $result[$idx] = ErrorCode::ATTACHMENT_SAVE_FAILED;
+                    }
+                } catch (FileException $e) {
+                    $result[$idx] = ErrorCode::ATTACHMENT_MOVE_FAILED;
+                }
+            }
+            if (count($result) == 1) {
+                return array_shift($result);
+            }
+            return $result;
+        } else {
+            return ErrorCode::ATTACHMENT_UPLOAD_INVALID;
+        }
+
+
+
+
+    }
+
+    /**
+     * 删除附件
+     *
+     * @param $md5 string 删除文件的md5码
+     * @return int 错误码or 0(成功)
+     */
+    public function deleteAttachment($md5) {
+        $attachment = Attachment::where(['md5' => $md5])->first();
+        if (!$attachment) {
+            return ErrorCode::ATTACHMENT_NOT_EXIST;
+        }
+        if (file_exists($attachment->path)) {
+            if($attachment->path == $attachment->url){
+                $key = explode('/',$attachment->path);
+                OSS::publicDeleteObject(config('alioss.BucketName'),end($key));
+                return 0;
+            }else{
+                if (@unlink($attachment->path)) {
+                    if ($attachment->delete()) {
+                        return 0;
+                    } else {
+                        return ErrorCode::ATTACHMENT_RECORD_DELETE_FAILED;
+                    }
+                } else {
+                    return ErrorCode::ATTACHMENT_DELETE_FAILED;
+                }
+            }
+
+
+        } else {
+            return ErrorCode::ATTACHMENT_NOT_EXIST;
+        }
+
+    }
+
+}

+ 71 - 0
app/Helper/LogHelper.php

xqd
@@ -0,0 +1,71 @@
+<?php
+namespace App\Http\HelperTraits;
+
+use App\Models\AccountLog;
+
+trait LogHelper
+{
+    /**
+     * account log记录
+     * @param $data
+     * @return AccountLog
+     * @throws \Exception
+     */
+//    public function writeAccountLog($data) {
+//        if (!isset($data['obj_type']) || empty($data['obj_type'])) {
+//            throw new \Exception('obj_type must be supplied and cannot be empty');
+//        }
+//        if (!isset($data['obj_id']) || empty($data['obj_id'])) {
+//            throw new \Exception('obj_id must be supplied and cannot be empty');
+//        }
+//        if (!isset($data['direction'])) {
+//            $data['direction'] = 1;
+//        }
+//        if ($data['direction'] != 1 && $data['direction'] != 2) {
+//            throw new \Exception('direction must be 1 or 2');
+//        }
+//        if (isset($data['vm_type']) && !array_key_exists($data['vm_type'], AccountLog::getAllType())) {
+//            throw new \Exception('vm_type invalid');
+//        }
+//        if (isset($data['channel']) && !array_key_exists($data['channel'], AccountLog::getAllChannels())) {
+//            throw new \Exception('channel invalid');
+//        }
+//        if (isset($data['op']) && !array_key_exists($data['op'], AccountLog::getAllop())) {
+//            throw new \Exception('op invalid');
+//        }
+//
+//        return AccountLog::create($data);
+//    }
+//
+//    public function logAccount($objType, $objId, $objName, $op, $vmType, $amount, $direction, $balance, $channel, $note = null) {
+//        return $this->writeAccountLog([
+//            'obj_type'      => $objType,
+//            'obj_id'        => $objId,
+//            'obj_name'      => $objName,
+//            'vm_type'       => $vmType,
+//            'amount'        => $amount,
+//            'balance'       => $balance,
+//            'direction'     => $direction,
+//            'op'            => $op,
+//            'channel'       => $channel,
+//            'note'          => $note,
+//        ]);
+//    }
+
+    private function logAccount($fromType, $fromId, $fromName, $fromAmount,  $op, $toType, $toId, $toName, $toAmount) {
+        return AccountLog::create([
+            'from_type'     => $fromType,
+            'from_id'       => $fromId,
+            'from_name'     => $fromName,
+            'from_amount'   => $fromAmount,
+            'op'            => $op,
+            'to_type'       => $toType,
+            'to_id'         => $toId,
+            'to_name'       => $toName,
+            'to_amount'     => $toAmount,
+        ]);
+    }
+
+
+
+}

+ 44 - 0
app/Helper/SmsHelper.php

xqd
@@ -0,0 +1,44 @@
+<?php
+namespace App\Helper;
+
+use GuzzleHttp\Client as GuzzleHttpClient;
+use GuzzleHttp\Exception\RequestException;
+
+trait SmsHelper
+{
+    public function sendSms($msg, $mobile) {
+        $url = "http://api.106txt.com/smsGBK.aspx?";
+        $account = "swufecredit2017";
+        $password = "mask751002";
+        $password = strtoupper(md5($password));
+        $gwid = 53;
+        $message = iconv("UTF-8", "GB2312", $msg);
+
+        try {
+            $client = new GuzzleHttpClient();
+            $data = [
+                'action'      => 'Send',
+                'username'        => $account,
+                'password'       => $password,
+                'gwid'      => $gwid,
+                'mobile'    => $mobile,
+                'message'       => $message,
+            ];
+            $apiRequest = $client->post($url, [
+                'form_params'      => $data,
+            ]);
+            $resp = $apiRequest->getBody()->getContents();
+            $res = iconv("GB2312", "UTF-8", $resp);
+            $re = json_decode($res, true);
+            \Log::info("发送短信 到手机:$mobile 内容:$msg RESULT:".$re['RESULT']);
+            if (trim($re['CODE']) == '1') {
+                return true;
+            }
+        } catch (RequestException $re) {
+            \Log::info("发送短信错误:".$re->getMessage());
+            return false;
+        }
+        return false;
+    }
+
+}

+ 33 - 0
app/Helper/constants.inc.php

xqd
@@ -0,0 +1,33 @@
+<?php
+/**
+ *  全局的常量配置
+ */
+
+// ===================== 返回状态 ================== //
+define("SUCESS_CODE", 200);
+define("FAILURE_CODE", 400);
+define("SERVER_ERROR",500);
+define("NO_PERMISSION",401);
+define("APP_PATH", str_replace('\\', '/', substr(__DIR__, 0, -6)));
+define("SYSTEM_TIME", time());
+defined("PAGE_NUMS") || define("PAGE_NUMS", 10);
+define("PAGE_MAX_NUMS", 50);
+
+//网站登录SESSION
+define("LOGIN_OPENID_SESSION_KEY", 'LOGIN_OPENID_SESSION_KEY');
+define("AUTH_BACK_REDIRECT", 'AUTH_BACK_REDIRECT');
+
+//网站管理角色
+define("WEB_ADMIN_ROLE", 'ROLE_WEB_ADMIN');
+
+defined("LOGIN_MARK_SESSION_KEY") || define("LOGIN_MARK_SESSION_KEY", 'tewelwekrkjk34293423k4jnn');
+defined("USER_ROOT_ID") || define("USER_ROOT_ID", '0');
+defined("USER_ROOT_EMAIL") || define("USER_ROOT_EMAIL", 'root');
+
+/*
+ * 当前现有系统
+ */
+
+
+
+

+ 735 - 0
app/Helper/functions.inc.php

xqd
@@ -0,0 +1,735 @@
+<?php
+
+/**
+ * 二维数组去重
+ * @return array
+ */
+if (! function_exists('array_unique_two_dimensional')) {
+    function array_unique_multidimensional(array $input)
+    {
+        $unique = [];
+        foreach ($input as $item) {
+            if (! is_array($item)) {
+                return $input;
+            }
+
+            $str = implode(',', $item); //利用implode,将二维数组中的下层数组变成字符串
+            $strArr[] = $str;
+
+            $unique = array_unique($strArr); //去掉重复的字符串,也就是生成一个干净的一维数组
+        }
+
+        $output = [];
+        foreach ($unique as $item) {
+            $output[] = explode(',', $item);
+        }
+
+        return $output;
+    }
+}
+
+
+
+if( ! function_exists('array_to_sort')) {
+    /**
+     * 对二维数组排序
+     * @param string $arr old数组
+     * @param string $keys 要排序的键
+     * @param string $type 排序类型[asc,desc]
+     * @param string $reset 重新排列数组key
+     * @return string 返回排序之后的数组
+     */
+    function array_to_sort($arr, $keys, $type = 'asc', $reset = false)
+    {
+        $keysvalue = $new_array = array();
+        foreach ($arr as $k => $v) {
+            $keysvalue[$k] = $v[$keys];
+        }
+        if ($type == 'asc') {
+            asort($keysvalue);
+        } else {
+            arsort($keysvalue);
+        }
+        reset($keysvalue);
+        foreach ($keysvalue as $k => $v) {
+            if ($reset) {
+                $new_array[] = $arr[$k];
+            } else {
+                $new_array[$k] = $arr[$k];
+            }
+        }
+        return $new_array;
+    }
+}
+
+
+/**
+ * 写作的时间人性化
+ *
+ * @param int $time 写作的时间
+ * @return string
+ */
+if( ! function_exists('showWriteTime'))
+{
+    function showWriteTime($time)
+    {
+        $interval = time() - $time;
+        $format = array(
+            '31536000'  => '年',
+            '2592000'   => '个月',
+            '604800'    => '星期',
+            '86400'     => '天',
+            '3600'      => '小时',
+            '60'        => '分钟',
+            '1'         => '秒'
+        );
+        foreach($format as $key => $value)
+        {
+            $match = floor($interval / (int) $key );
+            if(0 != $match)
+            {
+                return $match . $value . '前';
+            }
+        }
+        return date('Y-m-d', $time);
+    }
+}
+if( ! function_exists('pairList'))
+{
+    function pairList($list, $keyField, $valueField)
+    {
+        $pairList = array();
+        foreach ($list as $one) {
+            $pairList[$one[$keyField]] = $one[$valueField];
+        }
+        return $pairList;
+    }
+}
+
+
+/**
+ * 重新组装url ,如果没有host回自动添加当前host
+ * @param string $url
+ * @param array $query  key=>val
+ * @return string
+ */
+function U ($url, $query = [])
+{
+    $url = ltrim($url, '/');
+    $urlInfo = parse_url($url);
+    $aQuery = [];
+
+    if (isset($urlInfo['query']) && $urlInfo['query'] !== '') {
+        parse_str($urlInfo['query'],$aQuery);
+    }
+    $queryString = http_build_query(array_merge($aQuery, $query));
+    if(isset($urlInfo['host'])) {
+        $url = $urlInfo['scheme'] . '://' . $urlInfo['host'].'/admin/';
+    }else{
+        $url = request()->root() . '/admin/';
+    }
+    $url .= isset($urlInfo['path']) ? $urlInfo['path'] : '';
+    $url .= $queryString === '' ? '' : ('?'.$queryString);
+    return $url;
+}
+/**
+ * 验证角色菜单权限
+ *
+ * @param string $route 路由
+ * @param string $params 附带参数
+ * @return bool
+ */
+
+if( ! function_exists('role'))
+{
+    function role($route, $params = [])
+    {
+        $user = \Auth::guard('admin')->user();
+        $role = session()->get(LOGIN_MARK_SESSION_KEY);
+        if($user['is_root']) {
+            return true;
+        }
+        $route = trim($route);
+        $roles = $role['role'];
+        if(isset($roles[$route])){
+            return true;
+        }else{
+            return false;
+        }
+    }
+}
+if( ! function_exists('dict'))
+{
+    function dict()
+    {
+        return new App\Services\Base\Dictionary;
+    }
+}
+
+
+/**
+ * 隐藏部分手机号码
+ * @param $mobile
+ * @param $hide_length
+ * @return string
+ */
+if( ! function_exists('hidePartMobile'))
+{
+    function hidePartMobile($mobile, $hide_length = 5){
+        $hide_length = intval($hide_length);
+        $hide = '';
+        for($i = 0; $i < $hide_length; $i++){
+            $hide .= '*';
+        }
+        $pattern = "/(1\d{1,2})([0-9]{". $hide_length .",". $hide_length ."})(\d+)/";
+        $replacement = "\$1{$hide}\$3";
+        return preg_replace($pattern, $replacement, $mobile);
+    }
+}
+
+/**
+ * Function echo_log
+ * 输出调试日志
+ * @param $content 输出内容
+ */
+if( ! function_exists('echoLog'))
+{
+    function echoLog($content, $filename = '')
+    {
+        if(is_object($content) || is_array($content)) {
+            $content = var_export($content, true);
+        }
+        $log_path = storage_path() . DIRECTORY_SEPARATOR . "debug_log" . DIRECTORY_SEPARATOR;
+
+        if($filename){
+            $file_path = $log_path . $filename;
+        }else{
+            $file_path = $log_path . "debug_log_" . date("Ymd") . ".txt";
+        }
+
+        if(!file_exists($log_path)){
+            mkdir($log_path,0777);
+        }
+
+        $fp = fopen($file_path, "a");
+        flock($fp, LOCK_EX) ;
+        fwrite($fp,"执行日期:".date("Y-m-d H:i:s",time())."\n".$content."\n\n");
+        flock($fp, LOCK_UN);
+        fclose($fp);
+    }
+}
+if( ! function_exists('curlAjax'))
+{
+    function curlAjax($url) {
+        $cookieStr = '';
+        if($_COOKIE) {
+            foreach ($_COOKIE as $key=>$val) {
+                $cookieStr .= $key . '=' . $val . ';';
+            }
+            $cookieStr = substr($cookieStr, 0,-1);
+        }
+        $headers = array(
+            'Content-Type' => 'text/json;charset=utf-8', // 设置为Ajax方式
+            'X-Requested-With' => 'XMLHttpRequest', // 设置为Ajax方式
+            'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36', // 设置为Ajax方式
+            'Referer' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],
+            'Cookie' => $cookieStr
+        );
+        $headerArr = array();
+        foreach( $headers as $n => $v ) {
+            $headerArr[] = $n .':' . $v;
+        }
+        $ch = curl_init($url);
+        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
+        curl_setopt($ch, CURLOPT_HEADER, 0);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+        $return = curl_exec($ch);
+        curl_close ( $ch );
+        return $return;
+    }
+}
+
+if( ! function_exists('img'))
+{
+    function img($system, $system_primary = NULL, $system_key = NULL, $first = false, $pagesize = PAGE_MAX_NUMS)
+    {
+        $paramArgs = func_get_args();
+        $key = "system_img" . md5(serialize($paramArgs));
+        if(!Cache::has($key) ||  request('no_cache') === 'true') {
+            $data =  \App\Services\Base\Images::getSrc($system, $system_primary, $system_key, $first, $pagesize);
+            \Cache::forever($key,$data);
+        }
+        $data = \Cache::get($key);
+        return $data;
+    }
+}
+
+/**
+ * 字符截取 支持UTF8/GBK
+ * @param $string
+ * @param $length
+ * @param $dot
+ */
+if( ! function_exists('str_cut'))
+{
+    function str_cut($string, $length, $dot = '...') {
+        $strlen = strlen($string);
+        if($strlen <= $length) return $string;
+        $string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
+        $strcut = '';
+        if(strtolower('utf-8') == 'utf-8') {
+            $length = intval($length-strlen($dot)-$length/3);
+            $n = $tn = $noc = 0;
+            while($n < strlen($string)) {
+                $t = ord($string[$n]);
+                if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
+                    $tn = 1; $n++; $noc++;
+                } elseif(194 <= $t && $t <= 223) {
+                    $tn = 2; $n += 2; $noc += 2;
+                } elseif(224 <= $t && $t <= 239) {
+                    $tn = 3; $n += 3; $noc += 2;
+                } elseif(240 <= $t && $t <= 247) {
+                    $tn = 4; $n += 4; $noc += 2;
+                } elseif(248 <= $t && $t <= 251) {
+                    $tn = 5; $n += 5; $noc += 2;
+                } elseif($t == 252 || $t == 253) {
+                    $tn = 6; $n += 6; $noc += 2;
+                } else {
+                    $n++;
+                }
+                if($noc >= $length) {
+                    break;
+                }
+            }
+            if($noc > $length) {
+                $n -= $tn;
+            }
+            $strcut = substr($string, 0, $n);
+            $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
+        } else {
+            $dotlen = strlen($dot);
+            $maxi = $length - $dotlen - 1;
+            $current_str = '';
+            $search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
+            $replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
+            $search_flip = array_flip($search_arr);
+            for ($i = 0; $i < $maxi; $i++) {
+                $current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
+                if (in_array($current_str, $search_arr)) {
+                    $key = $search_flip[$current_str];
+                    $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
+                }
+                $strcut .= $current_str;
+            }
+        }
+        return $strcut.$dot;
+    }
+}
+
+/**
+ * 取得文件扩展
+ *
+ * @param $filename 文件名
+ * @return 扩展名
+ */
+if( ! function_exists('fileExt'))
+{
+    function fileExt($filename)
+    {
+        return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
+    }
+}
+
+/**
+ * 过滤参数
+ *
+ * @param $param    参数数组
+ * @param $allowKey 被允许的KEY集合数组
+ * @return 扩展名
+ */
+if( ! function_exists('filterParam'))
+{
+    function filterParam(array $param, array $allowKey)
+    {
+        $data = array();
+        foreach ($param AS $key => $val) {
+            if(in_array($key, $allowKey)) $data[$key] = $val;
+        }
+        return $data;
+    }
+}
+if(!function_exists('list_to_tree')) {
+    function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0)
+    {
+        // 创建Tree
+        $tree = array();
+        if(is_array($list)) {
+            // 创建基于主键的数组引用
+            $refer = array();
+            foreach ($list as $key => $data) {
+                $refer[$data[$pk]] =& $list[$key];
+            }
+            foreach ($list as $key => $data) {
+                // 判断是否存在parent
+                $parentId = $data[$pid];
+                if ($root == $parentId) {
+                    $tree[] =& $list[$key];
+                }else{
+                    if (isset($refer[$parentId])) {
+                        $parent =& $refer[$parentId];
+                        $parent[$child][] =& $list[$key];
+                    }
+                }
+            }
+        }
+        return $tree;
+    }
+}
+
+
+/**
+ * 判断远程文件是否存在
+ * @param unknown $url
+ * @return boolean
+ */
+function check_remote_file_exists($url)
+{
+    $curl = curl_init($url);
+    curl_setopt($curl, CURLOPT_NOBODY, true);
+    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
+    $result = curl_exec($curl);
+    $found = false;
+    if ($result !== false)
+    {
+        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
+        if ($statusCode == 200)
+        {
+            $found = true;
+        }
+    }
+    curl_close($curl);
+    return $found;
+}
+
+if( ! function_exists('getCacheKey')) {
+    /**
+     * 更具参数获取一个唯一的缓存KEY
+     * @param string $name 名称
+     * @param obj|array|string $data 参数
+     */
+    function getCacheKey($name,$data) {
+        return $name . md5(serialize($data));
+
+    }
+}
+
+function isMobile()
+{
+    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
+    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
+    {
+        return true;
+    }
+    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
+    if (isset ($_SERVER['HTTP_VIA']))
+    {
+        // 找不到为false,否则为true
+        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
+    }
+    // 脑残法,判断手机发送的客户端标志,兼容性有待提高
+    if (isset ($_SERVER['HTTP_USER_AGENT']))
+    {
+        $clientkeywords = array ('nokia',
+            'sony',
+            'ericsson',
+            'mot',
+            'samsung',
+            'htc',
+            'sgh',
+            'lg',
+            'sharp',
+            'sie-',
+            'philips',
+            'panasonic',
+            'alcatel',
+            'lenovo',
+            'iphone',
+            'ipod',
+            'blackberry',
+            'meizu',
+            'android',
+            'netfront',
+            'symbian',
+            'ucweb',
+            'windowsce',
+            'palm',
+            'operamini',
+            'operamobi',
+            'openwave',
+            'nexusone',
+            'cldc',
+            'midp',
+            'wap',
+            'mobile'
+        );
+        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
+        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
+        {
+            return true;
+        }
+    }
+    // 协议法,因为有可能不准确,放到最后判断
+    if (isset ($_SERVER['HTTP_ACCEPT']))
+    {
+        // 如果只支持wml并且不支持html那一定是移动设备
+        // 如果支持wml和html但是wml在html之前则是移动设备
+        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+
+/**
+ * post 提交
+ * @param strint $url
+ * @param array $post_data
+ * @return mixed
+ */
+function formPost($url, $post_data=array(), $timeout=60, $userpwd = null)
+{
+    $ch = curl_init();
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    curl_setopt($ch, CURLOPT_POST, 1);
+    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+    curl_setopt($ch, CURLOPT_HEADER, 0);
+    curl_setopt($ch, CURLOPT_URL, $url);
+    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // 设置超时限制防止死循环
+    curl_setopt($ch, CURLOPT_POST, 1);
+    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
+    // 		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
+    if ($userpwd) {
+        curl_setopt($ch, CURLOPT_HTTPAUTH , CURLAUTH_BASIC);
+        curl_setopt($ch, CURLOPT_USERPWD  , $userpwd);
+    }
+    $result = curl_exec($ch);
+    if (curl_errno($ch)) {
+        // echo curl_error($ch);exit;
+    }
+    curl_close($ch); // 关键CURL会话
+    //	CBase::write_log('formPost' . date("Ymd") . ".log", $result);
+    return $result;
+}
+
+
+/***
+ * @param string $position 图片保存地址
+ * @return string
+ */
+function editor($position='local') {
+    $token  = csrf_token();
+    $editer = <<<HTML
+    <!-- 配置文件 -->
+    <script type="text/javascript" src="/base/neditor-1.5.3/neditor.config.js"></script>
+    <!-- 编辑器源码文件 -->
+    <script type="text/javascript" src="/base/neditor-1.5.3/neditor.all.js"></script>
+    <!-- 实例化编辑器 -->
+    <script type="text/javascript">
+   
+        var ue = UE.getEditor('container',{
+             toolbars: [
+          ["fullscreen","source","autotypeset","bold", "italic","underline","forecolor", "paragraph","fontfamily","fontsize","indent","justifyleft", "justifycenter","justifyright","justifyjustify","link","unlink","simpleupload","insertimage","insertcode"
+          ]],
+           autoHeightEnabled: true,
+           autoFloatEnabled: true,
+           initialFrameHeight:320
+        });
+         UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
+         UE.Editor.prototype.getActionUrl = function(action) {
+        if (action == 'simpleupload' ||  action == 'uploadimage') {
+          return '/admin/Base/Attachment/upload?folder=upload&editor=1&position={$position}';
+        } else {
+            return this._bkGetActionUrl.call(this, action);
+        }
+    };
+   
+        ue.ready(function(){
+        ue.execCommand('serverparam', '_token', '{$token}');
+    })
+    </script>
+HTML;
+
+    return $editer;
+}
+
+
+if( ! function_exists('widget'))
+{
+    function widget($widgetName)
+    {
+        $widgetNameEx = explode('.', $widgetName);
+        if( ! isset($widgetNameEx[1])) return false;
+        $widgetClass = 'App\\Widget\\'.$widgetNameEx[0].'\\'.$widgetNameEx[1];
+        if(app()->bound($widgetName)) return app()->make($widgetName);
+        app()->singleton($widgetName, function() use ($widgetClass)
+        {
+            return new $widgetClass();
+        });
+        return app()->make($widgetName);
+    }
+}
+
+
+//
+//if( ! function_exists('sendSms')) {
+//    // return string 'success' 为成功
+//    function sendSms($msg, $mobile){
+//        $post_data = array();
+//        $post_data['un'] ="N9304000";
+//        $post_data['pw'] = "Mask751002@";
+//        $post_data['msg']="【小洲蔬菜】$msg";
+//        $post_data['phone'] =$mobile;
+//        $post_data['rd']=1;
+//
+//        $post_data['needstatus']='true';
+//        $url='https://sms.253.com/msg/send';
+//        $data=http_build_query($post_data);
+//
+//        if(function_exists('curl_init')){
+//            $curl = curl_init();
+//            curl_setopt($curl, CURLOPT_URL, $url);
+//
+//            if (!empty($data)){
+//                curl_setopt($curl, CURLOPT_POST, 1);
+//                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
+//            }
+//            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
+//            $output = curl_exec($curl);
+//            curl_close($curl);
+//            $result=preg_split("/[,\r\n]/",$output);
+//            if($result[1]==0){
+//                $res = "success";
+//            }else{
+//                $res = "curl error:".$result[1];
+//            }
+//        }elseif(function_exists('file_get_contents')){
+//            $output=file_get_contents($url.$data);
+//            $result=preg_split("/[,\r\n]/",$output);
+//            if($result[1]==0){
+//                $res = "success";
+//            }else{
+//                $res = "error:".$result[1];
+//            }
+//        }else{
+//            $res="error";
+//        }
+//        return $res;
+//    }
+//}
+//
+//if( ! function_exists('sendMultiSms')) {
+//    //  群发短信 $mobiles电话号码之间用英文逗号分割
+//    // return string 'success' 为成功
+//    function sendMultiSms($msg, $mobiles){
+//        $post_data = array();
+//        $post_data['un'] ="M3512322";
+//        $post_data['pw'] = "N8ecbXn0A7dc18";
+//        $post_data['msg']="【小洲蔬菜】$msg 回复TD退订";
+//        $post_data['phone'] =$mobiles;
+//        $post_data['rd']=1;
+//
+//        $post_data['needstatus']='true';
+//        $url='https://sms.253.com/msg/send';
+//        $data=http_build_query($post_data);
+//
+//        if(function_exists('curl_init')){
+//            $curl = curl_init();
+//            curl_setopt($curl, CURLOPT_URL, $url);
+//
+//            if (!empty($data)){
+//                curl_setopt($curl, CURLOPT_POST, 1);
+//                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
+//            }
+//            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
+//            $output = curl_exec($curl);
+//            curl_close($curl);
+//            $result=preg_split("/[,\r\n]/",$output);
+//            if($result[1]==0){
+//                $res = "success";
+//            }else{
+//                $res = "curl error:".$result[1];
+//            }
+//        }elseif(function_exists('file_get_contents')){
+//            $output=file_get_contents($url.$data);
+//            $result=preg_split("/[,\r\n]/",$output);
+//            if($result[1]==0){
+//                $res = "success";
+//            }else{
+//                $res = "error:".$result[1];
+//            }
+//        }else{
+//            $res="error";
+//        }
+//        return $res;
+//    }
+//}
+//
+//
+//if( ! function_exists('sendCaixin')) {
+//    //return  true or false
+//    function sendCaixin($mobile){
+//
+//        $post_data =$data =$msgdata = array();
+//
+//        $url ="http://www.baidu.com";//回调URL
+//        $key ="6MG5jNK4Q15907";//密码
+////文字body
+//        $data['frame']="1"; //文字标识
+//        $data['part']  ="1";//文字标识
+//        $data['type']="1" ;
+//        $data['content']=base64_encode('亲爱的朋友,“芜湖小洲蔬菜”,芜湖人的掌上菜篮子,已是我每天买菜必备工具。好东西首先想到了您,赶快关注使用吧!');
+//
+////图片body
+//        $msgdata['frame']="1";
+//        $msgdata['part']  ="2";//图片标识
+//        $msgdata['type']="2" ;//图片标识
+//        $msgdata['content']=base64_encode(file_get_contents(public_path('app/wap/images/')."qrcode.jpg"));//图片
+//
+//        $post_data['account'] ="C8636841";//账号
+//        $post_data['ext_id']="72175534217316595927";//自传参数
+//        $post_data['msg']=json_encode(array($data,$msgdata)) ;//json
+//        $post_data['phones']  = $mobile;//手机
+//        $post_data['timestamp'] = time();//时间戳
+//
+//        $post_data['title']= '芜湖小洲蔬菜'; //标题
+//
+//        $sign ='account=' . $post_data['account'].'ext_id=' . $post_data['ext_id'].'msg=' . $post_data['msg'].'phones=' . $post_data['phones'].'timestamp=' . $post_data['timestamp'].'title=' . $post_data['title'].'url=' . $url.'key=' . $key;
+//        $sign=md5($sign); //加密
+//        $post_data['sign']=$sign;
+//        $post_data['url']=$url;
+//
+//        $url='http://caixin.253.com/api/send?';
+//        $data = http_build_query($post_data);
+//
+//        if(function_exists('curl_init')){
+//            $curl = curl_init();
+//            curl_setopt($curl, CURLOPT_URL, $url);
+//
+//            if (!empty($data)){
+//                curl_setopt($curl, CURLOPT_POST, 1);
+//                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
+//            }
+//            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
+//            $output = curl_exec($curl);
+//            curl_close($curl);
+//            $res = json_decode($output);
+//            if(is_array($res)&&$res['code']==1){
+//                return true;
+//            }
+//
+//        }
+//        return false;
+//    }
+//}

+ 106 - 0
app/Http/Controllers/Admin/AdminRoleController.php

xqd
@@ -0,0 +1,106 @@
+<?php
+
+namespace App\Http\Controllers\Admin;
+
+use App\Models\AdminRoleModel;
+use App\Models\Department;
+use App\Models\Road;
+use Illuminate\Http\Request;
+
+class AdminRoleController extends BaseController
+{
+    protected $model;
+
+    protected $department;
+
+    protected $model_name = '角色';
+
+    protected $pre_uri = '/admin/AdminRole/';
+
+    protected $view_path = 'admin.admin-roles.';
+
+    protected $redirect_index = '/admin/AdminRole/index';
+
+    public function __construct()
+    {
+        $this->model = new AdminRoleModel();
+    }
+
+    public function index()
+    {
+        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
+        return view($this->view_path . 'index', compact('model', 'model_name','pre_uri'));
+    }
+
+    public function get(Request $request)
+    {
+        $items = $this->model->where('id', '>', 0);
+
+        $tmp_items = collect(['name']);
+        foreach($tmp_items as $tmp_item) {
+            if($request->has($tmp_item) && !empty($request->input($tmp_item))) {
+                $items = $items->where($tmp_item, 'like', '%' . $request->input($tmp_item) . '%');
+            }
+        }
+
+        $select_items = collect([]);
+        foreach($select_items as $select_item) {
+            if($request->has($select_item) && !empty($request->input($select_item))) {
+                $items = $items->where($select_item, '=', $request->input($select_item));
+            }
+        }
+
+        $items = $items->paginate();
+
+        return response()->json(['code' => 0, 'message' => '', 'count' => $items->total(), 'data' => $items->items()]);
+    }
+
+    public function create()
+    {
+        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
+        return view($this->view_path . 'create', compact('model', 'model_name','pre_uri'));
+    }
+
+    public function store(Request $request)
+    {
+        if(empty($request->input('data')) || !is_array($request->input('data'))) return back()->withErrors(['sg_error_info' => '数据错误']);
+        $validator = $this->model->getValidator($request, 'store');
+        if($validator->fails()) {
+            return back()->withErrors($validator)->withInput();
+        }
+        $data = $request->input('data');
+        $res = $this->model->create($data);
+        if(empty($res)) return back()->withErrors(['sg_error_info' => '保存失败']);
+        return redirect($this->pre_uri . 'create')->with(['sg_success_info' => '创建成功']);
+    }
+
+    public function edit(Request $request)
+    {
+        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return back()->withErrors(['sg_error_info' => '找不到要编辑的数据']);
+        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
+        return view($this->view_path . 'edit', compact('model', 'model_name', 'pre_uri', 'item'));
+    }
+
+    public function update(Request $request)
+    {
+        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return back()->withErrors(['sg_error_info' => '找不到要编辑的数据']);
+        if(empty($request->input('data')) || !is_array($request->input('data'))) return back()->withErrors(['sg_error_info' => '数据错误']);
+        $validator = $this->model->getValidator($request, 'update');
+        if($validator->fails()) {
+            return back()->withErrors($validator)->withInput();
+        }
+        $data = $request->input('data');
+        $res = $this->model->where('id', $request->input('id'))->update($data);
+        if(!$res) return back()->withErrors(['sg_error_info' => '数据库保存失败!']);
+        return back()->with(['sg_success_info' => '编辑成功']);
+    }
+
+    public function delete(Request $request)
+    {
+        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return response()->json(['status' => 'fail', 'info' => '找不到要删除的数据']);
+        $res = $item->delete();
+        if (!$res) return response()->json(['status' => 'fail', 'info' => '删除失败']);
+        return response()->json(['status' => 'success', 'info' => '操作成功']);
+    }
+
+}

+ 151 - 0
app/Http/Controllers/Admin/AdminUserController.php

xqd
@@ -0,0 +1,151 @@
+<?php
+namespace App\Http\Controllers\Admin;
+
+use App\Models\AdminRoleModel;
+use App\Models\AdminUserModel;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Auth;
+use Illuminate\Support\Facades\Hash;
+
+class AdminUserController extends BaseController
+{
+    protected $model;
+
+    protected $adminRole;
+
+    protected $road;
+
+    protected $zone;
+
+    protected $model_name = '账号';
+
+    protected $pre_uri = '/admin/AdminUser/';
+
+    protected $view_path = 'admin.admin-users.';
+
+    protected $redirect_index = '/admin/AdminUser/index';
+
+    public function __construct()
+    {
+        $this->model = new AdminUserModel();
+        $this->adminRole = new AdminRoleModel();
+    }
+
+    public function index()
+    {
+        $admin_role_options = $this->adminRole->getOptions();
+        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
+        return view($this->view_path . 'index', compact('model', 'model_name','pre_uri', 'admin_role_options'));
+    }
+
+    public function get(Request $request)
+    {
+        $items = $this->model->where('id', '>', 0);
+
+        $tmp_items = collect(['mobile']);
+        foreach($tmp_items as $tmp_item) {
+            if($request->has($tmp_item) && !empty($request->input($tmp_item))) {
+                $items = $items->where($tmp_item, 'like', '%' . $request->input($tmp_item) . '%');
+            }
+        }
+
+        $select_items = collect([]);
+        foreach($select_items as $select_item) {
+            if($request->has($select_item) && !empty($request->input($select_item))) {
+                $items = $items->where($select_item, '=', $request->input($select_item));
+            }
+        }
+
+        $items = $items->paginate();
+        foreach($items as $item) {
+            $item->role_name = empty($item->adminRole) ? '' : $item->adminRole->name;
+        }
+        return response()->json(['code' => 0, 'message' => '', 'count' => $items->total(), 'data' => $items->items()]);
+    }
+
+    public function create()
+    {
+        $admin_role_options = $this->adminRole->getOptions();
+        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
+        return view($this->view_path . 'create', compact('model', 'model_name','pre_uri', 'admin_role_options'));
+    }
+
+    public function store(Request $request)
+    {
+        if(empty($request->input('data')) || !is_array($request->input('data'))) return back()->withErrors(['sg_error_info' => '数据错误']);
+        $validator = $this->model->getValidator($request, 'store');
+        if($validator->fails()) {
+            return back()->withErrors($validator)->withInput();
+        }
+        $data = $request->input('data');
+        unset($data['password_confirmation']);
+        $data['password'] = bcrypt($data['password']);
+        $res = $this->model->create($data);
+        if(empty($res)) return back()->withErrors(['sg_error_info' => '保存失败']);
+        return redirect($this->pre_uri . 'create')->with(['sg_success_info' => '创建成功']);
+    }
+
+    public function edit(Request $request)
+    {
+        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return back()->withErrors(['sg_error_info' => '找不到要编辑的数据']);
+        $admin_role_options = $this->adminRole->getOptions();
+        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
+        return view($this->view_path . 'edit', compact('model', 'model_name', 'pre_uri', 'item', 'admin_role_options'));
+    }
+
+    public function update(Request $request)
+    {
+        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return back()->withErrors(['sg_error_info' => '找不到要编辑的数据']);
+        if(empty($request->input('data')) || !is_array($request->input('data'))) return back()->withErrors(['sg_error_info' => '数据错误']);
+        $validator = $this->model->getValidator($request, 'update');
+        if($validator->fails()) {
+            return back()->withErrors($validator)->withInput();
+        }
+        $data = $request->input('data');
+        if(isset($data['password']) && !empty($data['password'])) {
+            $data['password'] = bcrypt($data['password']);
+        } else {
+            unset($data['password']);
+        }
+        unset($data['password_confirmation']);
+        $res = $this->model->where('id', $request->input('id'))->update($data);
+        if(!$res) return back()->withErrors(['sg_error_info' => '数据库保存失败!']);
+        return back()->with(['sg_success_info' => '编辑成功']);
+    }
+
+    public function delete(Request $request)
+    {
+        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return response()->json(['status' => 'fail', 'info' => '找不到要删除的数据']);
+        $res = $item->delete();
+        if (!$res) return response()->json(['status' => 'fail', 'info' => '删除失败']);
+        return response()->json(['status' => 'success', 'info' => '操作成功']);
+    }
+
+    public function changePassword()
+    {
+        $item = Auth::guard('admin')->user();
+        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
+        return view($this->view_path . 'change-password', compact('model', 'model_name', 'pre_uri', 'item'));
+    }
+
+    public function updatePassword(Request $request)
+    {
+        $validator = $this->model->getValidator($request, 'change-password');
+        $user = Auth::guard('admin')->user();
+        $data = $request->input('data');
+        $validator->after(function ($validator) use($request, $data, $user) {
+            if(!isset($data['old_password'])) {
+                $validator->errors()->add('old_password', '请填写原来密码');
+            } else if(!Hash::check($data['old_password'], $user['password'])) {
+                $validator->errors()->add('old_password', '原来密码错误');
+            }
+        });
+        if($validator->fails()) {
+            return back()->withErrors($validator)->withInput();
+        }
+
+        $this->model->where('id', $user['id'])->update(['password' => $data['password']]);
+
+        return back()->with(['sg_success_info' => '操作成功']);
+    }
+}

+ 32 - 0
app/Http/Controllers/Admin/Auth/ForgotPasswordController.php

xqd
@@ -0,0 +1,32 @@
+<?php
+
+namespace App\Http\Controllers\Admin\Auth;
+
+use App\Http\Controllers\Admin\Controller;
+use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
+
+class ForgotPasswordController extends Controller
+{
+    /*
+    |--------------------------------------------------------------------------
+    | Password Reset Controller
+    |--------------------------------------------------------------------------
+    |
+    | This controller is responsible for handling password reset emails and
+    | includes a trait which assists in sending these notifications from
+    | your application to your users. Feel free to explore this trait.
+    |
+    */
+
+    use SendsPasswordResetEmails;
+
+    /**
+     * Create a new controller instance.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        $this->middleware('guest');
+    }
+}

+ 101 - 0
app/Http/Controllers/Admin/Auth/LoginController.php

xqd
@@ -0,0 +1,101 @@
+<?php
+
+namespace App\Http\Controllers\Admin\Auth;
+
+use App\Services\Admin\AdminUser;
+use App\Http\Controllers\Admin\Controller;
+use Illuminate\Foundation\Auth\AuthenticatesUsers;
+use Validator, Auth;
+
+class LoginController extends Controller
+{
+    /*
+    |--------------------------------------------------------------------------
+    | Login Controller
+    |--------------------------------------------------------------------------
+    |
+    | This controller handles authenticating users for the application and
+    | redirecting them to your home screen. The controller uses a trait
+    | to conveniently provide its functionality to your applications.
+    |
+    */
+
+    use AuthenticatesUsers;
+
+    /**
+     * Where to redirect users after login.
+     *
+     * @var string
+     */
+    protected $redirectTo = '/admin';
+
+    /**
+     * Create a new controller instance.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        $this->_service = new AdminUser();
+        $this->middleware('guest', ['except' => 'logout']);
+    }
+    /**
+     * 重写登录视图页面
+     * @author 晚黎
+     * @date   2016-09-05T23:06:16+0800
+     * @return [type]                   [description]
+     */
+    public function showLoginForm()
+    {
+        return view('admin.auth.login');
+    }
+    /**
+     * 自定义认证驱动
+     * @author 晚黎
+     * @date   2016-09-05T23:53:07+0800
+     * @return [type]                   [description]
+     */
+    protected function guard()
+    {
+        return auth()->guard('admin');
+    }
+
+    public function username()
+    {
+        return 'name';
+    }
+
+    public function login(\Illuminate\Http\Request $request)
+    {
+
+        $validator = Validator::make($data = $request->all(),
+            [
+                'name' => 'required', 'password' => 'required',
+            ],
+            [
+                'name.required'=>'请输入用户名',
+                'password.required'=>'请输入密码'
+            ]
+        );
+
+        if ($validator->fails()) {
+            $msg = $validator->messages()->first();
+            return $this->showWarning($msg);
+        }
+        $res = $this->_service->login($request->name, $request->password);
+        if($res) {
+            redirect('/admin/login');
+        }else{
+            $msg = $this->_service->getMsg();
+            $this->showWarning($msg);
+        }
+
+        return redirect('/admin');
+    }
+    public function logout()
+    {
+        Auth::guard('admin')->logout();
+        return redirect('/admin/login');
+
+    }
+}

+ 71 - 0
app/Http/Controllers/Admin/Auth/RegisterController.php

xqd
@@ -0,0 +1,71 @@
+<?php
+
+namespace App\Http\Controllers\Admin\Auth;
+
+use App\User;
+use App\Http\Controllers\Admin\Controller;
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Foundation\Auth\RegistersUsers;
+
+class RegisterController extends Controller
+{
+    /*
+    |--------------------------------------------------------------------------
+    | Register Controller
+    |--------------------------------------------------------------------------
+    |
+    | This controller handles the registration of new users as well as their
+    | validation and creation. By default this controller uses a trait to
+    | provide this functionality without requiring any additional code.
+    |
+    */
+
+    use RegistersUsers;
+
+    /**
+     * Where to redirect users after registration.
+     *
+     * @var string
+     */
+    protected $redirectTo = '/home';
+
+    /**
+     * Create a new controller instance.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        $this->middleware('guest');
+    }
+
+    /**
+     * Get a validator for an incoming registration request.
+     *
+     * @param  array  $data
+     * @return \Illuminate\Contracts\Validation\Validator
+     */
+    protected function validator(array $data)
+    {
+        return Validator::make($data, [
+            'name' => 'required|max:255',
+            'email' => 'required|email|max:255|unique:users',
+            'password' => 'required|min:6|confirmed',
+        ]);
+    }
+
+    /**
+     * Create a new user instance after a valid registration.
+     *
+     * @param  array  $data
+     * @return User
+     */
+    protected function create(array $data)
+    {
+        return User::create([
+            'name' => $data['name'],
+            'email' => $data['email'],
+            'password' => bcrypt($data['password']),
+        ]);
+    }
+}

+ 86 - 0
app/Http/Controllers/Admin/Auth/ResetPasswordController.php

xqd
@@ -0,0 +1,86 @@
+<?php
+
+namespace App\Http\Controllers\Admin\Auth;
+
+use App\Http\Controllers\Admin\Controller;
+use Illuminate\Foundation\Auth\ResetsPasswords;
+use Validator, Auth,Hash;
+
+class ResetPasswordController extends Controller
+{
+    /*
+    |--------------------------------------------------------------------------
+    | Password Reset Controller
+    |--------------------------------------------------------------------------
+    |
+    | This controller is responsible for handling password reset requests
+    | and uses a simple trait to include this behavior. You're free to
+    | explore this trait and override any methods you wish to tweak.
+    |
+    */
+
+    use ResetsPasswords;
+
+    /**
+     * Where to redirect users after resetting their password.
+     *
+     * @var string
+     */
+    protected $redirectTo = '/home';
+
+    /**
+     * Create a new controller instance.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        $this->middleware('guest');
+    }
+
+    public function showChangeForm()
+    {
+        return view('admin.auth.change');
+    }
+
+    public function changePassword(\Illuminate\Http\Request $request)
+    {
+
+        $validator = Validator::make($data = $request->all(),
+            [
+                'old_passwprd' => 'required', 'password' => 'required','password_confirmation'=> 'required'
+            ],
+            [
+                'old_passwprd.required'=>'请输入原密码',
+                'password.required'=>'请输入密码',
+                'password_confirmation.required'=>'请输入确认密码',
+            ]
+        );
+        if ($validator->fails()) {
+            $msg = $validator->messages()->first();
+            return $this->showWarning($msg);
+        }
+
+        $user = Auth::guard('admin')->user();
+        $oldpassword = $request->input('old_passwprd');
+        $newpassword = $request->input('password');
+        $password_confirmation= $request->input('password_confirmation');
+
+        if($newpassword!=$password_confirmation){
+            return $this->showWarning("两次密码一直");
+        }
+
+        if(!Hash::check($oldpassword, $user->password)){
+            return $this->showWarning("原密码不正确");
+        }
+
+        $user->password = bcrypt($newpassword);
+        $result = $user->save();
+
+        if($result){
+            return $this->showMessage("修改成功");
+        }else{
+            return $this->showWarning("修改密码失败");
+        }
+    }
+}

+ 69 - 0
app/Http/Controllers/Admin/Base/ActionlogController.php

xqd
@@ -0,0 +1,69 @@
+<?php
+/**
+ * 操作日志
+ *  @author  Mike <m@9026.com>
+ *  @version    1.0
+ *  @date 2015年10月15日
+ *
+ */
+namespace App\Http\Controllers\Admin\Base;
+
+use App\Http\Controllers\Admin\Controller;
+use Request;
+use App\Services\User\Payinfo;
+use App\Utils\AliLog;
+use Carbon\Carbon;
+
+class ActionlogController extends Controller {
+    private $_service;
+    private $_viewdata;
+    private $_aTopic = [ 'action-view-log'=>'访问日志','action-operate-log'=>'操作日志'];
+    /**
+     * 初始化Service
+     */
+    public function __construct()
+    {
+        parent::__construct();
+    
+        if(!$this->_service) $this->_service = new Payinfo();
+        
+        $this->_viewdata = array();
+    }
+    
+    /**
+     * 列表
+     */
+    function index()
+    {
+        $obj = new AliLog();
+        $this->_viewdata['aTopIc'] = $this->_aTopic;
+        $this->_viewdata['topic'] = Request::input('topic','action-view-log');
+        $this->_viewdata['aLine'] = [50=>'50行',100=>'100行',200=>'200行'];
+        $this->_viewdata['line']  = Request::input('line',50);
+        $this->_viewdata['start_time']  = Request::input('start_time',Carbon::yesterday());
+        $this->_viewdata['end_time']  = Request::input('end_time',Carbon::tomorrow());
+        $query = '';
+        $data = $obj->listLogs('admin-operate-log',
+                                strtotime($this->_viewdata['start_time']),
+                                strtotime($this->_viewdata['end_time']), 
+                                $this->_viewdata['topic'],
+                                $query,
+                                $this->_viewdata['line']
+                );
+        $request = Request::all();
+        $search['keyword'] = Request::input('keyword');
+        
+        $orderby = array();
+        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
+            $orderby[$request['sort_field']] = $request['sort_field_by'];
+        }
+        $this->_viewdata['data'] = $data;
+    
+        return view('admin.base.actionlog.index', $this->_viewdata);
+    }
+    
+    
+    
+    
+    
+}

+ 192 - 0
app/Http/Controllers/Admin/Base/AttachmentController.php

xqd
@@ -0,0 +1,192 @@
+<?php
+
+namespace App\Http\Controllers\Admin\Base;
+
+use App\Http\Controllers\Admin\Controller;
+use App\Services\Base\Attachment;
+use App\Models\BaseAttachmentModel;
+use Request, Response;
+
+class AttachmentController extends Controller
+{
+    private $_serviceAttachment;
+    private $_serviceAttachmentBbs;
+    private $_serviceForumAttachment;
+    private $_serviceForumAttachmentUnused;
+
+    public function __construct()
+    {
+        if( !$this->_serviceAttachment ) $this->_serviceAttachment = new Attachment();
+
+    }
+
+
+    /**
+     * SWFUpload文件上传
+     */
+    public function upload()
+    {
+        $request = Request::all();
+
+        //通过上传控件ID,区分文件上传类型
+        if(isset($request['elementid']) && substr($request['elementid'], 0, 15) == 'upload_template'){
+
+            $this->_uploadTemplate($request);
+
+            //上传到阿里云
+        }elseif(isset($request['position']) && $request['position'] == 'alioss'){
+
+            $this->_uploadToAlioss($request);
+
+            //上传专题文件
+        }
+        elseif(isset($request['position']) && $request['position'] == 'special'){
+
+            $this->_uploadSpecial($request);
+
+            //上传到本地
+        } else{
+
+            $this->webupload($request);
+        }
+    }
+
+
+    /**
+     * 上传到本地
+     */
+    private function _uploadToServer($request)
+    {
+        $return = $this->_serviceAttachment->localUpload('imgFile', $request);
+        if($return['code']=='200'){
+            echo json_encode(["error"=> 0,"url" => config('app.url').$return['fileurl']]);exit;
+        }else{
+
+            echo json_encode(["error" => 1,"message" =>  $return['message']]);exit;
+        }
+    }
+
+    /***
+     * 文件上传
+     */
+    public function fileupload(){
+        $request = request()->all();
+        $data = $this->_serviceAttachment->fileUpload('file', $request, 'files');
+//        return response()->json(array('data' => $data), 200);
+        echo json_encode($data);exit;
+    }
+
+    /**
+     * 上传专题文件
+     */
+    private function _uploadSpecial($request)
+    {
+        $return = $this->_serviceAttachment->specialUpload('Filedata', $request);
+        echo json_encode($return);exit;
+    }
+
+    /**
+     * 上传到阿里云
+     */
+    private function _uploadToAlioss($request)
+    {
+        $return = [];
+        if(isset($request['editor'])){
+            $data = $this->_serviceAttachment->aliUpload('upfile', $request);
+            if($data['code'] === 200){
+                \Log::info(json_encode($data));
+                $return['state'] = 'SUCCESS';
+                $return['url']   = $data['fileurl'];
+                $return['title']   = $data['name'];
+            }else{
+                $return['error']    = 1;
+                $return['message']  = $data['message'];
+            }
+        }else{
+            $return = $this->_serviceAttachment->aliUpload('file', $request,'files');
+        }
+        echo json_encode($return);exit;
+    }
+
+    /**
+     * 控件上传
+     */
+    public function webupload($request)
+    {
+        $return = [];
+        if(isset($request['editor'])){
+            $data = $this->_serviceAttachment->localUpload('upfile', $request, 'files');
+            if($data['code'] === 200){
+                \Log::info(json_encode($data));
+                $return['state'] = 'SUCCESS';
+                $return['url']   = $data['fileurl'];
+                $return['title']   = $data['name'];
+            }else{
+                $return['error']    = 1;
+                $return['message']  = $data['message'];
+            }
+        }else{
+            $return = $this->_serviceAttachment->localUpload('file', $request, 'files');
+        }
+        echo json_encode($return);exit;
+    }
+
+
+    /**
+     * @api {get} /api/attachment/download/{md5} 下载文件(图片)
+     * @apiDescription 下载文件(图片)(get code)
+     * @apiGroup Attachment
+     * @apiPermission none
+     * @apiVersion 0.1.0
+     * @apiParam {string} md5   图片md5码
+     * @apiSuccessExample {json} Success-Response:
+     *     HTTP/1.1 200 OK
+     *     {
+     *       文件二进制码
+     *     }
+     * @apiErrorExample {json} Error-Response:
+     *     HTTP/1.1 404 Not found
+     */
+    public function download()
+    {
+        $request = Request::all();
+        $attachment = BaseAttachmentModel::where(['md5' => $request['md5']])->first();
+        if (!$attachment) {
+            return view('errors.404');
+        }
+
+        return Response::download($attachment->path, $attachment->name, [
+            'Content-type'  => $attachment->file_type,
+            'Accept-Ranges' => 'bytes',
+            'Accept-Length' => $attachment->size,
+        ]);
+    }
+
+
+
+
+    private function _createAttachmentRecord($data)
+    {
+        $uid = Request::input('uid');
+        $aid = $this->_serviceForumAttachment->create(['tid' => 0, 'pid' => 0, 'uid' => $uid, 'tableid' => 127]);
+        if($aid){
+            $info = [
+                'aid'           => $aid,
+                'uid'           => $uid,
+                'dateline'      => SYSTEM_TIME,
+                'filename'      => $data['filename'],
+                'filesize'      => $data['filesize'],
+                'attachment'    => $data['attachment'],
+                'isimage'       => (isset($data['width']) && $data['width']) ? 1 : 0,
+                'remote'        => 1,
+                'width'         => isset($data['width']) ? $data['width'] : 0,
+                'thumb'         => 0,
+            ];
+            if(!$this->_serviceForumAttachmentUnused->create($info)){
+                return 0;
+            }
+        }
+        return $aid;
+    }
+
+}

+ 58 - 0
app/Http/Controllers/Admin/Base/ClassController.php

xqd
@@ -0,0 +1,58 @@
+<?php
+
+namespace App\Http\Controllers\Admin\Base;
+
+use Illuminate\Http\Request as HttpRequest;
+use App\Http\Controllers\Admin\Controller;
+use App\Models\ClassModel;
+use App\Models\BaseAttachmentModel;
+use Request, Response, Validator, File;
+
+class ClassController extends Controller
+{
+    public function add(HttpRequest $request)
+    {
+    	if(! $request->has('class') || Request::method() != 'POST') {
+    		return back();
+    	}
+
+    	$validator = Validator::make($request->all(), [
+            'class' => 'required|string|max:100|unique:classes,class',
+        ]);
+    	if($validator->fails()) {
+    		$validator->errors()->add('my-error', '分类已存在!');
+    		return back()->withErrors($validator)->withInput();
+    	}
+    	
+    	$class = new ClassModel;
+    	$class->class = $request->input('class');
+    	if(! $class->save()) {
+    		$validator->errors()->add('my-error', '添加分类失败!');
+    		return back()->withErrors($validator)->withInput();
+    	}
+
+    	return back();
+    }
+
+    public function delete(HttpRequest $request)
+    {
+        if(Request::method() != 'POST') {
+            return back();
+        }
+
+        $class = null;
+        if($request->has('class') && ($class = ClassModel::find($request->input('class'))) != null) {
+            if($class->class == '未分类') {
+                return back();
+            }
+
+            $photos = BaseAttachmentModel::where('class', $class->class)->get();
+            foreach($photos as $photo) {
+                File::delete($photo->path);
+                $photo->delete();
+            }
+            $class->delete();
+        }
+        return redirect('admin/Base/Photos/index');
+    }
+}

+ 97 - 0
app/Http/Controllers/Admin/Base/CrudController.php

xqd
@@ -0,0 +1,97 @@
+<?php
+/**
+ * 创建增删改查
+ * User: Mike
+ * Email: m@9026.com
+ * Date: 2016/6/4
+ * Time: 17:14
+ */
+
+namespace App\Http\Controllers\Admin\Base;
+
+use App\Http\Controllers\Admin\Controller;
+use App\Services\CRUD\CRUD;
+use Illuminate\Support\Facades\DB;
+use App\Services\Admin\Menus;
+use Request;
+
+
+class CrudController extends Controller
+{
+    function create() {
+        if(Request::method() == 'POST') {
+            return $this->_createSave();
+        }
+        $schema = env("DB_DATABASE");
+
+        $tables = DB::select("SELECT TABLE_NAME,TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA='$schema'");
+
+        $MenusTrees = (new Menus())->getMenusTree();
+        return view('admin.base.crud.create',compact('tables','MenusTrees'));
+    }
+    private function _createSave() {
+        $data = Request::all();
+        $obj = new CRUD();
+        $ok = $obj->create($data);
+        if($ok) {
+            $this->showMessage("操作成功");
+        }else{
+            $this->showWarning("操作失败:" . $obj->getMessage());
+        }
+    }
+
+
+
+    public function getTable(){
+        $table = request()->get('table');
+        $schema = env("DB_DATABASE");
+        $data = DB::select("SELECT COLUMN_NAME,COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='{$schema}' AND TABLE_NAME='{$table}';");
+    }
+
+    public function checkModelPath($modelPath = null) {
+        if(!$modelPath) {
+            $modelPath = request()->get('path');
+        }
+        $modelPath = app_path() . "/Models/" . $modelPath . ".php";
+        if(file_exists($modelPath)) {
+            return json_encode(['status'=>FAILURE_CODE,'msg'=>'注意!!Model文件已存在,系统重复不会创建!!!']);
+        }else{
+            return json_encode(['status'=>SUCESS_CODE]);
+        }
+    }
+
+    public function checkServicePath($modelPath = null) {
+        if(!$modelPath) {
+            $modelPath = request()->get('path');
+        }
+        $modelPath = app_path() . "/Repositories/" . $modelPath . ".php";
+        if(file_exists($modelPath)) {
+            return json_encode(['status'=>FAILURE_CODE,'msg'=>'注意!!Service文件已存在,系统重复不会创建!!!']);
+        }else{
+            return json_encode(['status'=>SUCESS_CODE]);
+        }
+    }
+
+    public function checkControllerPath($modelPath = null) {
+        if(!$modelPath) {
+            $modelPath = request()->get('path');
+        }
+        $modelPath = app_path() . "/Http/Controllers/Admin/" . $modelPath . ".php";
+        if(file_exists($modelPath)) {
+            return json_encode(['status'=>FAILURE_CODE,'msg'=>'注意!!Controller文件已存在,系统重复不会创建!!!']);
+        }else{
+            return json_encode(['status'=>SUCESS_CODE]);
+        }
+    }
+    public function checkPath($modelPath = null) {
+        if(!$modelPath) {
+            $modelPath = request()->get('path');
+        }
+        $modelPath = app_path() . "/Http/Controllers/Admin/" . $modelPath . ".php";
+        if(file_exists($modelPath)) {
+            return json_encode(['status'=>FAILURE_CODE,'msg'=>'注意!!Controller文件已存在,系统重复不会创建!!!']);
+        }else{
+            return json_encode(['status'=>SUCESS_CODE]);
+        }
+    }
+}

+ 138 - 0
app/Http/Controllers/Admin/Base/DictionaryController.php

xqd
@@ -0,0 +1,138 @@
+<?php
+/**
+ *  字典管理
+ *  @author  system
+ *  @version    1.0
+ *  @date 2018-06-12 10:14:19
+ *
+ */
+namespace App\Http\Controllers\Admin\Base;
+use App\Http\Controllers\Admin\Controller;
+use Illuminate\Http\Request;
+use App\Repositories\Base\Criteria\OrderBy;
+use App\Repositories\Base\Criteria\MultiWhere;
+use App\Repositories\Base\DictionaryRepository;
+
+class DictionaryController extends Controller
+{
+    private $repository;
+
+    public function __construct(DictionaryRepository $repository) {
+        if(!$this->repository) $this->repository = $repository;
+    }
+
+    function index(Request $request) {
+        $search['keyword'] = $request->input('keyword');
+        $query = $this->repository->pushCriteria(new MultiWhere($search));
+
+        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
+        $query = $query->pushCriteria(new OrderBy($request['sort_field'],$request['sort_field_by']));
+        }else{
+            $query = $query->pushCriteria(new OrderBy('id','DESC'));
+        }
+        $list = $query->paginate();
+        return view('admin.base.dictionary.index',compact('list'));
+    }
+
+
+    function check(Request $request) {
+        $request = $request->all();
+        $search['keyword'] = $request->input('keyword');
+        $orderby = array();
+        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
+            $orderby[$request['sort_field']] = $request['sort_field_by'];
+        }
+        $list = $this->repository->search($search,$orderby);
+        return view('admin.base.dictionary.check',compact('list'));
+    }
+
+
+    /**
+     * 添加
+     * 
+     */
+    public function create(Request $request)
+    {
+        if($request->method() == 'POST') {
+            return $this->_createSave();
+        }
+        return view('admin.base.dictionary.edit');
+    }
+
+    /**
+     * 保存修改
+     */
+    private function _createSave(){
+        $data = (array) request('data');
+        $id = $this->repository->create($data);
+        if($id) {
+            $url[] = array('url'=>U( 'Base/Dictionary/index'),'title'=>'返回列表');
+            $url[] = array('url'=>U( 'Base/Dictionary/create'),'title'=>'继续添加');
+            $this->showMessage('添加成功',$url);
+        }else{
+            $url[] = array('url'=>U( 'Base/Dictionary/index'),'title'=>'返回列表');
+            return $this->showWarning('添加失败',$url);
+        }
+    }
+    
+    /**
+     * 
+     * 修改
+     * 
+     * 
+     */
+    public function update(Request $request) {
+        if($request->method() == 'POST') {
+            return $this->_updateSave();
+        }
+        $data = $this->repository->find($request->get('id'));
+        return view('admin.base.dictionary.edit',compact('data'));
+    }
+
+    /**
+     * 保存修改
+     */
+    private function _updateSave() {
+        $data = (array) request('data');
+        $ok = $this->repository->update(request('id'),$data);
+        if($ok) {
+            $url[] = array('url'=>U( 'Base/Dictionary/index'),'title'=>'返回列表');
+            return $this->showMessage('操作成功',urldecode(request('_referer')));
+        }else{
+            $url[] = array('url'=>U( 'Base/Dictionary/index'),'title'=>'返回列表');
+            return $this->showWarning('操作失败',$url);
+        }
+    }
+
+    public function view(Request $request) {
+        $data = $this->repository->find(request('id'));
+        return view('admin.base.dictionary.view',compact('data'));
+    }
+
+
+    /**
+     *
+     * 状态改变
+     *
+     */
+    public function status(Request $request) {
+        $ok = $this->repository->updateStatus(request('id'),request('status'));
+        if($ok) {
+            return $this->showMessage('操作成功');
+        }else{
+            return $this->showWarning('操作失败');
+        }
+    }
+    
+    /**
+     * 删除
+     */
+    public function destroy(Request $request) {
+        $bool = $this->repository->destroy($request->get('id'));
+        if($bool) {
+            return  $this->showMessage('操作成功');
+        }else{
+            return  $this->showWarning("操作失败");
+        }
+    }
+}

+ 66 - 0
app/Http/Controllers/Admin/Base/IndexController.php

xqd
@@ -0,0 +1,66 @@
+<?php
+/**
+ *  
+ *  @author  Mike <m@9026.com>
+ *  @version    1.0
+ *  @date 2015年10月12日
+ *
+ */
+namespace App\Http\Controllers\Admin\Base;
+
+use App\Http\Controllers\Admin\Controller;
+use App\Services\Base\Tree;
+use App\Services\Base\BaseArea;
+use App\Services\Admin\Menus;
+use App\Services\Admin\Acl;
+
+class IndexController extends Controller
+{
+    public function __construct()
+    {
+        parent::__construct();
+    }
+
+    function index() {
+        if($this->_user['is_root']) {
+            $obj = new Menus();
+            $menus = $obj->search(array('level'=>2,'display'=>1),$orderby=array('sort'=>'desc'),$pagesize = 100000);
+            $menus = $menus->toArray();
+            $menus = list_to_tree($menus['data']);
+        }else{
+            $obj = new Acl();
+            $data = $obj->getRoleMenu($this->_user['admin_role_id']);
+            $menus = list_to_tree($data);
+        }
+        return view('admin.base.index.index',compact('menus'));
+    }
+    function welcome() {
+        return view('admin.base.index.welcome');
+    }
+    
+    function createAreaDate(){
+        //Base-index-createareadate.do
+        header("Content-type:text/html;charset=utf-8");
+        $areaObj = new BaseArea();
+        $data = $areaObj->getLevel();
+
+        $treeObj = new Tree();
+        $treeObj -> init($data);
+        $info = $treeObj -> getTree();
+        $output = array();
+        
+        foreach($info AS $key => $val){
+            if($val['id'] == '100000') continue;
+            $val['level'] = $val['level'] - 1;
+            unset($val['grade'], $val['spacer']);
+            $output[]= $val;
+        }
+        
+        $str = json_encode($output);
+        
+        $area_path = public_path() . '/base/js/areadata.js';
+        file_put_contents($area_path, $str);
+        
+        echo $str;exit;
+    }
+}

+ 41 - 0
app/Http/Controllers/Admin/Base/LogsController.php

xqd
@@ -0,0 +1,41 @@
+<?php
+/**
+ *  
+ *  @author  Mike <m@9026.com>
+ *  @version    1.0
+ *  @date 2015年10月30日
+ *
+ */
+namespace App\Http\Controllers\Admin\Base;
+use App\Http\Controllers\Admin\Controller;
+use App\Services\Base\Attachment;
+
+class LogsController extends Controller
+{
+   
+    //系统日志
+    public function nginx() {
+        $log_path = storage_path() . '/logs/' . "error-log" . date("Y-m-d") . ".log";
+        if(file_exists($log_path)) {
+            echo "<pre>" . file_get_contents($log_path) . "</pre>";
+        }else{
+            exit("没有错误日志");
+        }
+        
+    }
+    /**
+     * 初始化文件上传组件
+     */
+    private function _uploadControl($folder, $position = 'ali')
+    {
+        //初始化文件上传组件
+        $attachmentObj = new Attachment();
+        return $attachmentObj -> initupload([
+                'file_types' => 'jpg|jpeg|gif|png|bmp',
+        ], [
+                'position'   => $position,
+                'folder'     => $folder,
+        ]);
+    }
+    
+} 

+ 120 - 0
app/Http/Controllers/Admin/Base/MenusController.php

xqd
@@ -0,0 +1,120 @@
+<?php
+/**
+ *  文章
+ *  @author  Mike <m@9026.com>
+ *  @version    1.0
+ *  @date 2015年10月15日
+ *
+ */
+namespace App\Http\Controllers\Admin\Base;
+use App\Http\Controllers\Admin\Controller;
+use App\Services\Admin\Menus;
+use Request;
+
+class MenusController extends Controller
+{
+
+    private $_service;
+
+    public function __construct ()
+    {
+        if (!$this->_service) $this->_service = new Menus();
+    }
+
+    function index ()
+    {
+        $search['keyword'] = Request::input('keyword');
+        $list = $this->_service->getMenusTree($search);
+        return view('admin.base.menus.index', compact('list'));
+    }
+
+    public function _showEdit ()
+    {
+        $MenusTrees = $this->_service->getMenusTree();
+        view()->share("MenusTrees", $MenusTrees);
+    }
+
+    /**
+     * 添加
+     */
+    public function create ()
+    {
+        if (Request::method() == 'POST') {
+            return $this->_createSave();
+        }
+        $this->_showEdit();
+        return view('admin.base.menus.edit');
+    }
+
+    private function _createSave ()
+    {
+        $id = $this->_service->create(Request::input('data'));
+        if (isset($id->id)) {
+            //更新菜单层级关系
+            $level = $this->_service->getLevel($id->id);
+            $this->_service->update($id->id, ['level' => $level]);
+            
+            $url[] = array(
+                    'url' => U( 'Base/Menus/index'),
+                    'title' => '返回列表'
+            );
+            $url[] = array(
+                    'url' => U( 'Base/Menus/create'),
+                    'title' => '继续添加'
+            );
+            $this->showMessage('添加成功', $url);
+        } else {
+            $url[] = array(
+                    'url' => U( 'Base/Menus/index'),
+                    'title' => '返回列表'
+            );
+            $this->showWarning('添加失败', $url);
+        }
+    }
+
+    /**
+     * 修改
+     */
+    public function update ()
+    {
+        if (Request::method() == 'POST') {
+            return $this->_updateSave();
+        }
+        $this->_showEdit();
+        $data = $this->_service->find(Request::input('id'));
+        return view('admin.base.menus.edit', compact('data'));
+    }
+
+    private function _updateSave ()
+    {
+        $data = Request::input('data');
+        $data['level'] = $this->_service->getLevel(Request::input('id'));
+        $ok = $this->_service->update(Request::input('id'), $data);
+        if ($ok) {
+            $url[] = array(
+                    'url' => U( 'Base/Menus/index'),
+                    'title' => '返回列表'
+            );
+            $this->showMessage('操作成功', urldecode(Request::input('_referer')));
+        } else {
+            $url[] = array(
+                    'url' => U( 'Base/Menus/index'),
+                    'title' => '返回列表'
+            );
+            $this->showWarning('操作失败', $url);
+        }
+    }
+
+    /**
+     * 删除
+     */
+    public function destroy ()
+    {
+        $bool = $this->_service->destroy(Request::input('id'));
+        if ($bool) {
+            $this->showMessage('操作成功');
+        } else {
+            $this->showWarning("操作失败");
+        }
+    }
+}

+ 123 - 0
app/Http/Controllers/Admin/Base/PhotosController.php

xqd
@@ -0,0 +1,123 @@
+<?php
+
+namespace App\Http\Controllers\Admin\Base;
+
+use App\Http\Controllers\Admin\Controller;
+use App\Services\Base\Attachment;
+use App\Models\BaseAttachmentModel;
+use App\Models\ClassModel;
+use App\Services\OSS;
+use Illuminate\Http\Request as HttpRequest;
+use Request;
+use File;
+
+class PhotosController extends Controller
+{
+    private $_serviceAttachment;
+
+    public function __construct()
+    {
+        if( !$this->_serviceAttachment ) $this->_serviceAttachment = new Attachment();
+    }
+
+    public function index(HttpRequest $request)
+    {
+        $classes = ClassModel::all();
+        $a_class = $request->has('class') ? $request->input('class') : null;
+
+        if(($a_class = ClassModel::find($a_class)) == null) {
+            $a_class = ClassModel::first();
+        }
+        $photos = null;
+        $status = 'normal';
+        if($request->has('search')){
+            $currentQuery = new BaseAttachmentModel();
+            if ($request->has('search') && !empty($request->has('search'))) {
+                $name = '%' . $request->input('search') . '%';
+                $currentQuery = $currentQuery->where(function ($query) use ($name) {
+                    $query->where('name', 'like', $name);
+                });
+            }
+
+            if($request->has('start') && !empty($request->get('start')))
+            {
+                $start = $request->get('start');
+                $currentQuery = $currentQuery->where(function ($query) use ($start) {
+                    $query->where('created_at', '>=', $start);
+                });
+            }
+            if($request->has('end') && !empty($request->get('end')))
+            {
+                $end = $request->get('end');
+                $currentQuery = $currentQuery->where(function ($query) use ($end) {
+                    $query->where('created_at', '<=', $end);
+                });
+            }
+
+            $photos = $currentQuery->paginate(24);
+        } else{
+            $photos = BaseAttachmentModel::where('class',$a_class->class)->paginate(24);
+        }
+    	return view('admin.base.photos.index', compact('photos', 'classes', 'a_class', 'status', 'photo_compress_quality'));
+    }
+
+    public function edit(HttpRequest $request)
+    {
+        if(Request::method() != 'POST') {
+            return back();
+        }
+
+        if($request->has('img-name') && $request->has('img-id')) {
+            $photo = BaseAttachmentModel::find($request->input('img-id'));
+            $photo->name = $request->input('img-name');
+            $photo->save();
+        }
+
+        return back();
+    }
+
+    public function move(HttpRequest $request)
+    {
+        if(Request::method() != 'POST') {
+            return back();
+        }
+
+        $ids = explode(',', $request->input('ids'));
+        $class = ClassModel::find($request->input('class'));
+        BaseAttachmentModel::whereIn('id', $ids)->update(['class' => $class->class]);
+        return back();
+    }
+
+    public function delete(HttpRequest $request)
+    {
+        if(Request::method() != 'POST') {
+            return back();
+        }
+
+        $ids = explode(',', $request->input('ids'));
+        $photos = BaseAttachmentModel::find($ids);
+        foreach($photos as $photo) {
+            if($photo->path == $photo->url){
+                $key = explode('/',$photo->path);
+                OSS::publicDeleteObject(config('alioss.BucketName'),end($key));
+            }else{
+                File::delete($photo->path);
+            }
+            $photo->delete();
+
+        }
+        return back();
+    }
+
+    public function crop(HttpRequest $request)
+    {
+        if(Request::method() != 'POST') {
+            return back();
+        }
+
+        $this->_serviceAttachment->localUpload('file', $request->all());
+
+        return response()->json(['status' => 'ok'], 200);
+    }
+
+}

+ 185 - 0
app/Http/Controllers/Admin/Base/RoleController.php

xqd
@@ -0,0 +1,185 @@
+<?php
+
+namespace App\Http\Controllers\Admin\Base;
+
+use App\Http\Controllers\Admin\Controller;
+use App\Services\Admin\Role;
+use Request;
+use App\Services\Admin\Acl;
+
+class RoleController extends Controller
+{
+    private $level;
+    private $_service;
+    private $_serviceDepartments;
+
+    /**
+     * 初始化Service
+     */
+    public function __construct()
+    {
+        parent::__construct();
+        
+        if(!$this->_service) $this->_service = new Role();
+        $this->level = isset($this->_getRoleNode()->level)?$this->_getRoleNode()->level:'';
+    }
+    
+    /**
+     * 列表
+     */
+    function index()
+    {
+        if($this->_user['is_root']){
+            $search['level'] = 0;
+        }else{
+            $search['level'] = $this->level;
+        }
+        
+        $request = Request::all();
+        $search['keyword'] = Request::input('keyword');
+        
+        $orderby = array();
+        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
+            $orderby[$request['sort_field']] = $request['sort_field_by'];
+        }
+        $list = $this->_service->search($search, $orderby);
+
+        return view('admin.base.role.index', compact('list'));
+    }
+
+    /**
+     * 创建
+     */
+    public function create()
+    {
+        if(Request::method() == 'POST'){
+            if(intval(Request::input('info.level')) < $this->level){
+                $this->showWarning('你无权创建该等级的角色!', urldecode(Request::input('_referer')));
+            }
+            if($this->_service->create(Request::input('info'))){
+                $this->showMessage('操作成功', U( 'Base/Role/index'));
+            }else{
+                $this->showMessage('操作失败', U( 'Base/Role/index'));
+            }
+        }
+        $level = $this->level;
+        return view('admin.base.role.edit', compact('level', 'Departments'));
+    }
+
+    /**
+     * 更新
+     */
+    public function update()
+    {
+        if(Request::method() == 'POST'){
+            if(intval(Request::input('info.level')) < $this->level){
+                $this->showWarning('你无权创建该等级的角色!', urldecode(Request::input('_referer')));
+            }
+            if($this->_service->update(Request::input('id'), Request::input('info'))){
+                $this->showMessage('操作成功', urldecode(Request::input('_referer')));
+            }else{
+                $this->showWarning('操作失败', urldecode(Request::input('_referer')));
+            }
+        }
+        $data = $this->_service->find(Request::input('id'));
+        $level = $this->level;
+        return view('admin.base.role.edit', compact('data', 'level', 'Departments'));
+    }
+    
+    /**
+     * 更新
+     */
+    public function auth()
+    {
+        $id = Request::input('id');
+        
+        $objAcl = new Acl();
+        
+        
+        if(Request::method() == 'POST'){
+           $menuIds = Request::input('menu_ids');
+           if($this->_user['is_root']) {
+               $allMenus = false;
+           }else{
+               $allMenus = array();
+               foreach ($this->_user['menus'] as $value) {
+                   $allMenus[] = $value['id'];
+               }
+           }
+           $ok = $objAcl->setRole($id, $menuIds,$allMenus);
+           if($ok) {
+               $arr['status'] = SUCESS_CODE;
+               
+           }else{
+               $arr['status'] = SERVER_ERROR;
+           }
+           exit(json_encode($arr));
+        }
+        
+        $hasPermissions = $objAcl->getAccessIDs($id);
+        
+        $role =  session(LOGIN_MARK_SESSION_KEY);
+        //为ztree做数据准备
+        $zTree = []; $all = [];
+        foreach($role['menus'] as $key => $value)
+        {
+            $arr = ['id' => $value['id'], 'pId' => $value['pid'], 
+                    'name' => $value['name'] . " (" . $value['path'] . ")",
+                    'open' => true];
+            if(in_array($value['id'], $hasPermissions)) $arr['checked'] = true;
+            $zTree[] = $arr;
+            $all[] = $value['id'];
+        }
+        $data = $this->_service->find($id);
+        return view('admin.base.role.auth', compact('data','zTree','all'));
+    }
+  
+    /**
+     * 更新状态
+     */
+    public function status()
+    {
+        $bool = $this->_service->updateStatus(Request::input('id'), Request::input('status'));
+        if($bool) {
+            $this->showMessage('操作成功');
+        }else{
+            $this->showWarning('操作失败');
+        }
+    }
+    
+    /**
+     * 删除
+     */
+    public function destroy()
+    {
+        $bool = $this->_service->destroy(Request::input('id'));
+        if($bool) {
+            $this->showMessage('操作成功');
+        }else{
+            $this->showWarning("操作失败");
+        }
+    }
+    
+    /**
+     * 获取角色权限节点(level越小权限越大)
+     */
+    private function _getRoleNode()
+    {
+        return $this->_service->getLevelNode($this->_user['admin_role_id']);
+    }
+
+
+    /**
+     * 获取树形结构
+     */
+    private function _getTreeByDepartmentId()
+    {
+        if($this->_user['is_root']){
+            $department_id = 0;
+        }else{
+            $department_id = intval($this->_user['department_id']);
+        }
+        return $this->_serviceDepartments->getTreeByDepartmentId($department_id);
+    }
+    
+}

+ 41 - 0
app/Http/Controllers/Admin/Base/SystemController.php

xqd
@@ -0,0 +1,41 @@
+<?php
+/**
+ *  
+ *  @author  Mike <m@9026.com>
+ *  @version    1.0
+ *  @date 2015年10月30日
+ *
+ */
+namespace App\Http\Controllers\Admin\Base;
+
+use App\Http\Controllers\Admin\Controller;
+use App\Services\Base\Attachment;
+use App\Services\Base\System;
+use Request;
+
+class SystemController extends Controller
+{
+   
+    //系统日志
+    public function config() {
+        if(Request::method() == 'POST') {
+            return $this->_counfigSave();
+        }
+        $obj = new System();
+        $data = $obj->getCoufig();
+        return view('admin.base.system.config', compact('data'));
+
+    }
+
+    private function _counfigSave() {
+        $data = (array) Request::input('data');
+        $obj = new System();
+        $ok = $obj->saveConfig($data);
+        if($ok) {
+            $this->showMessage('操作成功');
+        }else{
+            $this->showWarning('操作失败');
+        }
+    }
+
+} 

+ 123 - 0
app/Http/Controllers/Admin/Base/ToolController.php

xqd
@@ -0,0 +1,123 @@
+<?php
+/**
+ *  
+ *  @author  Mike <m@9026.com>
+ *  @version    1.0
+ *  @date 2015年10月30日
+ *
+ */
+namespace App\Http\Controllers\Admin\Base;
+
+use App\Http\Controllers\Admin\Controller;
+use App\Services\Base\Attachment;
+use Request;
+//use App\Utils\OSS\Alioss;
+//use App\Utils\DirUtil;
+
+class ToolController extends Controller
+{
+    private $_dirUtil;
+    private $_aliossService;
+    
+    public function __construct() {
+        if( !$this->_dirUtil ) $this->_dirUtil = new DirUtil();
+        if( !$this->_aliossService ) $this->_aliossService = new Alioss();
+    }
+    
+    /**
+     * 专题上传
+     */
+    function specialupload() {
+        $attachmentObj = new Attachment();
+        $uploadControl = $attachmentObj -> initupload([
+            'file_types' => 'php|htm|html',
+        ], [
+            'position'   => 'special',
+            'folder'     => 'at',
+        ]);
+        
+        //遍历专题目录
+        $data = array();
+        $dirList = $this->_dirUtil->dirTraverse(public_path('resources/views/web/special'));
+        if(!empty($dirList)){
+            foreach ($dirList AS $key => $val){
+                $data[$key]['name'] = trim(iconv("GBK", "UTF-8//IGNORE", substr(strrchr($val, '/'), 1, 50))) . '.html';
+                $data[$key]['url'] = 'http://' . config('sys.sys_www_domain') . '/at/' . $data[$key]['name'];
+            }
+        }
+        view()->share("uploadControl", $uploadControl);
+        return view('admin.base.tool.specialupload', compact('data'));
+    }
+    
+    /**
+     * 阿里云上传
+     */
+    function alimanage()
+    {
+        
+        $ok = $this->_aliossService->doesObjectExist("a/bg.jpg");
+        
+        $img_path = config('sys.sys_images_url');
+        $file_path = config('sys.sys_file_url');
+        $folder = trim(Request::input('folder'));
+        $dirname = trim(Request::input('dirname'));
+
+        //创建目录
+        if(Request::method() == 'POST'){
+            if($dirname){
+                $this->_createDir($dirname,  $folder);
+            }else{
+                $this->showWarning('目录名不能为空!');
+            }
+        }
+        
+        //构建路径
+        $folderPath = '/<a href="' . U( 'Base/Tool/alimanage') . '?folder=">根目录</a>/';
+        if($folder){
+            $dirPath = '';
+            $dirs = array_filter(explode('/', $folder));
+            foreach ($dirs AS $dir){
+                $dirPath .= $dir . '/';
+                $folderPath .= '<a href="' . U( 'Base/Tool/alimanage') . '?folder=' . $dirPath . '">'. $dir .'</a>/';
+            }
+        }
+        $itemObj = $this->_aliossService->listObjects(['prefix'=>$folder]);
+        $item['obj'] = $itemObj->getObjectList(); // 文件列表
+        $item['dir'] = $itemObj->getPrefixList(); // 目录列表
+       
+        $uploadControl = $this->_uploadControl('');
+        
+        return view('admin.base.tool.alimanage', compact('item', 'img_path', 'file_path', 'folderPath', 'uploadControl'));
+    }
+    
+    private function _createDir($dirname, $folder)
+    {
+        if(strpos($dirname, '/') === false && preg_match('/^([0-9a-zA-Z\_]+)$/is', $dirname)){
+            $newdir = $folder . $dirname;
+            $code = $this->_aliossService->createObjectDir($newdir);
+            if($code == null){
+                $this->showMessage('目录创建成功!', U( 'Base/Tool/alimanage') . '?folder=' . $newdir . '/');
+            }else{
+                $this->showWarning('目录创建失败!');
+            }
+        }else{
+            $this->showWarning('非法的目录名!');
+        }
+    }
+    
+    /**
+     * 初始化文件上传组件
+     */
+    private function _uploadControl($folder, $position = 'ali')
+    {
+        //初始化文件上传组件
+        $attachmentObj = new Attachment();
+        return $attachmentObj -> initupload([
+                'file_types' => 'jpg|jpeg|gif|png|bmp',
+        ], [
+                'position'   => $position,
+                'folder'     => $folder,
+        ]);
+    }
+    
+} 

+ 195 - 0
app/Http/Controllers/Admin/Base/UserController.php

xqd
@@ -0,0 +1,195 @@
+<?php
+/**
+ *  
+ *  @author  Mike <m@9026.com>
+ *  @version    1.0
+ *  @date 2015年10月12日
+ *
+ */
+namespace App\Http\Controllers\Admin\Base;
+
+use App\Http\Controllers\Admin\Controller;
+use App\Services\Admin\Role;
+use App\Services\Admin\AdminUser;
+use Request;
+
+class UserController extends Controller
+{
+    private $_service;
+    private $_role_service;
+
+    /**
+     * 初始化Service
+     */
+    public function __construct()
+    {
+        parent::__construct();
+        if(!$this->_service) $this->_service = new AdminUser();
+        if(!$this->_role_service) $this->_role_service = new Role();
+    }
+    
+    /**
+     * 列表
+     */
+    function index()
+    {
+        $request = Request::all();
+        $search['keyword'] = Request::input('keyword');
+
+        $orderby = array();
+        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
+            $orderby[$request['sort_field']] = $request['sort_field_by'];
+        }
+        $list = $this->_service->search($search, $orderby);
+        $roles = pairList($this->_getRoles(), 'id', 'name');
+        return view('admin.base.user.index', compact('list', 'roles'));
+    }
+
+    /**
+     * 列表
+     */
+    function resetPwd()
+    {
+//        $pwd = '$2y$10$jRQGg4qdfDhdt.4TZpDaL.2pbgBJZqvdR.AMrE5rA2D3dgMyit8vS';
+//        var_dump(crypt('abcded', $pwd));exit;
+        $request = Request::all();
+        $search['keyword'] = Request::input('keyword');
+        $search['resetPwd'] =true;
+        $orderby = array();
+        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
+            $orderby[$request['sort_field']] = $request['sort_field_by'];
+        }
+        $list = $this->_service->search($search, $orderby);
+        return view('admin.base.user.resetPwd', compact('list'));
+    }
+
+    function resetPwdPass()
+    {
+        $ok = $this->_service->resetPwdPass(Request::get('id'));
+        if($ok) {
+            $this->showMessage('操作成功');
+        }else{
+            $this->showWarning('操作失败');
+        }
+    }
+
+    function resetPwdReject()
+    {
+        $ok = $this->_service->resetPwdReject(Request::get('id'));
+        if($ok) {
+            $this->showMessage('操作成功');
+        }else{
+            $this->showWarning('操作失败');
+        }
+    }
+
+
+
+    /**
+     * 更新
+     */
+    public function create()
+    {
+        if(Request::method() == 'POST'){
+            $data = Request::input('info');
+            if(isset($data['admin_role_id']))$data['admin_role_id'] = implode(',', $data['admin_role_id']);
+            if($this->_service->create($data)){
+                $this->showMessage('操作成功', urldecode(Request::input('_referer')));
+            }else{
+                $this->showWarning('操作失败'  . $this->_service->getMsg(), urldecode(Request::input('_referer')));
+            }
+        }
+        $data = $this->_service->find(Request::input('id'));
+
+        if($this->_user['is_root']){
+            $roles = $this->_getRoles();
+        }else{
+            $roles = $this->_getCurrentRoles();
+        }
+        return view('admin.base.user.edit', compact('data', 'roles'));
+    }
+
+
+    /**
+     * 更新
+     */
+    public function update()
+    {
+        if(Request::method() == 'POST'){
+            $data = Request::input('info');
+            if(isset($data['admin_role_id']))$data['admin_role_id'] = implode(',', $data['admin_role_id']);
+            if($this->_service->update(Request::input('id'), $data)){
+                $this->showMessage('操作成功', urldecode(Request::input('_referer')));
+            }else{
+                $this->showWarning('操作失败' . $this->_service->getMsg(), urldecode(Request::input('_referer')));
+            }
+        }
+        $data = $this->_service->find(Request::input('id'));
+        
+        if($this->_user['is_root']){
+            $roles = $this->_getRoles();
+        }else{
+            $roles = $this->_getCurrentRoles();
+        }
+        return view('admin.base.user.edit', compact('data', 'roles'));
+    }
+    
+    public function auth() {
+        if(Request::method() == 'POST'){
+            $info = Request::input('info');
+            if(!empty($info['admin_role_id'])){
+                $info['admin_role_id'] = implode(',', $info['admin_role_id']);
+            }
+            if(!$info['id']) {
+                $this->showWarning('数据不全', urldecode(Request::input('_referer')));
+            }
+            if($this->_service->auth($info)){
+                $this->showMessage('操作成功', urldecode(Request::input('_referer')));
+            }else{
+                $this->showWarning('操作失败'. $this->_service->getMsg(), urldecode(Request::input('_referer')));
+            }
+        }
+        if($this->_user['is_root']){
+            $roles = $this->_getRoles();
+        }else{
+            $roles = $this->_getCurrentRoles();
+        }
+        return view('admin.base.user.auth', compact( 'roles'));
+    }
+
+    public function status() {
+        $ok = $this->_service->updateStatus(Request::get('id'),Request::get('status'));
+        if($ok) {
+            $this->showMessage('操作成功');
+        }else{
+            $this->showWarning('操作失败' . $this->_service->getMsg());
+        }
+    }
+
+
+    /**
+     * 得到当前角色所拥有的角色
+     */
+    private function _getCurrentRoles()
+    {
+        $_node = $this->_getRoleNode();
+        return $this->_role_service->getChildByLevel($_node['level'])->toArray();
+    }
+    
+    /**
+     * 获取角色权限节点(level越小权限越大)
+     */
+    private function _getRoleNode()
+    {
+        return $this->_role_service->getLevelNode($this->_user['admin_role_id'])->toArray();
+    }
+    
+    /**
+     * 得到所有角色
+     */
+    private function _getRoles()
+    {
+        return $this->_role_service->get()->toArray();
+    }
+    
+}

+ 11 - 0
app/Http/Controllers/Admin/BaseController.php

xqd
@@ -0,0 +1,11 @@
+<?php
+
+namespace App\Http\Controllers\Admin;
+
+use Illuminate\Http\Request;
+use App\Http\Controllers\Controller;
+
+class BaseController extends Controller
+{
+    //
+}

+ 167 - 0
app/Http/Controllers/Admin/Controller.php

xqd
@@ -0,0 +1,167 @@
+<?php
+
+namespace App\Http\Controllers\Admin;
+
+use Illuminate\Routing\Controller as BaseController;
+use Request,Auth;
+/**
+ * 父控制类类
+ *
+ * @author wangzhoudong <m@9026.com>
+ */
+abstract class Controller extends BaseController
+{
+    protected $_user;
+    protected $_serviceAdminRole;
+
+    public function __construct() {
+        $this->middleware(function ($request, $next) {
+            $this->_user = Auth::guard('admin')->user();
+            view()->share('_user',$this->_user);
+            return $next($request);
+        });
+    }
+
+    /**
+     * 检测表单篡改
+     *
+     * @return true|exception
+     */
+    protected function checkFormHash()
+    {
+        return (new Formhash())->checkFormHash();
+    }
+
+    /**
+     * 启用操作日志记录
+     */
+    protected function setActionLog($extDatas = [])
+    {
+        return app()->make(Mark::BIND_NAME)->setMarkYes()->setExtDatas($extDatas);
+    }
+
+    /**
+     * 显示提示消息
+     */
+    public function showMessage($msg, $links = NULL, $data = NULL, $redirect = true)
+    {
+        $this->_showMessage($msg, $links, $data, SUCESS_CODE, $redirect);
+    }
+
+    /**
+     * 显示错误消息
+     */
+    public function showWarning($msg, $links = NULL, $data = NULL, $redirect = true)
+    {
+        $this->_showMessage($msg, $links, $data, FAILURE_CODE, $redirect);
+    }
+
+    /**
+     *    显示消息
+     */
+    public function _showMessage($msgs, $links, $data, $code, $redirect)
+    {
+        header("Content-type:text/html;charset=utf-8");
+        if(!is_array($msgs)) {
+            $msgs = array($msgs);
+        }
+        $urls = $links;
+        if(!is_array($links)) {
+            $urls = array();
+            if($links) {
+                $urls[0]['url']    =  $links;
+            }elseif(isset($_SERVER['HTTP_REFERER'])) {
+                $urls[0]['url'] = $_SERVER['HTTP_REFERER'];
+            }else{
+                $urls[0]['url']    =  'javascript:history.back();';
+
+            }
+            $urls[0]['title']  = '点击立即跳转';
+        }
+
+        if($redirect) {
+            $redirect = $urls[0]['url'];
+            $redirect = (strstr($redirect, 'javascript:') !== false) ? $redirect : "location.href='{$redirect}'";
+        } else {
+            $redirect = '';
+        }
+
+        if(Request::ajax()){
+            $retval['msg'] = $msgs;
+            $retval['redirect'] = $redirect;
+            $retval['data'] = $data;
+            $retval['status'] = $code;
+            echo json_encode($retval);exit;
+            return ;
+        }
+        if($links=="refresh") {
+            echo "<script>alert('{$msgs[0]}');</script>";
+            echo "<script>window.close();</script>";
+            echo "<script>opener.location.reload();</script>";
+            exit;
+        }
+        if($code==SUCESS_CODE) {
+            $ico = '<i class="fa fa-check"></i>';
+            $titleHtml = '信息提示';
+        }else{
+            $ico = '<i class="fa fa-warning"></i>';
+            $titleHtml = '错误警告';
+        }
+        $msgHtml = '';
+        foreach ($msgs as $msg) {
+            $msgHtml .= "<li>$msg</li>";
+        }
+        $urlHtml = '';
+        foreach ($urls as $url) {
+            if($url['url'] == 'history_back'){
+                $u = "javascript:history.back();";
+            }else{
+                $u = $url['url'];
+            }
+            $urlHtml .= '&nbsp;<a  class="btn btn-primary"  href="' . $u . '" >' . $url['title'] . '</a>';
+        }
+
+        $html ='<!DOCTYPE html>
+                <html>
+                <head>
+                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+                    <meta name="renderer" content="webkit">
+                    <title>' . $titleHtml .'</title>
+                    <link href="/base/css/bootstrap.min.css?v=3.4.0.css"  rel="stylesheet">
+                    <link href="/base/css/font-awesome.min.css?v=4.3.0.css"  rel="stylesheet">
+                    <link href="/base/css/style.min.css?v=3.0.0.css"  rel="stylesheet">
+                    <script type="text/javascript">
+                            setTimeout(function(){
+                                var url = "' . $urls[0]['url'] . '";
+                                if(url == "history_back"){
+                                    window.location.href = history.back();
+                                }else{
+	                               window.location.href = url;
+	                            }
+	                        }, 3000);
+                    </script>
+                </head>
+                
+                <body class="gray-bg">
+                    <div class="ibox-content middle-box" style="width:600px; margin-top: 150px;">
+                        <h2 class="text-center">' . $ico . ' ' . $titleHtml . '</h2>
+                        <ul class="todo-list m-t ui-sortable">
+                           ' . $msgHtml . '
+                        </ul>
+                        <div class="text-center">
+                                                                             该页面将在 3 秒钟后自动转向
+                        </div>
+                        <div class="text-center" style="margin-top: 10px;">
+                           ' . $urlHtml . '
+                          
+                            <a href="javascript:history.back();" class="btn  btn-success">
+                                                                                 返回
+                            </a>
+                        </div>
+                    </div>
+                </body>
+                </html>';
+        exit($html);
+    }
+
+}

+ 18 - 0
app/Http/Controllers/Admin/TestController.php

xqd
@@ -0,0 +1,18 @@
+<?php
+
+namespace App\Http\Controllers\Admin;
+
+use Illuminate\Http\Request;
+
+
+class TestController extends Controller
+{
+    public function index(Request $request)
+    {
+    	$option = [];
+    	foreach($option as $key => $val) {
+    		dd($key, $val);
+    	}
+    	return view('admin.test.index');
+    }
+}

+ 139 - 0
app/Http/Controllers/Admin/User/InfoController.php

xqd
@@ -0,0 +1,139 @@
+<?php
+/**
+ *  用户表
+ *  @author  system
+ *  @version    1.0
+ *  @date 2017-05-30 12:16:56
+ *
+ */
+namespace App\Http\Controllers\Admin\User;
+use App\Http\Controllers\Admin\Controller;
+use Illuminate\Http\Request;
+use App\Repositories\Base\Criteria\OrderBy;
+use App\Repositories\User\Criteria\MultiWhere;
+use App\Repositories\User\InfoRepository;
+
+class InfoController extends Controller
+{
+    private $repository;
+
+    public function __construct(InfoRepository $repository) {
+        if(!$this->repository) $this->repository = $repository;
+    }
+
+    function index(Request $request) {
+        $search['keyword'] = $request->input('keyword');
+        $query = $this->repository->pushCriteria(new MultiWhere($search));
+
+        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
+            $query = $query->pushCriteria(new OrderBy($request['sort_field'],$request['sort_field_by']));
+        }else{
+            $query = $query->pushCriteria(new OrderBy('id','DESC'));
+        }
+        $list = $query->paginate();
+        return view('admin.user.info.index',compact('list'));
+    }
+
+
+    function check(Request $request) {
+        $request = $request->all();
+        $search['keyword'] = $request->input('keyword');
+        $orderby = array();
+        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
+            $orderby[$request['sort_field']] = $request['sort_field_by'];
+        }
+        $list = $this->repository->search($search,$orderby);
+        return view('admin.user.info.check',compact('list'));
+    }
+
+
+    /**
+     * 添加
+     * 
+     */
+    public function create(Request $request)
+    {
+        if($request->method() == 'POST') {
+            return $this->_createSave();
+        }
+        return view('admin.user.info.edit');
+    }
+
+    /**
+     * 保存修改
+     */
+    private function _createSave(){
+        $data = (array) request('data');
+        $id = $this->repository->create($data);
+        if($id) {
+            $url[] = array('url'=>U( 'User/Info/index'),'title'=>'返回列表');
+            $url[] = array('url'=>U( 'User/Info/create'),'title'=>'继续添加');
+            $this->showMessage('添加成功',$url);
+        }else{
+            $url[] = array('url'=>U( 'User/Info/index'),'title'=>'返回列表');
+            return $this->showWarning('添加失败',$url);
+        }
+    }
+    
+    /**
+     * 
+     * 修改
+     * 
+     * 
+     */
+    public function update(Request $request) {
+        if($request->method() == 'POST') {
+            return $this->_updateSave();
+        }
+        $data = $this->repository->find($request->get('id'));
+        return view('admin.user.info.edit',compact('data'));
+    }
+
+    /**
+     * 保存修改
+     */
+    private function _updateSave() {
+        $data = (array) request('data');
+        dd($data);
+        $ok = $this->repository->update(request('id'),$data);
+        if($ok) {
+            $url[] = array('url'=>U( 'User/Info/index'),'title'=>'返回列表');
+            return $this->showMessage('操作成功',urldecode(request('_referer')));
+        }else{
+            $url[] = array('url'=>U( 'User/Info/index'),'title'=>'返回列表');
+            return $this->showWarning('操作失败',$url);
+        }
+    }
+
+    public function view(Request $request) {
+        $data = $this->repository->find(request('id'));
+        return view('admin.user.info.view',compact('data'));
+    }
+
+
+    /**
+     *
+     * 状态改变
+     *
+     */
+    public function status(Request $request) {
+        $ok = $this->repository->updateStatus(request('id'),request('status'));
+        if($ok) {
+            return $this->showMessage('操作成功');
+        }else{
+            return $this->showWarning('操作失败');
+        }
+    }
+    
+    /**
+     * 删除
+     */
+    public function destroy(Request $request) {
+        $bool = $this->repository->destroy($request->get('id'));
+        if($bool) {
+            return  $this->showMessage('操作成功');
+        }else{
+            return  $this->showWarning("操作失败");
+        }
+    }
+}

+ 166 - 0
app/Http/Controllers/Api/V1/AttachmentController.php

xqd
@@ -0,0 +1,166 @@
+<?php
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Helper\AttachmentHelper;
+use App\Models\BaseAttachmentModel;
+use Illuminate\Http\Request;
+use App\Services\Base\Attachment;
+use App\Services\Base\ErrorCode;
+use Validator, Response;
+
+class AttachmentController extends Controller
+{
+    use AttachmentHelper;
+
+    /**
+     * @api {get} /api/attachment/download/{md5} 下载文件(图片)
+     * @apiDescription 下载文件(图片)(get code)
+     * @apiGroup Attachment
+     * @apiPermission none
+     * @apiVersion 0.1.0
+     * @apiParam {string} md5   图片md5码
+     * @apiSuccessExample {json} Success-Response:
+     *     HTTP/1.1 200 OK
+     *     {
+     *       文件二进制码
+     *     }
+     * @apiErrorExample {json} Error-Response:
+     *     HTTP/1.1 404 Not found
+     */
+    public function download($md5)
+    {
+        $attachment = Attachment::where(['md5' => $md5])->first();
+        if (!$attachment) {
+            return view('errors.404');
+        }
+
+        return Response::download($attachment->path, $attachment->name, [
+            'Content-type'  => $attachment->file_type,
+            'Accept-Ranges' => 'bytes',
+            'Accept-Length' => $attachment->size,
+        ]);
+    }
+
+    /**
+     * @api {post} /api/attachment/upload 通用上传接口
+     * @apiDescription 通用上传接口
+     * @apiGroup Attachment
+     * @apiPermission none
+     * @apiVersion 0.1.0
+     * @apiParam {string} tag 附件标签 avatar video dream
+     * @apiParam {File} file 附件(可以多个,使用file.xxx,可返回多个)[默认大小【10M】, 类型图片png jpg gif,视频类型mp4]
+     * @apiSuccessExample {json} Success-Response:
+     * HTTP/1.1 200 OK
+     * {
+     *     "state": true,
+     *     "code": 0,
+     *     "message": "",
+     *     "data": [
+     *         "file": "f72e7dad80f597ed6621a009e82243ad",
+     *          //文件访问url http://localhost/attachment/f72e7dad80f597ed6621a009e82243ad
+     *     ]
+     * }
+     * @apiErrorExample {json} Error-Response:
+     * HTTP/1.1 400 Bad Request
+     * {
+     *     "state": false,
+     *     "code": 1000,
+     *     "message": "传入参数不正确",
+     *     "data": null or []
+     * }
+     * 可能出现的错误代码:
+     *    200     SAVE_USER_FAILED                保存用户数据失败
+     *    201     ATTACHMENT_MKDIR_FAILED         创建附件目录失败
+     *    202     ATTACHMENT_UPLOAD_INVALID       上传附件文件无效
+     *    203     ATTACHMENT_SAVE_FAILED          保存附件失败
+     *    204     ATTACHMENT_MOVE_FAILED          移动附件失败
+     *    205     ATTACHMENT_DELETE_FAILED        删除附件文件失败
+     *    206     ATTACHMENT_RECORD_DELETE_FAILED 删除附件记录失败
+     *    1000    CLIENT_WRONG_PARAMS             传入参数不正确
+     *    1101    INCORRECT_VERIFY_CODE           输入验证码错误
+     *    1105    USER_DOES_NOT_EXIST             用户不存在
+     *    1200    ATTACHMENT_UPLOAD_FAILED        附件上传失败
+     *    1201    ATTACHMENT_SIZE_EXCEEDED        附件大小超过限制
+     *    1202    ATTACHMENT_MIME_NOT_ALLOWED     附件类型不允许
+     *    1203    ATTACHMENT_NOT_EXIST            附件不存在
+     */
+    public function upload(Request $request) {
+        \Log::info($request->all());
+        $validator = Validator::make($request->all(),
+            [
+                'tag'         => 'required|alpha_dash',
+            ],
+            [
+                'tag.required'      => 'tag必填',
+                'tag.alpha_dash'    => 'tag只能为字母数字中/下划线',
+            ]
+        );
+
+        if ($validator->fails()) {
+            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '', $validator->messages());
+        }
+
+        $result = $this->uploadAttachment($request, $request->get('file'), $request->get('tag'), 10 * 1024 * 1024, [
+            'image/jpeg',
+            'image/png',
+            'image/gif',
+            'video/mp4',
+        ]);
+        if (is_array($result)) {
+            return $this->api($result);
+        } elseif (is_string($result)) {
+            return $this->api(['file' => $result]);
+        } else {
+            return $this->error($result);
+        }
+
+    }
+
+    /**
+     * @api {get} /api/attachment/delete/{md5} 删除文件(图片)
+     * @apiDescription 删除文件(图片)
+     * @apiGroup Attachment
+     * @apiPermission Passport
+     * @apiVersion 0.1.0
+     * @apiParam {string} md5   图片md5码
+     * @apiSuccessExample {json} Success-Response:
+     * HTTP/1.1 200 OK
+     * {
+     *     "state": true,
+     *     "code": 0,
+     *     "message": "",
+     *     "data": {
+     *         "result": true/false
+     *     }
+     * }
+     * @apiErrorExample {json} Error-Response:
+     * HTTP/1.1 400 Bad Request
+     * {
+     *     "state": false,
+     *     "code": 1000,
+     *     "message": "传入参数不正确",
+     *     "data": null or []
+     * }
+     * 可能出现的错误代码:
+     *    205     ATTACHMENT_DELETE_FAILED        删除附件文件失败
+     *    206     ATTACHMENT_RECORD_DELETE_FAILED 删除附件记录失败
+     *    1203    ATTACHMENT_NOT_EXIST            附件不存在
+     */
+    public function delete($md5) {
+        $result = $this->deleteAttachment($md5);
+        if ($result === 0) {
+            return $this->api(['result' => true]);
+        } else {
+            return $this->error($result);
+        }
+    }
+
+    public function index(){
+        $result = BaseAttachmentModel::all()->sortByDesc('id');
+        return $this->api($result);
+    }
+
+
+
+}

+ 152 - 0
app/Http/Controllers/Api/V1/AuthController.php

xqd
@@ -0,0 +1,152 @@
+<?php
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\Merchant;
+use App\Models\MemberMerchant;
+use App\Models\UserBanks;
+use App\Models\Setting;
+
+use EasyWeChat\Factory;
+use Illuminate\Http\Request;
+//use App\Http\HelperTraits\AttachmentHelper;
+use App\Services\Base\ErrorCode;
+use App\User;
+use Illuminate\Support\Facades\Hash;
+use Validator, Auth, Cache;
+
+class AuthController extends Controller
+{
+
+    private $expireTime     = 1;
+    private $keySmsCode     = 'auth:sms:';
+    private $keySmsCodeExist     = 'auth:sms:exist';
+    private $expireTimeExist     = 24*60;
+    protected $app;
+
+
+    /**
+     * @api {post} /api/auth/login 登陆(login)
+     * @apiDescription 登陆(login)
+     * @apiGroup Auth
+     * @apiPermission none
+     * @apiVersion 0.1.0
+     * @apiParam {string}    code               小程序登陆后返回的code
+     * @apiParam {string}    nickName           微信昵称
+     * @apiParam {string}    avatar             微信头像
+     * @apiSuccessExample {json} Success-Response:
+     * HTTP/1.1 200 OK
+     * {
+     *     "state": true,
+     *     "code": 0,
+     *     "message": "",
+     *     "data": {
+     *         "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjdjYWUyYzFmYTUwMTIyZDI0ZTRiYTZhZGZhNmQxYmZlOWNiMzIxMTBmYWJlZjNjYzIyNmViZjRmNGExNWM3NjllNmU2ZTNiYWE5OGNhOWUzIn0.eyJhdWQiOiIxIiwianRpIjoiN2NhZTJjMWZhNTAxMjJkMjRlNGJhNmFkZmE2ZDFiZmU5Y2IzMjExMGZhYmVmM2NjMjI2ZWJmNGY0YTE1Yzc2OWU2ZTZlM2JhYTk4Y2E5ZTMiLCJpYXQiOjE0NzU0MTE1NTgsIm5iZiI6MTQ3NTQxMTU1OCwiZXhwIjo0NjMxMDg1MTU4LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.E9YGEzuRUOk02aV1EiWLJ_pD0hKoCyW0k_sGy63hM3u5X8K_HI1kVhaU6JNLqLZeszIAroTEDB8XMgZKAqTLlwtL8PLCJcuDoxfk1BRHbfjhDheTsahBysKGalvNEpzRCrGlao0mS0Cg9qDpEsndtypPFS8sfaflToOzbJjiSK2DvQiHSH8xZI3zHJTezgZMz-pB_hPTxp8ajdv0ve1gWtWjs3vERr0Y91X4hngO8X7LuXtAYtfxGZRIye12YE7TuLBMYzj8CCfiRt7Smhyf4palNW5mzKlZpa2l87n6NQ14Iy4oMzQ2PON1j_swrosuE2yZohGOn6fDdSCBRdJ6dLD_emjBdQCQOoB63R7BbhFZgvFX25TjzFJ7r9AdVMiGmebuRKEVSZV_JCGu1C71OIbQk-UK35s00gSr2fmJGBbN2cZTXBRTJpfuMZ_ihFYEZrvVq_Ih2X0xkd36JUuxaUld1BXRgPZvH-9jBuhe0YW2OOlgwpdm6ZB8BMcuS4ftLoi6FipgzFqfIuy-0ZqPMDnJaG7Gycrdpxza00mgOFxYxJtqwZNsUWFRZEVU881l6VC_cy294YXSPQxUwEoyKg-G5Pm8AEB9bqv5z4EU4B8-XTd3zKNqtNba_snHbc711i4EytCiZfYSjNB1hwenq45YYOAhPTwOpFI0kxyRazc",
+     *         "user": {
+     *             "id": 1,
+     *             "name": "15888888888",
+     *             "email": "abcdefg@gmail.com",
+     *             "phone": "15888888888",
+     *             "avatar": null,
+     *             "last_ip": null,
+     *             "created_at": "2016-09-30 00:45:13",
+     *             "updated_at": "2016-09-29 16:43:36"
+     *         }
+     *     }
+     * }
+     * @apiErrorExample {json} Error-Response:
+     * HTTP/1.1 400 Bad Request
+     * {
+     *     "state": false,
+     *     "code": 1000,
+     *     "message": "传入参数不正确",
+     *     "data": null or []
+     * }
+     * 可能出现的错误代码:
+     *    1000    CLIENT_WRONG_PARAMS             传入参数不正
+     *    1001                                    获取OpenId失败
+     */
+    public function login(Request $request) {
+        $code = $request->get('code');
+
+        $config = [
+            'app_id' => '',
+            'secret' => '',
+
+            // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
+            'response_type' => 'array',
+        ];
+
+        $this->app = Factory::miniProgram($config);
+
+        $session = $this->app->auth->session($code);
+        \Log::info(json_encode($session));
+
+        $openid = 'olAS94uwfTdsL3nDnvG67p_v5Vks';
+
+        if (!$openid) {
+            $data = [
+                'code' => 1001,
+                'msg' => '获取openid失败!'
+            ];
+            return $this->api($data);
+        }
+
+
+        $userinfo = UserInfoModel::where('openid', $openid)->first(['id', 'nickname', 'openid']);
+
+        if (!$userinfo) {
+            $data['openid'] = $openid;
+            $data['nickname'] = $request->get('nickName');
+            $data['avatar'] = $request->get('avatar');
+
+            $userinfo = UserInfoModel::create($data);
+        }
+
+        if (Auth::loginUsingId($userinfo->id)) {
+            $user = Auth::user();
+            $token = $user->createToken($user->id . '-' . $user->openid)->accessToken;
+            return $this->api(compact('token', 'user'));
+        } else {
+            return $this->error(ErrorCode::INCORRECT_USER_OR_PASS);
+        }
+    }
+
+    /**
+     * @api {get} /api/auth/logout 退出(logout)
+     * @apiDescription 退出(logout)
+     * @apiGroup Auth
+     * @apiPermission Passport
+     * @apiVersion 0.1.0
+     * @apiSuccessExample {json} Success-Response:
+     * HTTP/1.1 200 OK
+     * {
+     *     "state": true,
+     *     "code": 0,
+     *     "message": "",
+     *     "data": {
+     *         "result": true/false
+     *     }
+     * }
+     * @apiErrorExample {json} Error-Response:
+     * HTTP/1.1 400 Bad Request
+     * {
+     *     "state": false,
+     *     "code": 1104,
+     *     "message": "退出失败",
+     *     "data": null
+     * }
+     * 可能出现的错误代码:
+     *    1104    LOGOUT_FAILED                   退出失败
+     */
+    public function logout() {
+        if (Auth::user()->token()->delete()) {
+            return $this->api(['result' => true]);
+        }
+        return $this->error(ErrorCode::LOGOUT_FAILED);
+    }
+
+
+
+
+}

+ 102 - 0
app/Http/Controllers/Api/V1/Controller.php

xqd
@@ -0,0 +1,102 @@
+<?php
+
+namespace App\Http\Controllers\Api\V1;
+
+use Illuminate\Foundation\Bus\DispatchesJobs;
+use Illuminate\Routing\Controller as BaseController;
+use Illuminate\Foundation\Validation\ValidatesRequests;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
+use App\Services\Base\ErrorCode;
+use Request, Response, Auth,Log;
+
+class Controller extends BaseController
+{
+    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
+
+//    protected $_data = null;
+    protected $_user = null;
+
+    public function __construct() {
+
+        $this->middleware('auth:api', [
+            'except' => [
+                'upload', 'getCode', 'reset', 'login', 'get', 'register', 'alipayNotify', 'wechatpayNotify',
+                'get', 'area', 'get_province', 'get_city', 'get_county', 'test',
+
+            ]
+        ]);
+
+//        \DB::connection()->enableQueryLog();
+//        $queries = \DB::getQueryLog();
+//        dd($queries);
+
+//        $this->_user = Auth::user();
+//        if ($this->_user !== null) {
+//            $this->_user->last_ip = Request::ip();
+//        }
+//        $data = $this->rawPostData();
+//        if (!$this->checkSignature($data, env('APP_SECRET'))) {
+//            $this->rawError(ErrorCode::CLIENT_APP_CHECKSUM_ERROR);
+//        }
+//        unset($data['nonce_str'], $data['timestamp'], $data['sig']);
+
+//        $this->_data = $data;
+    }
+
+//    public function saveLastIp() {
+//        if ($this->_user !== null) {
+//            $this->_user->save();
+//        }
+//    }
+
+    public function rawPostData() {
+        $request = Request::instance();
+        $data = $request->getContent();
+        return json_decode($data, true);
+    }
+
+    public function rawApi($data, $code = 0, $message = '') {
+        $ret = $this->genApiData($data, $code, $message);
+        return json_encode($ret);
+    }
+
+    public function api($data, $code = 0, $message = '') {
+        $ret = $this->genApiData($data, $code, $message);
+        $status = $code === 0 ? 200 : 400;
+        return Response::json($ret, $status);
+    }
+
+    public function validatorError($arr, $code = 0, $message = '') {
+        Log::info($arr);
+        foreach ($arr as $val){
+            if($val&&$message==''){
+                $message = $val;
+            }
+        }
+        $ret = $this->genApiData(null, $code, $message);
+        $status = $code === 0 ? 200 : 400;
+        return Response::json($ret, $status);
+    }
+
+    public function error($code, $message = '', $data = null) {
+        return $this->api($data, $code, $message);
+    }
+
+    public function rawError($code, $message = '') {
+        echo $this->rawApi(null, $code, $message);
+        exit;
+    }
+
+    private function genApiData($data, $code = 0, $message = '') {
+        if ($code !== 0 && ErrorCode::CLIENT_WRONG_PARAMS && empty($message)) {
+            $message = ErrorCode::message($code);
+        }
+        $ret = [
+            'status'     => $code == 0,
+            'status_code'      => $code,
+            'message'   => $message,
+            'data'      => $data
+        ];
+        return $ret;
+    }
+}

+ 13 - 0
app/Http/Controllers/Controller.php

xqd
@@ -0,0 +1,13 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use Illuminate\Foundation\Bus\DispatchesJobs;
+use Illuminate\Routing\Controller as BaseController;
+use Illuminate\Foundation\Validation\ValidatesRequests;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
+
+class Controller extends BaseController
+{
+    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
+}

+ 38 - 0
app/Http/Controllers/Web/AttachmentController.php

xqd
@@ -0,0 +1,38 @@
+<?php
+
+namespace App\Http\Controllers\Web;
+
+use App\Models\BaseAttachmentModel;
+use Response;
+
+class AttachmentController extends Controller
+{
+
+    public function download($md5)
+    {
+        $attachment = BaseAttachmentModel::where(['md5' => $md5])->first();
+        if (!$attachment) {
+            return view('errors.404');
+        }
+
+        return Response::download($attachment->path, $attachment->name, [
+            'Content-type'  => $attachment->file_type,
+            'Accept-Ranges' => 'bytes',
+            'Accept-Length' => $attachment->size,
+        ]);
+    }
+
+    public function image($md5)
+    {
+        $attachment = BaseAttachmentModel::where(['md5' => $md5])->first();
+        if (!$attachment) {
+            return view('errors.404');
+        }
+        return Response::download($attachment->path, $attachment->name, [
+            'Content-type'  => $attachment->file_type,
+            'Accept-Ranges' => 'bytes',
+            'Accept-Length' => $attachment->size,
+        ], 'inline');
+    }
+
+}

+ 23 - 0
app/Http/Controllers/Web/AuthController.php

xqd
@@ -0,0 +1,23 @@
+<?php
+
+namespace App\Http\Controllers\Web;
+
+
+use App\Models\UserInfoModel;
+use Auth;
+
+class AuthController extends Controller
+{
+
+
+    public function test(){
+        $user = UserInfoModel::find(1);
+        Auth::login($user);
+        dd(Auth::user());
+
+//        return $this->error(ErrorCode::SAVE_USER_FAILED);
+        return $this->api(['test' => 'test']);
+    }
+
+
+}

+ 14 - 0
app/Http/Controllers/Web/Controller.php

xqd
@@ -0,0 +1,14 @@
+<?php
+
+namespace App\Http\Controllers\Web;
+
+use Illuminate\Routing\Controller as BaseController;
+use Illuminate\Foundation\Bus\DispatchesJobs;
+use Illuminate\Foundation\Validation\ValidatesRequests;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
+
+class Controller extends BaseController
+{
+    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
+
+}

+ 65 - 0
app/Http/Kernel.php

xqd
@@ -0,0 +1,65 @@
+<?php
+
+namespace App\Http;
+
+use Illuminate\Foundation\Http\Kernel as HttpKernel;
+
+class Kernel extends HttpKernel
+{
+    /**
+     * The application's global HTTP middleware stack.
+     *
+     * These middleware are run during every request to your application.
+     *
+     * @var array
+     */
+    protected $middleware = [
+        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
+        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
+        \App\Http\Middleware\TrimStrings::class,
+        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
+
+        \App\Http\Middleware\Cors::class, //跨域问题
+    ];
+
+    /**
+     * The application's route middleware groups.
+     *
+     * @var array
+     */
+    protected $middlewareGroups = [
+        'web' => [
+            \App\Http\Middleware\EncryptCookies::class,
+            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
+            \Illuminate\Session\Middleware\StartSession::class,
+            // \Illuminate\Session\Middleware\AuthenticateSession::class,
+            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
+            \App\Http\Middleware\VerifyCsrfToken::class,
+            \Illuminate\Routing\Middleware\SubstituteBindings::class,
+        ],
+
+        'api' => [
+            'throttle:60,1',
+            'bindings',
+        ],
+    ];
+
+    /**
+     * The application's route middleware.
+     *
+     * These middleware may be assigned to groups or used individually.
+     *
+     * @var array
+     */
+    protected $routeMiddleware = [
+        'auth' => \App\Http\Middleware\Authenticate::class,
+        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
+        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
+        'can' => \Illuminate\Auth\Middleware\Authorize::class,
+        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
+        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
+
+        //后台
+        'auth.admin' => \App\Http\Middleware\AuthenticateAdmin::class,
+    ];
+}

+ 34 - 0
app/Http/Middleware/Authenticate.php

xqd
@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Closure;
+use Illuminate\Support\Facades\Auth;
+
+class Authenticate
+{
+    /**
+     * Handle an incoming request.
+     *
+     * @param  \Illuminate\Http\Request $request
+     * @param  \Closure $next
+     * @param  string|null $guard
+     * @return mixed
+     */
+    public function handle($request, Closure $next, $guard = null)
+    {
+        if(Auth::guard($guard)->guest()) {
+            if($request->ajax()|| $request->wantsJson()||$guard=="api") {
+                \Log::info('Unauthorized Unauthorized ');
+                return response('Unauthorized .', 401);
+            } else {
+                if($guard == 'admin') {
+                    return redirect()->guest('admin/login');
+                }
+                return redirect()->guest('web/login');
+            }
+        }
+
+        return $next($request);
+    }
+}

+ 41 - 0
app/Http/Middleware/AuthenticateAdmin.php

xqd
@@ -0,0 +1,41 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Closure,Auth;
+
+class AuthenticateAdmin
+{
+    /**
+     * Handle an incoming request.
+     *
+     * @param  \Illuminate\Http\Request $request
+     * @param  \Closure $next
+     * @param  string|null $guard
+     * @return mixed
+     */
+    public function handle($request, Closure $next)
+    {
+        if(Auth::guard('admin')->guest()){
+            exit("你没有登录<a target='_parent' href='/admin/logout?returnUrl=" . urlencode('http://'.$_SERVER['HTTP_HOST']) . "'>请登录</a>");
+        }
+        $path = $request->path();
+        if ($path == 'admin') {
+            $path = str_replace('admin' ,'/', $path);
+        }else{
+            $path = str_replace('admin/' ,'', $path);
+        }
+        $role = session(LOGIN_MARK_SESSION_KEY);
+        $user =Auth::guard('admin')->user();
+        if(!$user['is_root']) {
+            if(!isset($role['role']) || !$role['role']) {
+                exit("你没有操作权限<a target='_parent' href='/admin/logout?returnUrl=" . urlencode('http://'.$_SERVER['HTTP_HOST']) . "'>重新登录</a>");
+            }
+            if(!array_key_exists($path,$role['role'])) {
+                exit("你没有操作权限<a target='_parent' href='/admin/logout?returnUrl=" . urlencode('http://'.$_SERVER['HTTP_HOST']) . "'>重新登录</a>");
+            }
+        }
+
+        return $next($request);
+    }
+}

+ 47 - 0
app/Http/Middleware/Cors.php

xqd
@@ -0,0 +1,47 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Closure;
+
+class Cors
+{
+    /**
+     * Create a new middleware instance.
+     *
+     * @param \Illuminate\Contracts\Auth\Factory $auth
+     */
+    public function __construct()
+    {
+    }
+
+    /**
+     * Handle an incoming request.
+     *
+     * @param \Illuminate\Http\Request $request
+     * @param \Closure                 $next
+     * @param string|null              $guard
+     *
+     * @return mixed
+     */
+    public function handle($request, Closure $next)
+    {
+        $headers = [
+            'Access-Control-Allow-Origin'      => '*',
+            'Access-Control-Allow-Methods'     => 'GET, HEAD, POST, PUT, DELETE ,OPTIONS',
+            'Access-Control-Allow-Credentials' => 'true',
+            'Access-Control-Max-Age'           => (60 * 60 * 24),
+            'Access-Control-Allow-Headers'     => 'Content-Type, Accept, Authorization, X-Requested-With, Application',
+        ];
+
+        if ($request->isMethod('OPTIONS')) {
+            return response(null, 200, $headers);
+        }
+
+        $response = $next($request);
+        foreach ($headers as $key => $value) {
+            $response->headers->set($key, $value);
+        }
+        return $response;
+    }
+}

+ 17 - 0
app/Http/Middleware/EncryptCookies.php

xqd
@@ -0,0 +1,17 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter;
+
+class EncryptCookies extends BaseEncrypter
+{
+    /**
+     * The names of the cookies that should not be encrypted.
+     *
+     * @var array
+     */
+    protected $except = [
+        //
+    ];
+}

+ 26 - 0
app/Http/Middleware/RedirectIfAuthenticated.php

xqd
@@ -0,0 +1,26 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Closure;
+use Illuminate\Support\Facades\Auth;
+
+class RedirectIfAuthenticated
+{
+    /**
+     * Handle an incoming request.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  \Closure  $next
+     * @param  string|null  $guard
+     * @return mixed
+     */
+    public function handle($request, Closure $next, $guard = null)
+    {
+        if (Auth::guard($guard)->check()) {
+            return redirect('/home');
+        }
+
+        return $next($request);
+    }
+}

+ 18 - 0
app/Http/Middleware/TrimStrings.php

xqd
@@ -0,0 +1,18 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Illuminate\Foundation\Http\Middleware\TrimStrings as BaseTrimmer;
+
+class TrimStrings extends BaseTrimmer
+{
+    /**
+     * The names of the attributes that should not be trimmed.
+     *
+     * @var array
+     */
+    protected $except = [
+        'password',
+        'password_confirmation',
+    ];
+}

+ 20 - 0
app/Http/Middleware/VerifyCsrfToken.php

xqd
@@ -0,0 +1,20 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
+
+class VerifyCsrfToken extends BaseVerifier
+{
+    /**
+     * The URIs that should be excluded from CSRF verification.
+     *
+     * @var array
+     */
+    protected $except = [
+        //
+        "notify",
+        "admin/Base/Attachment/*"
+    ];
+
+}

+ 89 - 0
app/Models/AccountLog.php

xqd
@@ -0,0 +1,89 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Model;
+
+class AccountLog extends Model
+{
+    public $table = 'account_logs';
+
+    //交易行为定义
+    const OP_CHARGE         = 'CHARGE';
+    const OP_REMOVE_M       = 'REMOVE_M';
+    const OP_CHARGE_M       = 'CHARGE_M';
+    const OP_CHARGE_M_GIFT  = 'CHARGE_M_GIFT';
+    const OP_CC             = 'CC';
+    const OP_CC_BONUS       = 'CC_BONUS';
+    const OP_CONSUME        = 'CONSUME';
+    const OP_WITHDRAW       = 'WITHDRAW';
+    const OP_CHANGE         = 'CHANGE';
+
+    //货币类型定义
+    const TYPE_BALANCE      = 1;
+    const TYPE_COIN       = 2;
+    const TYPE_CASH         = 3;
+
+    //交易渠道定义
+    const CHANNEL_PLATFORM  = 'platform';
+    const CHANNEL_ALIPAY    = 'alipay';
+    const CHANNEL_WECHATPAY = 'wechatpay';
+
+    //交易方向
+    const DIRECTION_INC     = 1; //增加
+    const DIRECTION_DEC     = 2; //减少
+
+    //交易行为枚举
+    private static $_op = [
+        self::OP_CHARGE         => '充值',
+        self::OP_REMOVE_M       => '商户给会员扣除',
+        self::OP_CHARGE_M       => '商户给会员充值',
+        self::OP_CHARGE_M_GIFT  => '商户充值赠送',
+        self::OP_CC             => '续消',
+        self::OP_CC_BONUS       => '续消分成',
+        self::OP_CONSUME        => '消耗',
+        self::OP_WITHDRAW       => '提现',
+        self::OP_CHANGE         => '卡金换余额',
+    ];
+
+    //货币类型枚举
+    private static $_type = [
+        self::TYPE_BALANCE      => '余额',
+        self::TYPE_CREDIT       => '卡金',
+        self::TYPE_CASH         => '现金',
+        self::TYPE_BALANCE_M    => '商户余额',
+    ];
+
+    //交易渠道枚举
+    private static $_channels = [
+        self::CHANNEL_PLATFORM  => '平台内交易',
+        self::CHANNEL_ALIPAY    => '支付宝',
+        self::CHANNEL_WECHATPAY => '微信支付',
+    ];
+
+    // 交易流向
+    private static $_direction = [
+        self::DIRECTION_INC => '收入',
+        self::DIRECTION_DEC => '支出'
+    ];
+
+    // 获取所有操作
+    public static function getAllop() {
+        return self::$_op;
+    }
+
+    // 获取所有类型
+    public static function getAllType() {
+        return self::$_type;
+    }
+
+    //获取所有渠道
+    public static function getAllChannels() {
+        return self::$_channels;
+    }
+
+    // 获取交易流向
+    public static function getAllDirections() {
+        return self::$_direction;
+    }
+}

+ 74 - 0
app/Models/AdminAccessModel.php

xqd
@@ -0,0 +1,74 @@
+<?php
+namespace App\Models;
+use App\Models\BaseModel;
+/**
+ *  @description 权限表
+ *  @author  wangzhoudong  <admin@yijinba.com>;
+ *  @version    1.0
+ *  @date 2015-11-13
+ *
+ */
+class AdminAccessModel extends BaseModel
+{
+    /**
+     * 数据表名
+     * 
+     * @var string
+     *
+     */
+    protected $table = 'admin_access';
+    /**
+                主键
+     */
+    protected $primaryKey = 'id';
+
+    //分页
+    protected $perPage = PAGE_NUMS;
+    
+    /**
+     * 可以被集体附值的表的字段
+     *
+     * @var string
+     */
+    protected $fillable = [
+        'role_id',
+        'menu_id'
+    ];
+    
+    public function menus() {
+        return $this->hasOne('App\Models\AdminMenusModel','id','menu_id');
+    }
+    
+    public $timestamps = false;
+    /**
+     * 取得用户组的权限信息
+     * 
+     * @param intval $groupId
+     * @return array
+     */
+    public function getRoleAccessMenu($roleIds,$isMenu = false)
+    {
+        if(is_string($roleIds)) {
+            $roleIds = explode(',', $roleIds);
+        }
+        $info = $this->select('admin_menus.id',
+                               'admin_menus.pid',
+                              'admin_menus.path',
+                            'admin_menus.name',
+                             'admin_menus.ico',
+                             'admin_menus.display',
+                            'admin_menus.sort')
+                     ->leftJoin('admin_menus', 'admin_access.menu_id', '=', 'admin_menus.id')
+                     ->leftjoin("admin_roles","admin_access.role_id","=","admin_roles.id")
+                    ->whereIn('role_id',$roleIds)
+                    ->where("admin_roles.status",1);
+        if($isMenu) {
+            $info = $info->where("admin_menus.display",1);
+        }
+        $info = $info
+                     ->orderBy('admin_menus.sort', 'desc')->orderBy('admin_menus.id', 'asc')
+                     ->groupby(\DB::raw("admin_menus.id"))
+                     ->get();
+        return $info->toArray();
+    }
+}

+ 41 - 0
app/Models/AdminMenusModel.php

xqd
@@ -0,0 +1,41 @@
+<?php
+/**
+ *------------------------------------------------------
+ * AdminMenusModel.php
+ *------------------------------------------------------
+ *
+ * @author    m@9026.com
+ * @date      2017/03/20 11:43
+ * @version   V1.0
+ *
+ */
+
+namespace App\Models;
+
+class AdminMenusModel extends BaseModel
+{
+    /**
+     * 数据表名
+     */
+    protected $table = "admin_menus";
+
+    /**
+     * 主键
+     */
+    protected $primaryKey = "id";
+
+    /**
+     * 可以被集体附值的表的字段
+     */
+    protected $fillable = [
+        'pid',
+        'path',
+        'name',
+        'display',
+        'sort',
+        'level',
+        'ico',
+        'mark'
+    ];
+
+}

+ 34 - 0
app/Models/AdminRoleModel.php

xqd
@@ -0,0 +1,34 @@
+<?php
+/**
+ *------------------------------------------------------
+ * AdminRoleModel.php
+ *------------------------------------------------------
+ *
+ * @author    m@9026.com
+ * @date      2017/03/20 11:43
+ * @version   V1.0
+ *
+ */
+
+namespace App\Models;
+
+class AdminRoleModel extends BaseModel
+{
+    /**
+     * 数据表名
+     */
+    protected $table = "admin_roles";
+
+    /**
+     * 主键
+     */
+    protected $primaryKey = "id";
+
+    /**
+     * 可以被集体附值的表的字段
+     */
+    protected $guarded = [];
+
+
+
+}

+ 66 - 0
app/Models/AdminUserModel.php

xqd
@@ -0,0 +1,66 @@
+<?php
+/**
+ *------------------------------------------------------
+ * AdminUserModel.php
+ *------------------------------------------------------
+ *
+ * @author    m@9026.com
+ * @date      2017/03/21 10:15
+ * @version   V1.0
+ *
+ */
+
+namespace App\Models;
+
+use Illuminate\Foundation\Auth\User as Authenticatable;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Auth;
+use Illuminate\Support\Facades\Validator;
+
+class AdminUserModel extends Authenticatable
+{
+    /**
+     * 数据表名
+     */
+    protected $table = "admin_users";
+
+    /**
+     * 主键
+     */
+    protected $primaryKey = "id";
+
+    protected $guarded = [];
+
+    public function getValidator(Request $request, $type)
+    {
+        if ($type == 'store') {
+            $validator = Validator::make($request->input('data'), [
+                'name' => 'required'
+            ], [
+                'name.required' => '账号必填'
+            ]);
+        } else if ($type == 'change-password') {
+            $validator = Validator::make($request->input('data'), [
+                'old_password' => 'required',
+                'password' => 'required|min:6|confirmed'
+            ], [
+                'old_password.required' => '请填写原来密码',
+                'password.required' => '密码必填,且不能少于6位',
+                'password.min' => '密码必填,且不能少于6位',
+                'password.confirmed' => '两次填写的密码不一致'
+            ]);
+        } else {
+            $validator = Validator::make($request->input('data'), [
+                'name' => 'required'
+            ], [
+                'name.required' => '账号必填'
+            ]);
+        }
+        return $validator;
+    }
+
+    public function adminRole()
+    {
+        return $this->belongsTo('App\Models\AdminRoleModel', 'admin_role_id');
+    }
+}

+ 43 - 0
app/Models/BaseAreaModel.php

xqd
@@ -0,0 +1,43 @@
+<?php
+/**
+ *------------------------------------------------------
+ * BaseAreaModel.php
+ *------------------------------------------------------
+ *
+ * @author    m@9026.com
+ * @date      2017/03/20 13:09
+ * @version   V1.0
+ *
+ */
+
+namespace App\Models;
+
+class BaseAreaModel extends BaseModel
+{
+    /**
+     * 数据表名
+     */
+    protected $table = "base_area";
+
+    /**
+     * 主键
+     */
+    protected $primaryKey = "id";
+
+    /**
+     * 可以被集体附值的表的字段
+     */
+    protected $fillable = [
+        'name',
+        'pid',
+        'short_name',
+        'grade',
+        'city_code',
+        'zip_code',
+        'merger_name',
+        'lng',
+        'lat',
+        'pinyin'
+    ];
+
+}

+ 32 - 0
app/Models/BaseAttachmentModel.php

xqd
@@ -0,0 +1,32 @@
+<?php
+/**
+ *------------------------------------------------------
+ * BaseAttachmentModel.php
+ *------------------------------------------------------
+ *
+ * @author    m@9026.com
+ * @date      2017/03/20 13:09
+ * @version   V1.0
+ *
+ */
+
+namespace App\Models;
+
+class BaseAttachmentModel extends BaseModel
+{
+    //
+    /**
+     * 数据表名
+     *
+     * @var string
+     *
+     */
+    protected $table = 'base_attachments';
+    /**
+    主键
+     */
+    protected $primaryKey = 'id';
+
+    //分页
+    protected $perPage = PAGE_NUMS;
+}

+ 40 - 0
app/Models/BaseDictionaryModel.php

xqd
@@ -0,0 +1,40 @@
+<?php
+/**
+ *------------------------------------------------------
+ * BaseDictionaryOptionModel.php
+ *------------------------------------------------------
+ *
+ * @author    m@9026.com
+ * @date      2017/03/20 13:09
+ * @version   V1.0
+ *
+ */
+
+namespace App\Models;
+
+class BaseDictionaryModel extends BaseModel
+{
+    /**
+     * 数据表名
+     */
+    protected $table = "base_dictionary";
+
+    /**
+     * 主键
+     */
+    protected $primaryKey = "id";
+
+    /**
+     * 可以被集体附值的表的字段
+     */
+    protected $fillable = [
+        'dictionary_table_code',
+        'dictionary_code',
+        'key',
+        'value',
+        'name',
+        'input_code',
+        'sort'
+    ];
+
+}

+ 104 - 0
app/Models/BaseModel.php

xqd
@@ -0,0 +1,104 @@
+<?php
+/**
+ *------------------------------------------------------
+ * Model层基类
+ *------------------------------------------------------
+ *
+ * @author    qqiu@qq.com
+ * @date      2016/05/26 09:22
+ * @version   V1.0
+ *
+ */
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Validator;
+
+class BaseModel extends Model
+{
+    /**
+     * 维护数据表中 created_at 和 updated_at 字段
+     */
+    public $timestamps = true;
+
+    protected $statusOptions = [
+        ['id' => 1, 'name' => '未激活', 'color' => 'gray'],
+        ['id' => 2, 'name' => '激活', 'color' => 'blue'],
+        ['id' => 3, 'name' => '禁用', 'color' => 'red']
+    ];
+
+    /**
+     * 多个Where
+     * @param Object $query
+     * @param array $arr ['status' => 1, 'type' => 2]
+     * @return Object $query
+     */
+    public function multiwhere($query, $arr)
+    {
+        if ( !is_array($arr) ) {
+            return $query;
+        }
+        foreach ($arr as $key => $value) {
+            $query = $query->where($key, $value);
+        }
+        return $query;
+    }
+    public function getValidator(Request $request, $type)
+    {
+        if($type == 'store') {
+            $validator = Validator::make($request->input('data'), [
+                'name' => 'required'
+            ], [
+                'name.required' => '名称必填'
+            ]);
+        } else {
+            $validator = Validator::make($request->input('data'), [
+                'name' => 'required'
+            ], [
+                'name.required' => '名称必填'
+            ]);
+        }
+        return $validator;
+    }
+
+    public function getOptions()
+    {
+        return $this->where('id', '>', 0)->orderBy('sort')->get()->toArray();
+    }
+
+    public function getStatusOptions()
+    {
+        return $this->statusOptions;
+    }
+
+    /*
+     * type: name|label
+     */
+    public function getStatus($type = 'name') {
+        $options = $this->statusOptions;
+        $option = $options[0];
+        foreach($options as $item) {
+            if($item['id'] == $this['status']) {
+                $option = $item;
+                break;
+            }
+        }
+        if($type == 'name') return $option['name'];
+        else return '<div class="layui-badge layui-bg-' . $option['color'] . '">' . $option['name'] . '</div>';
+    }
+
+    public function getNameOrLabel($options = [], $type = 'name', $name = 'status')
+    {
+        $option = $options[0];
+        foreach($options as $item) {
+            if($item['id'] == $this[$name]) {
+                $option = $item;
+                break;
+            }
+        }
+        if($type == 'name') return $option['name'];
+        else return '<div class="layui-badge layui-bg-' . $option['color'] . '">' . $option['name'] . '</div>';
+    }
+}

+ 22 - 0
app/Models/ClassModel.php

xqd
@@ -0,0 +1,22 @@
+<?php
+
+namespace App\Models;
+use App\Models\BaseModel;
+
+class ClassModel extends BaseModel
+{
+    /**
+     * 数据表名
+     *
+     * @var string
+     *
+     */
+    protected $table = 'classes';
+    /**
+    主键
+     */
+    protected $primaryKey = 'id';
+
+    //分页
+    protected $perPage = PAGE_NUMS;
+}

+ 58 - 0
app/Models/UserInfoModel.php

xqd
@@ -0,0 +1,58 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Foundation\Auth\User as Authenticatable;
+use Laravel\Passport\HasApiTokens;
+
+/**
+ * @description 用户表
+ * @author  system;
+ * @version    1.0
+ * @date 2017-05-30 12:16:56
+ *
+ */
+class UserInfoModel extends Authenticatable
+{
+    use HasApiTokens;
+    /**
+     * 数据表名
+     *
+     * @var string
+     *
+     */
+    protected $table = 'user_info';
+    /**
+     * 主键
+     */
+    protected $primaryKey = 'id';
+
+    //分页
+    protected $perPage = PAGE_NUMS;
+
+    /**
+     * 可以被集体附值的表的字段
+     *
+     * @var string
+     */
+    protected $fillable = [
+        'password',
+        'email',
+        'area',
+        'name',
+        'vip',
+        'level',
+        'idcard',
+        'contact',
+        'prize',
+        'openid',
+        'remember_token',
+        'idcard_positive',
+        'idcard_back',
+        'username',
+        'real_name',
+        'email',
+        'mobile'
+    ];
+
+}

+ 28 - 0
app/Providers/AppServiceProvider.php

xqd
@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Providers;
+
+use Illuminate\Support\ServiceProvider;
+
+class AppServiceProvider extends ServiceProvider
+{
+    /**
+     * Bootstrap any application services.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        //
+    }
+
+    /**
+     * Register any application services.
+     *
+     * @return void
+     */
+    public function register()
+    {
+        //
+    }
+}

+ 31 - 0
app/Providers/AuthServiceProvider.php

xqd
@@ -0,0 +1,31 @@
+<?php
+
+namespace App\Providers;
+
+use Laravel\Passport\Passport;
+use Illuminate\Support\Facades\Gate;
+use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
+
+class AuthServiceProvider extends ServiceProvider
+{
+    /**
+     * The policy mappings for the application.
+     *
+     * @var array
+     */
+    protected $policies = [
+        'App\Model' => 'App\Policies\ModelPolicy',
+    ];
+
+    /**
+     * Register any authentication / authorization services.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        $this->registerPolicies();
+
+        Passport::routes();
+    }
+}

+ 21 - 0
app/Providers/BroadcastServiceProvider.php

xqd
@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Providers;
+
+use Illuminate\Support\ServiceProvider;
+use Illuminate\Support\Facades\Broadcast;
+
+class BroadcastServiceProvider extends ServiceProvider
+{
+    /**
+     * Bootstrap any application services.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        Broadcast::routes();
+
+        require base_path('routes/channels.php');
+    }
+}

+ 32 - 0
app/Providers/EventServiceProvider.php

xqd
@@ -0,0 +1,32 @@
+<?php
+
+namespace App\Providers;
+
+use Illuminate\Support\Facades\Event;
+use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
+
+class EventServiceProvider extends ServiceProvider
+{
+    /**
+     * The event listener mappings for the application.
+     *
+     * @var array
+     */
+    protected $listen = [
+        'App\Events\SomeEvent' => [
+            'App\Listeners\EventListener',
+        ],
+    ];
+
+    /**
+     * Register any events for your application.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        parent::boot();
+
+        //
+    }
+}

+ 82 - 0
app/Providers/RouteServiceProvider.php

xqd
@@ -0,0 +1,82 @@
+<?php
+
+namespace App\Providers;
+
+use Illuminate\Support\Facades\Route;
+use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
+
+class RouteServiceProvider extends ServiceProvider
+{
+    /**
+     * This namespace is applied to your controller routes.
+     *
+     * In addition, it is set as the URL generator's root namespace.
+     *
+     * @var string
+     */
+    protected $namespace = 'App\Http\Controllers';
+
+    /**
+     * Define your route model bindings, pattern filters, etc.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        //
+
+        parent::boot();
+    }
+
+    /**
+     * Define the routes for the application.
+     *
+     * @return void
+     */
+    public function map()
+    {
+        $this->mapApiRoutes();
+
+        $this->mapWebRoutes();
+
+        //后台路由
+        $this->mapAdminRoutes();
+    }
+
+    public function mapAdminRoutes()
+    {
+        Route::prefix('admin')
+            ->middleware('web')
+            ->namespace($this->namespace. '\Admin')
+            ->group(base_path('routes/admin.php'));
+    }
+
+    /**
+     * Define the "web" routes for the application.
+     *
+     * These routes all receive session state, CSRF protection, etc.
+     *
+     * @return void
+     */
+    protected function mapWebRoutes()
+    {
+        Route::middleware('web')
+             ->namespace($this->namespace)
+             ->group(base_path('routes/web.php'));
+    }
+
+    /**
+     * Define the "api" routes for the application.
+     *
+     * These routes are typically stateless.
+     *
+     * @return void
+     */
+    protected function mapApiRoutes()
+    {
+        Route::prefix('api')
+             ->middleware('api')
+             ->namespace($this->namespace)
+             ->group(base_path('routes/api.php'));
+    }
+}

+ 14 - 0
app/Repositories/Base/Criteria.php

xqd
@@ -0,0 +1,14 @@
+<?php
+namespace App\Repositories\Base;
+
+use App\Repositories\Contracts\RepositoryInterface as BaseRepository;
+
+abstract class Criteria {
+
+    /**
+     * @param $model
+     * @param Repository $repository
+     * @return mixed
+     */
+    public abstract function apply($model, BaseRepository $repository);
+}

+ 45 - 0
app/Repositories/Base/Criteria/MultiWhere.php

xqd
@@ -0,0 +1,45 @@
+<?php
+/**
+ * User: Mike
+ * Email: m@9026.com
+ * Date: 2017/1/12
+ * Time: 17:52
+ */
+
+namespace App\Repositories\Base\Criteria;
+
+
+
+
+use App\Repositories\Base\Criteria;
+use App\Repositories\Contracts\RepositoryInterface as Repository;
+
+class MultiWhere extends Criteria {
+
+    private $search = [];
+
+    /**
+     * MultiWhere constructor.
+     * @param array $search
+     *
+     */
+    public function __construct(array $search)
+    {
+        $this->search = $search;
+    }
+
+    /**
+    * @param $model
+    * @param RepositoryInterface $repository
+    * @return mixed
+    */
+    public function apply($model, Repository $repository)
+    {
+          if(isset($this->search['deleted_at']) && $this->search['deleted_at']) {
+                                    $model = $model->where('deleted_at',$this->search['deleted_at']);
+                                 }
+
+         return $model;
+    }
+
+}

+ 52 - 0
app/Repositories/Base/Criteria/OrderBy.php

xqd
@@ -0,0 +1,52 @@
+<?php
+/**
+ * User: Mike
+ * Email: m@9026.com
+ * Date: 2017/1/12
+ * Time: 17:52
+ */
+
+namespace App\Repositories\Base\Criteria;
+
+
+
+
+use App\Repositories\Base\Criteria;
+use App\Repositories\Contracts\RepositoryInterface as Repository;
+
+class OrderBy extends Criteria {
+
+    private $field = '';
+    private $sort = 'ASC';
+
+    /**
+     * MultiWhere constructor.
+     * @param array $search
+     *
+     *               id  商品ID
+     *               name 商品名称(模糊查询)
+     *               cate_id 分类ID
+     *               store_id 商家ID
+     *               store_name 商家名称(模糊查询)
+     *
+     *
+     *
+     */
+    public function __construct($field,$sort="ASC")
+    {
+        $this->field = $field;
+        $this->sort = $sort;
+    }
+
+    /**
+     * @param $model
+     * @param RepositoryInterface $repository
+     * @return mixed
+     */
+    public function apply($model, Repository $repository)
+    {
+        $model = $model->orderBy($this->field,$this->sort);
+        return $model;
+    }
+
+}

+ 21 - 0
app/Repositories/Base/DictionaryRepository.php

xqd
@@ -0,0 +1,21 @@
+<?php
+/**
+ *   字典管理
+ *  @author  system
+ *  @version    1.0
+ *  @date 2018-06-12 10:14:19
+ *
+ */
+namespace App\Repositories\Base;
+
+use App\Repositories\Base\Repository;
+
+
+class DictionaryRepository extends Repository {
+
+    public function model() {
+        return \App\Models\BaseDictionaryModel::class;
+    }
+
+    
+}

+ 358 - 0
app/Repositories/Base/Repository.php

xqd
@@ -0,0 +1,358 @@
+<?php
+
+namespace App\Repositories\Base;
+
+use Illuminate\Support\Collection;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Container\Container as App;
+use App\Repositories\Contracts\RepositoryInterface;
+use App\Repositories\Exceptions\RepositoryException;
+use App\Repositories\Contracts\CriteriaInterface;
+use App\Repositories\Base\Criteria;
+
+/**
+ * Class Repository
+ * @package Bosnadev\Repositories\Eloquent
+ */
+abstract class Repository implements RepositoryInterface, CriteriaInterface
+{
+
+    /**
+     * @var App
+     */
+    private $app;
+
+    /**
+     * @var Model
+     */
+    protected $model;
+
+    protected $newModel;
+
+    /**
+     * @var Collection
+     */
+    protected $criteria;
+
+    /**
+     * @var bool
+     */
+    protected $skipCriteria = false;
+
+    /**
+     * Prevents from overwriting same criteria in chain usage
+     * @var bool
+     */
+    protected $preventCriteriaOverwriting = true;
+
+    /**
+     * @param App $app
+     * @param Collection $collection
+     * @throws Exceptions\RepositoryException
+     */
+    public function __construct(App $app, Collection $collection)
+    {
+        $this->app = $app;
+        $this->criteria = $collection;
+        $this->resetScope();
+        $this->makeModel();
+    }
+
+    /**
+     * Specify Model class name
+     *
+     * @return mixed
+     */
+    public abstract function model();
+
+    /**
+     * @param array $columns
+     * @return mixed
+     */
+    public function all($columns = array('*'))
+    {
+        $this->applyCriteria();
+        return $this->model->get($columns);
+    }
+
+    /**
+     * @param array $relations
+     * @return $this
+     */
+    public function with(array $relations)
+    {
+        $this->model = $this->model->with($relations);
+        return $this;
+    }
+
+    /**
+     * @param  string $value
+     * @param  string $key
+     * @return array
+     */
+    public function lists($value, $key = null)
+    {
+        $this->applyCriteria();
+        $lists = $this->model->lists($value, $key);
+        if (is_array($lists)) {
+            return $lists;
+        }
+        return $lists->all();
+    }
+
+    /**
+     * @param int $perPage
+     * @param array $columns
+     * @return mixed
+     */
+    public function paginate($perPage = 25, $columns = array('*'))
+    {
+        $this->applyCriteria();
+        return $this->model->paginate($perPage, $columns);
+    }
+
+    /**
+     * @param array $data
+     * @return mixed
+     */
+    public function create(array $data)
+    {
+        return $this->model->create($data);
+    }
+
+    /**
+     * save a model without massive assignment
+     *
+     * @param array $data
+     * @return bool
+     */
+    public function saveModel(array $data)
+    {
+        foreach ($data as $k => $v) {
+            $this->model->$k = $v;
+        }
+        return $this->model->save();
+    }
+
+    /**
+     * @param array $data
+     * @param $id
+     * @param string $attribute
+     * @return mixed
+     */
+    public function update($id,array $data, $attribute = "id")
+    {
+        return $this->model->where($attribute, '=', $id)->update($data);
+    }
+
+    /**
+     * @param  array $data
+     * @param  $id
+     * @return mixed
+     */
+    public function updateRich( $id,array $data)
+    {
+        if (!($model = $this->model->find($id))) {
+            return false;
+        }
+
+        return $model->fill($data)->save();
+    }
+
+    /**
+     * @param $id
+     * @return mixed
+     */
+    public function delete($id)
+    {
+        return $this->model->destroy($id);
+    }
+    /**
+     * @param $id
+     * @return mixed
+     */
+    public function destroy($id)
+    {
+        $data = $this->model->find($id);
+        if ( $data->delete()) {
+            return true;
+        }else
+            return false;
+    }
+    /**
+     * @param $id
+     * @param array $columns
+     * @return mixed
+     */
+    public function find($id, $columns = array('*'))
+    {
+        $this->applyCriteria();
+        return $this->model->find($id, $columns);
+    }
+
+    /**
+     * @param $attribute
+     * @param $value
+     * @param array $columns
+     * @return mixed
+     */
+    public function findBy($attribute, $value, $columns = array('*'))
+    {
+        $this->applyCriteria();
+        return $this->model->where($attribute, '=', $value)->first($columns);
+    }
+
+    /**
+     * @param $attribute
+     * @param $value
+     * @param array $columns
+     * @return mixed
+     */
+    public function findAllBy($attribute, $value, $columns = array('*'))
+    {
+        $this->applyCriteria();
+        return $this->model->where($attribute, '=', $value)->get($columns);
+    }
+
+    /**
+     * Find a collection of models by the given query conditions.
+     *
+     * @param array $where
+     * @param array $columns
+     * @param bool $or
+     *
+     * @return \Illuminate\Database\Eloquent\Collection|null
+     */
+    public function findWhere($where, $columns = ['*'], $or = false)
+    {
+        $this->applyCriteria();
+
+        $model = $this->model;
+
+        foreach ($where as $field => $value) {
+            if ($value instanceof \Closure) {
+                $model = (!$or)
+                    ? $model->where($value)
+                    : $model->orWhere($value);
+            } elseif (is_array($value)) {
+                if (count($value) === 3) {
+                    list($field, $operator, $search) = $value;
+                    $model = (!$or)
+                        ? $model->where($field, $operator, $search)
+                        : $model->orWhere($field, $operator, $search);
+                } elseif (count($value) === 2) {
+                    list($field, $search) = $value;
+                    $model = (!$or)
+                        ? $model->where($field, '=', $search)
+                        : $model->orWhere($field, '=', $search);
+                }
+            } else {
+                $model = (!$or)
+                    ? $model->where($field, '=', $value)
+                    : $model->orWhere($field, '=', $value);
+            }
+        }
+        return $model->get($columns);
+    }
+
+    /**
+     * @return \Illuminate\Database\Eloquent\Builder
+     * @throws RepositoryException
+     */
+    public function makeModel()
+    {
+        return $this->setModel($this->model());
+    }
+
+    /**
+     * Set Eloquent Model to instantiate
+     *
+     * @param $eloquentModel
+     * @return Model
+     * @throws RepositoryException
+     */
+    public function setModel($eloquentModel)
+    {
+        $this->newModel = $this->app->make($eloquentModel);
+
+        if (!$this->newModel instanceof Model)
+            throw new RepositoryException("Class {$this->newModel} must be an instance of Illuminate\\Database\\Eloquent\\Model");
+
+        return $this->model = $this->newModel;
+    }
+
+    /**
+     * @return $this
+     */
+    public function resetScope()
+    {
+        $this->skipCriteria(false);
+        return $this;
+    }
+
+    /**
+     * @param bool $status
+     * @return $this
+     */
+    public function skipCriteria($status = true)
+    {
+        $this->skipCriteria = $status;
+        return $this;
+    }
+
+    /**
+     * @return mixed
+     */
+    public function getCriteria()
+    {
+        return $this->criteria;
+    }
+
+    /**
+     * @param Criteria $criteria
+     * @return $this
+     */
+    public function getByCriteria(Criteria $criteria)
+    {
+        $this->model = $criteria->apply($this->model, $this);
+        return $this;
+    }
+
+    /**
+     * @param Criteria $criteria
+     * @return $this
+     */
+    public function pushCriteria(Criteria $criteria)
+    {
+        if ($this->preventCriteriaOverwriting) {
+            // Find existing criteria
+            $key = $this->criteria->search(function ($item) use ($criteria) {
+                return (is_object($item) && (get_class($item) == get_class($criteria)));
+            });
+
+            // Remove old criteria
+            if (is_int($key)) {
+                $this->criteria->offsetUnset($key);
+            }
+        }
+
+        $this->criteria->push($criteria);
+        return $this;
+    }
+
+    /**
+     * @return $this
+     */
+    public function applyCriteria()
+    {
+        if ($this->skipCriteria === true)
+            return $this;
+
+        foreach ($this->getCriteria() as $criteria) {
+            if ($criteria instanceof Criteria)
+                $this->model = $criteria->apply($this->model, $this);
+        }
+
+        return $this;
+    }
+}

+ 41 - 0
app/Repositories/Contracts/CriteriaInterface.php

xqd
@@ -0,0 +1,41 @@
+<?php
+
+namespace App\Repositories\Contracts;
+
+use App\Repositories\Base\Criteria;
+
+/**
+ * Interface CriteriaInterface
+ * @package Bosnadev\Repositories\Contracts
+ */
+interface CriteriaInterface {
+
+    /**
+     * @param bool $status
+     * @return $this
+     */
+    public function skipCriteria($status = true);
+
+    /**
+     * @return mixed
+     *
+     */
+    public function getCriteria();
+
+    /**
+     * @param Criteria $criteria
+     * @return $this
+     */
+    public function getByCriteria(Criteria $criteria);
+
+    /**
+     * @param Criteria $criteria
+     * @return $this
+     */
+    public function pushCriteria(Criteria $criteria);
+
+    /**
+     * @return $this
+     */
+    public function  applyCriteria();
+}

+ 78 - 0
app/Repositories/Contracts/RepositoryInterface.php

xqd
@@ -0,0 +1,78 @@
+<?php
+namespace App\Repositories\Contracts;
+
+/**
+ * Interface RepositoryInterface
+ * @package Bosnadev\Repositories\Contracts
+ */
+interface RepositoryInterface {
+
+//    /**
+//     * @param array $columns
+//     * @return mixed
+//     */
+    public function all($columns = array('*'));
+//
+//    /**
+//     * @param $perPage
+//     * @param array $columns
+//     * @return mixed
+//     */
+    public function paginate($perPage = 1, $columns = array('*'));
+//
+//    /**
+//     * @param array $data
+//     * @return mixed
+//     */
+//    public function create(array $data);
+//
+//    /**
+//     * @param array $data
+//     * @return bool
+//     */
+//    public function saveModel(array $data);
+//
+//    /**
+//     * @param array $data
+//     * @param $id
+//     * @return mixed
+//     */
+    public function update($id,array $data);
+//
+//    /**
+//     * @param $id
+//     * @return mixed
+//     */
+//    public function delete($id);
+//
+//    /**
+//     * @param $id
+//     * @param array $columns
+//     * @return mixed
+//     */
+    public function find($id, $columns = array('*'));
+//
+//    /**
+//     * @param $field
+//     * @param $value
+//     * @param array $columns
+//     * @return mixed
+//     */
+    public function findBy($field, $value, $columns = array('*'));
+//
+//    /**
+//     * @param $field
+//     * @param $value
+//     * @param array $columns
+//     * @return mixed
+//     */
+//    public function findAllBy($field, $value, $columns = array('*'));
+//
+//    /**
+//     * @param $where
+//     * @param array $columns
+//     * @return mixed
+//     */
+//    public function findWhere($where, $columns = array('*'));
+
+}

+ 48 - 0
app/Repositories/User/Criteria/MultiWhere.php

xqd
@@ -0,0 +1,48 @@
+<?php
+/**
+ * User: Mike
+ * Email: m@9026.com
+ * Date: 2017/1/12
+ * Time: 17:52
+ */
+
+namespace App\Repositories\User\Criteria;
+
+
+
+
+use App\Repositories\Base\Criteria;
+use App\Repositories\Contracts\RepositoryInterface as Repository;
+
+class MultiWhere extends Criteria {
+
+    private $search = [];
+
+    /**
+     * MultiWhere constructor.
+     * @param array $search
+     *
+     */
+    public function __construct(array $search)
+    {
+        $this->search = $search;
+    }
+
+    /**
+    * @param $model
+    * @param RepositoryInterface $repository
+    * @return mixed
+    */
+    public function apply($model, Repository $repository)
+    {
+        if(isset($this->search['keyword']) && ! empty($this->search['keyword'])) {
+            $keywords = '%' . $this->search['keyword'] . '%';
+            $model = $model->where(function ($query) use ($keywords) {
+                $query->where('id'  , 'like', $keywords)
+                    ->orwhere('mobile', 'like', $keywords);
+            });
+        }
+        return $model;
+    }
+
+}

+ 21 - 0
app/Repositories/User/InfoRepository.php

xqd
@@ -0,0 +1,21 @@
+<?php
+/**
+ *   用户表
+ *  @author  system
+ *  @version    1.0
+ *  @date 2017-05-30 12:16:56
+ *
+ */
+namespace App\Repositories\User;
+
+use App\Repositories\Base\Repository;
+
+
+class InfoRepository extends Repository {
+
+    public function model() {
+        return \App\Models\UserInfoModel::class;
+    }
+
+    
+}

+ 128 - 0
app/Services/Admin/Acl.php

xqd
@@ -0,0 +1,128 @@
+<?php
+/**
+ *  
+ *  @author  Mike <m@9026.com>
+ *  @version    1.0
+ *  @date 2015年11月13日
+ *
+ */
+namespace App\Services\Admin;
+
+use App\Services\Base\BaseProcess;
+use App\Models\AdminAccessModel;
+use App\Models\AdminMenusModel;
+
+class Acl extends BaseProcess {
+    
+    private $objModel;
+    private $menusModel;
+    /**
+     * 初始化
+     *
+     * @access public
+     *
+     */
+    public function __construct()
+    {
+        if( ! $this->objModel) $this->objModel = new AdminAccessModel();
+        if( ! $this->menusModel) $this->menusModel = new AdminMenusModel();
+    }
+    
+    public function checkFunc($module,$contrl,$action) {
+        
+    }
+    
+    
+    public function getRoleFunc($roleIds) {
+        $data =$this->objModel->getRoleAccessMenu($roleIds);
+        if(!$data) {
+              return array('menus'=>array(),'func'=>array());
+        }
+        $arr = array('/'=>'0','Foundation/Index/index'=>501,'Foundation/Index/welcome'=>502,'Foundation/Login/logout'=>503);
+        foreach ($data as $val) {
+            $arr[$val['path']] = $val['id'];
+        }
+        return array('menus'=>$data,'func'=>$arr);
+            ;
+    }
+    
+    public function getRoleMenu($roleIds) {
+        $data =$this->objModel->getRoleAccessMenu($roleIds,true);
+        if(!$data) {
+            return array();
+        }
+        return $data;
+    }
+    
+    
+    public function getRootFunc() {
+        $data =$this->menusModel->select('id','pid','path','name','display','level','ico')->orderBy('sort','desc')->get()->toArray();
+        if(!$data) {
+            return array('menus'=>array(),'func'=>array());
+        }
+        $arr = array('/'=>'0','Foundation/Index/index'=>501,'Foundation/Index/welcome'=>502,'Foundation/Login/logout'=>503);
+        foreach ($data as $val) {
+            $arr[$val['path']] = $val['id'];
+        }
+        return array('menus'=>$data,'func'=>$arr);
+    }
+    /**
+     * 获取角色权限ID
+     * @param unknown $roleId
+     */
+   public function getAccessIDs($roleId) {
+       $data = $this->objModel->select("menu_id")->where("role_id",$roleId)->get();
+       $arr = array();
+       if($data) {
+            foreach ($data as $val) {
+                $arr[] = $val['menu_id'];
+            }
+       }
+       return $arr;
+   }
+   /**
+    * 
+    * @param unknown $roleId
+    * @param unknown $menuIds
+    * @param string $allMenus 权限范围,如果为false不验证
+    */
+   public function setRole($roleId,$menuIds,$allMenus=false) {
+       
+       try
+       {
+           $result = \DB::transaction(function() use ($roleId, $menuIds,$allMenus)
+           {
+               $ok = $this->objModel->where("role_id",$roleId)->delete();
+               if($ok===false) {
+                  throwException("删除出错");
+               }
+               foreach ($menuIds as $menu_id) {
+                   if($allMenus !== false) {
+                       if(!in_array($menu_id, $allMenus)) {
+                           throwException("涉及到越权操作");
+                       }
+                   }
+                   $add['role_id'] = $roleId;
+                   $add['menu_id'] = $menu_id;
+                   
+                   $ok = $this->objModel->create($add);
+                   if(!$ok) {
+                       throwException("添加出错");
+                   }
+               }
+              
+               return true;
+           });
+       }
+       catch (\Exception $e)
+       {
+           $result = false;
+       }
+       
+       if( ! $result) return $this->setMsg('操作失败');
+       
+       return true;
+   }
+   
+    
+}

+ 288 - 0
app/Services/Admin/AdminUser.php

xqd
@@ -0,0 +1,288 @@
+<?php
+/**
+ *  用户操作
+ *  @author  Mike <m@9026.com>
+ *  @version    1.0
+ *  @date 2015年11月13日
+ *
+ */
+namespace App\Services\Admin;
+use App\Models\AdminUserModel;
+use Hash;
+use App\Services\Base\BaseProcess;
+
+class AdminUser extends BaseProcess
+{
+    /**
+     * 模型
+     *
+     * @var object
+     *
+     */
+    private $objModel;
+
+    /**
+     * 初始化
+     */
+    public function __construct()
+    {
+        if( !$this->objModel) $this->objModel = new AdminUserModel();
+    }
+
+    public function model()
+    {
+        $this->setSucessCode();
+        return $this->objModel;
+    }
+
+    /**
+     * 搜索
+     * @param $search
+     * @param $pagesize
+     */
+    public function search($search, $orderby = array(), $pagesize = PAGE_NUMS)
+    {
+        $currentQuery = $this->objModel;
+        if(isset($search['keyword']) && !empty($search['keyword'])) {
+            $keywords = '%' . $search['keyword'] . '%';
+            $currentQuery = $currentQuery->where(function ($query) use ($keywords) {
+                $query->where('name'  , 'like', $keywords)
+                    ->orwhere('email', 'like', $keywords)
+                    ->orwhere('mobile', 'like', $keywords);
+            });
+        }
+        if(isset($search['resetPwd']) && $search['resetPwd']) {
+
+            $currentQuery = $currentQuery->where('reset_password', '<>', '');
+        }
+
+        if($orderby && is_array($orderby)){
+            foreach ($orderby AS $field => $value){
+                $currentQuery = $currentQuery -> orderBy($field, $value);
+            }
+        }else{
+            $currentQuery = $currentQuery->orderBy('id', 'DESC');
+        }
+        $currentQuery = $currentQuery->paginate($pagesize);
+        return $currentQuery;
+    }
+
+    /**
+     * 添加
+     * @param $data
+     */
+    public function create($data)
+    {
+        // 判断是否唯一
+        if($this->objModel->where('name', '=', $data['name'])->count()){
+            $this->setMsg("已经存在【{$data['name']}】用户!");
+            return false;
+        }
+        $data['name'] = isset($data['name']) ? $data['name'] : "";
+        $data['email'] = isset($data['email']) ? $data['email'] : "";
+        $data['mobile'] = isset($data['mobile']) ? $data['mobile'] : "";
+        $data['real_name'] = isset($data['real_name']) ? $data['real_name'] : "";
+        if($data['name']== "" && $data['email']=="" && $data['mobile']=="") {
+            $this->setMsg("至少有一个登陆凭证");
+            return false;
+        }
+        if(isset($data['name']) && $data['name']) {
+            if(is_numeric($data['name'])) {
+                $this->setMsg("用户名不能是全数字!");
+                return false;
+            }
+            if(strpos($data['name'],"@")) {
+                $this->setMsg("用户名不能有@符号!");
+                return false;
+            }
+            if($this->objModel->where('name', '=', $data['name'])->count()){
+                $this->setMsg("已经存在的用户名!");
+                return false;
+            }
+        }
+        if(isset($data['email']) && $data['email']) {
+            if($this->objModel->where('email', '=', $data['email'])->count()){
+                $this->setMsg("已经存在的邮箱!");
+                return false;
+            }
+        }
+        if(isset($data['mobile']) && $data['mobile']) {
+            if($this->objModel->where('mobile', '=', $data['mobile'])->count()){
+                $this->setMsg("已经存在的手机号!");
+                return false;
+            }
+        }
+        if(isset($data['password']) && $data['password']){
+            $data['password'] = bcrypt($data['password']);
+        }
+
+        return $this->objModel->create($data);
+    }
+
+    /**
+     * 更新
+     * @param $id
+     * @param $data
+     */
+    public function update($id, $data)
+    {
+        $obj = $this->objModel->find($id);
+        if(!$obj) {
+            return false;
+        }
+        if(isset($data['real_name']) && $data['real_name']){
+            $data['real_name'] = $data['real_name'];
+        }
+        if(isset($data['password']) && $data['password']){
+            $data['password'] = bcrypt($data['password']);
+        }
+        if(isset($data['name']) && $data['name']) {
+            if(is_numeric($data['name'])) {
+                $this->setMsg("用户名不能是全数字!");
+                return false;
+            }
+            if(strpos($data['name'],"@")) {
+                $this->setMsg("用户名不能有@符号!");
+                return false;
+            }
+            if($this->objModel->where('name', '=', $data['name'])->where('id',"<>",$id)->count()){
+                $this->setMsg("已经存在的用户名!");
+                return false;
+            }
+        }
+        if(isset($data['email']) && $data['email']) {
+            if($this->objModel->where('email', '=', $data['email'])->where('id',"<>",$id)->count()){
+                $this->setMsg("已经存在的邮箱!");
+                return false;
+            }
+        }
+        if(isset($data['mobile']) && $data['mobile']) {
+            if($this->objModel->where('mobile', '=', $data['mobile'])->where('id',"<>",$id)->count()){
+                $this->setMsg("已经存在的手机号!");
+                return false;
+            }
+        }
+        $ok = $obj->update($data);
+        return $ok;
+    }
+
+    /**
+     * 更新状态
+     * @param $id
+     * @param $status
+     */
+    public function updateStatus($id, $status)
+    {
+        $data = $this->objModel->find($id);
+        //禁用
+        $mobile = $data->mobile;
+        $data->status = $status;
+        return $data->save();
+    }
+
+    /**
+     * 删除
+     * @param $id
+     */
+    public function destroy($id)
+    {
+        return $this->objModel->destroy($id);
+    }
+
+    /**
+     * 获取一行数据
+     * @param $where
+     * @return
+     */
+    public function find($id)
+    {
+        return $this->objModel->find($id);
+    }
+
+
+    public function login($login,$password) {
+        if(is_numeric($login)) {
+            $loginField = "mobile";
+        }elseif(strpos($login,"@")) {
+            $loginField = "email";
+        }else{
+            $loginField = "name";
+        }
+        if (\Auth::guard('admin')->attempt(array($loginField => $login, 'password' =>$password)))
+        {
+            $data =  \Auth::guard('admin')->user();
+            if($data->status==0) {
+                $this->setMsg('账号正在努力审核中...');
+                return false;
+            }
+            if(!$data->status) {
+                $this->setMsg('账号被禁用');
+                return false;
+            }
+            $role = [];
+            if($data->is_root) {
+                $aclObj = new Acl();
+                $data =  $aclObj->getRootFunc();
+                $role['role'] =$data['func'];
+                $role['menus'] =$data['menus'];
+            }elseif($data->admin_role_id) {
+                $aclObj = new Acl();
+                $data =  $aclObj->getRoleFunc($data->admin_role_id);
+                $role['role'] =$data['func'];
+                $role['menus'] =$data['menus'];
+            }
+            session()->put(LOGIN_MARK_SESSION_KEY, $role);
+            session()->save();
+            return true;
+        }else{
+            $this->setMsg('用户密码错误');
+            return false;
+        }
+    }
+
+    /**
+     * 重设密码
+     * @param $loginName
+     * @param $data
+     */
+    public function resetPwd($loginName,$data) {
+        if(is_numeric($loginName)) {
+            $loginField = "mobile";
+        }elseif(strpos($loginName,"@")) {
+            $loginField = "email";
+        }else{
+            $loginField = "username";
+        }
+        $user = $this->objModel->where($loginField,$loginName)->first();
+        if(!$user) {
+            $this->setMsg('没有找到用户');
+            return false;
+        }
+        $user->reset_password = bcrypt($data['reset_password']);
+        $user->reset_password_img = $data['reset_password_img'];
+        $ok = $user->save();
+        if(!$ok) {
+            $this->setMsg('操作失败');
+            return false;
+        }
+        return true;
+    }
+
+
+    /**
+     * 查询多条数据
+     */
+    public function get($pagesize = PAGE_NUMS) {
+        return $this->objModel->take($pagesize)->orderBy('id', 'DESC')->get();
+    }
+
+
+    /**
+     * 查询多条数据并分页
+     */
+    public function getPage($pagesize = PAGE_NUMS) {
+        return $this->objModel->orderBy('id', 'DESC')->paginate($pagesize);
+    }
+
+
+}

+ 150 - 0
app/Services/Admin/Menus.php

xqd
@@ -0,0 +1,150 @@
+<?php
+/**
+ *------------------------------------------------------
+ * Menus.php
+ *------------------------------------------------------
+ *
+ * @author    qqiu@qq.com
+ * @date      2016/12/19 11:31
+ * @version   V1.0
+ *
+ */
+
+namespace App\Services\Admin;
+
+use App\Services\Base\BaseProcess;
+use App\Models\AdminMenusModel;
+use App\Services\Base\Tree;
+
+class Menus extends BaseProcess {
+
+    /**
+     * 模型
+     */
+    private $_model;
+
+    /**
+     * 初始化
+     */
+    public function __construct()
+    {
+        if( ! $this->_model) $this->_model = new AdminMenusModel();
+    }
+
+    public function model() {
+        $this->setSucessCode();
+        return $this->_model;
+    }
+
+    public function find($id) {
+        return $this->_model->find($id);
+    }
+
+    /**
+     * 添加
+     * @param unknown $data
+     */
+    public function create($data)
+    {
+        return $this->_model->create($data);
+    }
+
+    /**
+     * 更新
+     * @param unknown $id
+     * @param unknown $data
+     */
+    public function update($id,$data)
+    {
+        $obj = $this->_model->find($id);
+        if(!$obj) {
+            return false;
+        }
+        $ok = $obj->update($data);
+        return $ok;
+    }
+
+    /**
+     * 删除
+     * @param unknown $id
+     */
+    public function destroy($id)
+    {
+        return $this->_model->destroy($id);
+    }
+
+    /**
+     * 获取当前菜单层级
+     * @param $pid
+     * @return level
+     */
+    public function getLevel($id)
+    {
+        $tree = new Tree();
+        $MenusArr = $this->_model->orderBy('sort', 'DESC')->get()->toArray();
+        $tree->init($MenusArr);
+        $allParents = $tree->getPos($id);
+        return count($allParents);
+    }
+
+    /**
+     * 获取菜单树状结构
+     */
+    public function getMenusTree($search = array()){
+
+        $currentQuery = $this->_model;
+        if(isset($search['keyword']) && !empty($search['keyword'])) {
+            $keywords = '%' . $search['keyword'] . '%';
+            $currentQuery = $currentQuery->where(function ($query) use ($keywords) {
+                $query->where('name'  , 'like', $keywords)
+//                    ->orwhere('module', 'like', $keywords)
+                    ->orwhere('path', 'like', $keywords)
+                    ->orwhere('mark', 'like', $keywords);
+            });
+        }
+
+        $MenusArr = $currentQuery->orderBy('sort', 'DESC')->get()->toArray();
+        $tree = new Tree();
+        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
+        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
+        $tree->init($MenusArr);
+        return $tree->getTree();
+    }
+
+    /**
+     * 搜索
+     * @param $search
+     * @param $pagesize
+     */
+    public function search($search,$orderby=array('sort'=>'desc'),$pagesize = PAGE_NUMS)
+    {
+        $currentQuery = $this->_model;
+        if(isset($search['keyword']) && !empty($search['keyword'])) {
+            $keywords = '%' . $search['keyword'] . '%';
+            $currentQuery = $currentQuery->where(function ($query) use ($keywords) {
+                $query->where('name'  , 'like', $keywords)
+                    ->orwhere('module', 'like', $keywords)
+                    ->orwhere('contrl', 'like', $keywords);
+            });
+        }
+        if(isset($search['min_level']) && !empty($search['min_level'])) {
+            $currentQuery = $currentQuery->where('level','<=',$search['min_level']);
+        }
+        if(isset($search['display']) && !empty($search['display'])) {
+            $currentQuery = $currentQuery->where('display',$search['display']);
+        }
+        if($orderby) {
+            foreach ($orderby as $key=>$sort) {
+                $currentQuery = $currentQuery->orderBy($key,$sort);
+            }
+        }
+        if($pagesize){
+            $currentQuery = $currentQuery->paginate($pagesize);
+        }else{
+            $currentQuery = $currentQuery->get();
+        }
+        return $currentQuery;
+    }
+
+
+}

+ 181 - 0
app/Services/Admin/Role.php

xqd
@@ -0,0 +1,181 @@
+<?php
+/**
+ *  用户角色
+ *  @author  qqiu@qq.com
+ *  @version    1.0
+ *  @date 2015年10月9日
+ *
+ */
+namespace App\Services\Admin;
+
+use App\Services\Base\BaseProcess;
+use App\Models\AdminRoleModel;
+
+class Role extends BaseProcess
+{
+    /**
+     * 模型
+     *
+     * @var object
+     * 
+     */
+    private $objModel;
+    
+    /**
+     * 初始化
+     */
+    public function __construct()
+    {
+        if( !$this->objModel) $this->objModel = new AdminRoleModel();
+    }
+    
+    public function model()
+    {
+        $this->setSucessCode();
+        return $this->objModel;
+    }
+    
+    /**
+     * 搜索
+     * @param $search
+     * @param $pagesize
+     */
+    public function search($search, $orderby, $pagesize = PAGE_NUMS)
+    {
+        $currentQuery = $this->objModel;
+        if(isset($search['keyword']) && !empty($search['keyword'])) {
+            $keywords = '%' . $search['keyword'] . '%';
+            $currentQuery = $currentQuery->where(function ($query) use ($keywords) {
+                $query->where('name'  , 'like', $keywords)
+                ->orwhere('mark', 'like', $keywords);
+            });
+        }
+        
+        if(isset($search['department_ids']) && !empty($search['department_ids'])) {
+            $department_ids = $search['department_ids'];
+            $currentQuery = $currentQuery->where(function ($query) use ($department_ids) {
+                $query->whereIn('department_id', $department_ids);
+            });
+        }
+        
+        if($orderby && is_array($orderby)){
+            foreach ($orderby AS $field => $value){
+                $currentQuery = $currentQuery -> orderBy($field, $value);
+            }
+        }else{
+            $currentQuery = $currentQuery->orderBy('id', 'DESC');
+        }
+        
+        $currentQuery = $currentQuery->where('level', '>=', $search['level'])->paginate($pagesize);
+        return $currentQuery;
+    }
+
+    /**
+     * 添加
+     * @param $data
+     */
+    public function create($data)
+    {
+        return $this->objModel->create($data);
+    }
+    
+    /**
+     * 更新
+     * @param $id
+     * @param $data
+     */
+    public function update($id, $data)
+    {
+        $obj = $this->objModel->find($id);
+        if(!$obj) {
+            return false;
+        }
+        $ok = $obj->update($data);
+        return $ok;
+    }
+    
+    /**
+     * 更新状态
+     * @param $id
+     * @param $status
+     */
+    public function updateStatus($id, $status)
+    {
+        $data = $this->objModel->find($id);
+        $data->status = $status;
+        return $data->save();
+    }
+    
+    /**
+     * 删除
+     * @param $id
+     */
+    public function destroy($id)
+    {
+        return $this->objModel->destroy($id);
+    }
+    
+    /**
+     * 获取一行数据
+     * @param $where
+     * @return
+     */
+    public function find($id)
+    {
+        return $this->objModel->find($id);
+    }
+    
+    /**
+     * 获取角色权限节点(level越小权限越大)
+     */
+    public function getLevelNode($role_ids)
+    {
+        $role_ids = is_array($role_ids) ? $role_ids : explode(',', $role_ids);
+        return $this->objModel->whereIn('id', $role_ids)->take(1)->orderBy('level', 'ASC')->first();
+    }
+    
+    /**
+     * 根据状态查询数据
+     */
+    public function getValidData($status = 1)
+    {
+        return $this->objModel->where('status', $status)->orderBy('id', 'DESC')->get();
+    }
+    
+    /**
+     * 查询多条数据
+     */
+    public function get($pagesize = PAGE_NUMS) {
+        return $this->objModel->take($pagesize)->orderBy('level', 'ASC')->get();
+    }
+    
+    /**
+     * 查询多条数据并分页
+     */
+    public function getPage($pagesize = PAGE_NUMS) {
+        return $this->objModel->orderBy('id', 'DESC')->paginate($pagesize);
+    }
+    
+    /**
+     * 获取子等级数据
+     */
+    public function getChildByLevel($level, $departmentIds=array())
+    {
+        $currentQuery = $this->objModel;
+        $currentQuery = $currentQuery->where('level', '>=', $level);
+        $currentQuery = $currentQuery->where('status', '=', 1);
+        if($departmentIds){
+            $currentQuery = $currentQuery->whereIn('department_id', $departmentIds);
+        }
+        return $currentQuery = $currentQuery->orderBy('level', 'ASC')->get();
+    }
+    
+    /**
+     * 根据部门ID获取角色个数
+     */
+    public function getCountByDepartmentId($department_id)
+    {
+        return $this->objModel->where('department_id', '=', $department_id)->count();
+    }
+    
+}

+ 58 - 0
app/Services/Base/AbstractService.php

xqd
@@ -0,0 +1,58 @@
+<?php
+/**
+ *------------------------------------------------------
+ * AbstractService.php
+ *------------------------------------------------------
+ *
+ * @author    qqiu@qq.com
+ * @date      2016/5/26 11:17
+ * @version   V1.0
+ *
+ */
+
+namespace App\Services\Base;
+
+abstract class AbstractService
+{
+
+    protected $_code = FAILURE_CODE;
+
+    /**
+     * 错误的信息载体
+     */
+    protected $_msg;
+
+    /**
+     * 取回错误的信息
+     */
+    public function getMsg()
+    {
+        return $this->_msg;
+    }
+
+    /**
+     * 设置错误的信息
+     */
+    public function setMsg($msg)
+    {
+        $this->_msg = $msg;
+        return false;
+    }
+
+    /**
+     * 设置状态码
+     */
+    public function setCode($code)
+    {
+        $this->_code = $code;
+    }
+
+    /**
+     * 标记为成功
+     */
+    public function setSucessCode()
+    {
+        $this->setCode(SUCESS_CODE);
+    }
+
+}

+ 309 - 0
app/Services/Base/Attachment.php

xqd
@@ -0,0 +1,309 @@
+<?php
+/**
+ *------------------------------------------------------
+ * BaseProcess.php
+ *------------------------------------------------------
+ *
+ * @author    Mike
+ * @date      2016/5/26 11:17
+ * @version   V1.0
+ *
+ */
+
+namespace App\Services\Base;
+
+use App\Models\BaseAttachmentModel;
+use App\Services\OSS;
+use Response;
+use App\Models\BaseSettingsModel;
+use Image;
+class Attachment
+{
+    private $_model;
+
+    public function __construct() {
+        if( !$this->_model ) $this->_model = new BaseAttachmentModel();
+    }
+
+    public function aliUpload($field, $request, $tag = 'files', $size = 10 * 1024 * 1024, array $mimeType = ['image/jpeg', 'image/png', 'image/gif','video/mp4','video/quicktime']){
+        $class = isset($request['class']) ? $request['class'] : '未分类';
+        $sizex = isset($request['sizex']) ? $request['sizex'] : 0;
+        $sizey = isset($request['sizey']) ? $request['sizey'] : 0;
+
+        $file = $request[$field];
+        if ($file === null) {
+            return $this->_jsonMessage(500,  ['message' => '没有文件被上传']);
+        }
+        if (!$file->isValid()) {
+            return $this->_jsonMessage(500,  ['message' => '不允许上传']);
+        }
+
+        $fileSize = $file->getSize();
+        if ($fileSize > $size) {
+            return $this->_jsonMessage(500,  ['message' => '文件大小超过限制']);
+        }
+        $fileMimeType = $file->getMimeType();
+        if (!empty($mimeType) && !in_array($fileMimeType, $mimeType)) {
+            return $this->_jsonMessage(500,  ['message' => '文件格式不被允许']);
+        }
+        $clientName = $file->getClientOriginalName();
+        $md5 = md5($clientName . time());
+        $md5_filename = $md5 . '.' . $file->getClientOriginalExtension();
+
+        if(isset($request['from']) && $request['from'] == 'crop') {
+            $clientName = isset($request['name']) ? $request['name'] : '裁剪.png';
+            $md5_filename = $md5_filename . 'png';
+        }
+
+        $file_Path = $file->getRealPath();
+        try {
+            $ok = OSS::publicUpload(config('alioss.BucketName'),$md5_filename, $file_Path);
+
+            if(!$ok){
+                return $this->_jsonMessage(500,  ['message' => '上传失败']);
+            }
+
+            $attachment = new BaseAttachmentModel();
+            $attachment->name = $clientName;
+            $attachment->md5 = $md5;
+            $attachment->path = config('alioss.FileUrl').$md5_filename;
+            $attachment->url = config('alioss.FileUrl').$md5_filename;
+            $attachment->size = $fileSize;
+            $attachment->file_type = $fileMimeType;
+            $attachment->class = $class;
+            if ($attachment->save()) {
+                return $this->_jsonMessage(200,  ['message' => "上传成功", 'fileurl' => config('alioss.FileUrl').$md5_filename,'name'=>$md5_filename]);
+            } else {
+                OSS::publicDeleteObject(config('alioss.BucketName'),$md5_filename);
+                return $this->_jsonMessage(500,  ['message' => '数据库保存错误']);
+            }
+        } catch (FileException $e) {
+            return $this->_jsonMessage(500,  ['message' => '保存失败']);
+
+        }
+
+    }
+
+    public function specialUpload(){
+
+    }
+
+
+    public function _uploadfiles(){
+
+    }
+
+
+    public function _jsonMessage($status,$ret){
+        $ret['code'] = $status;
+        return $ret;
+    }
+
+
+    /**
+     * 上传附件
+     *
+     * @param string|array $field 文件key
+     * @param Request $request  laravel's http request
+     * @param string $tag       文件tag
+     * @param int $size         文件size限制,默认2M
+     * @param array $mimeType   文件mime类型限制,默认不限
+     * @return array|string|int 返回:md5字串|ErrorCode或[md5字串|ErrorCode]
+     */
+
+
+    public function localUpload($field, $request, $tag = 'files', $size = 10 * 1024 * 1024, array $mimeType = ['image/jpeg', 'image/png', 'image/gif','video/mp4','video/quicktime'])
+    {
+
+        $tag = $request['folder'];
+        $class = isset($request['class']) ? $request['class'] : '未分类';
+        $sizex = isset($request['sizex']) ? $request['sizex'] : 0;
+        $sizey = isset($request['sizey']) ? $request['sizey'] : 0;
+        $rel_path = '/upload/images/'.$tag . '/' . date('Ymd');
+        $path = public_path() . $rel_path;
+        // dd($request);
+        if (!file_exists($path)) {
+            if (!@mkdir($path, 0755, true)) {
+//              return ErrorCode::ATTACHMENT_MKDIR_FAILED;
+                return $this->_jsonMessage(500,  ['message' => '目录创建失败']);
+            }
+        }
+        \Log::info($request);
+        $file = $request[$field];
+
+        if ($file === null) {
+            return $this->_jsonMessage(500,  ['message' => '没有文件被上传']);
+        }
+        if (!$file->isValid()) {
+            return $this->_jsonMessage(500,  ['message' => '不允许上传']);
+        }
+
+        $fileSize = $file->getSize();
+        if ($fileSize > $size) {
+//            $result[$idx] = ErrorCode::ATTACHMENT_SIZE_EXCEEDED;
+            return $this->_jsonMessage(500,  ['message' => '文件大小超过限制']);
+        }
+        $fileMimeType = $file->getMimeType();
+        if (!empty($mimeType) && !in_array($fileMimeType, $mimeType)) {
+            return $this->_jsonMessage(500,  ['message' => '文件格式不被允许']);
+        }
+        $clientName = $file->getClientOriginalName();
+        $md5 = md5($clientName . time());
+        $md5_filename = $md5 . '.' . $file->getClientOriginalExtension();
+
+        if(isset($request['from']) && $request['from'] == 'crop') {
+            $clientName = isset($request['name']) ? $request['name'] : '裁剪.png';
+            $md5_filename = $md5_filename . 'png';
+        }
+
+        try {
+            if(!$file->move($path, $md5_filename)){
+                return $this->_jsonMessage(500,  ['message' => '上传失败']);
+            }
+
+            $real_path = $path . '/' . $md5_filename;
+            $url_path = $rel_path . '/' . $md5_filename;
+
+            $source_info = null;
+            if(($source_info = getimagesize($real_path)) != null) {
+                $source_width = $source_info[0];
+                $source_height = $source_info[1];
+                \Log::info('$source_width'.$source_width.'$source_height'.$source_height);
+
+                if($sizex || $sizey){
+                    if($sizex==0){
+                        $sizex = $source_width*($sizey/$source_height);
+                    }
+                    if($sizey==0){
+                        $sizey = $source_height*($sizex/$source_width);
+                    }
+                    \Log::info('$sizex'.$sizex.'$sizey'.$sizey);
+                    Image::make($real_path)->resize($sizex, $sizey)->save($real_path);
+                }
+
+            }
+
+            $attachment = new BaseAttachmentModel();
+            $attachment->name = $clientName;
+            $attachment->md5 = $md5;
+            $attachment->path = $real_path;
+            $attachment->url = $url_path;
+            $attachment->size = $fileSize;
+            $attachment->file_type = $fileMimeType;
+            $attachment->class = $class;
+            if ($attachment->save()) {
+                return $this->_jsonMessage(200,  ['message' => "上传成功", 'fileurl' => $url_path,'name'=>$md5_filename]);
+
+            } else {
+                @unlink($real_path);
+                return $this->_jsonMessage(500,  ['message' => '数据库保存错误']);
+//                $result= ErrorCode::ATTACHMENT_SAVE_FAILED;
+            }
+        } catch (FileException $e) {
+            return $this->_jsonMessage(500,  ['message' => '上传失败']);
+//            $result = ErrorCode::ATTACHMENT_MOVE_FAILED;
+        }
+    }
+
+    /**
+     * 删除附件
+     *
+     * @param $md5 string 删除文件的md5码
+     * @return int 错误码or 0(成功)
+     */
+    public function deleteAttachment($md5) {
+        $attachment = $this->_model->where(['md5' => $md5])->first();
+        if (!$attachment) {
+            return ErrorCode::ATTACHMENT_NOT_EXIST;
+        }
+        if (file_exists($attachment->path)) {
+            if (@unlink($attachment->path)) {
+                if ($attachment->delete()) {
+                    return 0;
+                } else {
+                    return ErrorCode::ATTACHMENT_RECORD_DELETE_FAILED;
+                }
+            } else {
+                return ErrorCode::ATTACHMENT_DELETE_FAILED;
+            }
+        } else {
+            return ErrorCode::ATTACHMENT_NOT_EXIST;
+        }
+
+    }
+
+    public function fileUpload($field, $request, $tag = 'files', $size = 10 * 1024 * 1024, array $mimeType = ['image/jpeg', 'image/png', 'image/gif','video/mp4','video/quicktime','text/plain']){
+        $tag = $request['folder'];
+        $class = isset($request['class']) ? $request['class'] : '未分类';
+        $sizex = isset($request['sizex']) ? $request['sizex'] : 0;
+        $sizey = isset($request['sizey']) ? $request['sizey'] : 0;
+        $rel_path = $tag . '/' . date('Ymd');
+        $path = public_path() . $rel_path;
+        // dd($request);
+        if (!file_exists($path)) {
+            if (!@mkdir($path, 0755, true)) {
+//              return ErrorCode::ATTACHMENT_MKDIR_FAILED;
+                return $this->_jsonMessage(500,  ['message' => '目录创建失败']);
+            }
+        }
+
+        $file = $request[$field];
+        if ($file === null) {
+            return $this->_jsonMessage(500,  ['message' => '没有文件被上传']);
+        }
+        if (!$file->isValid()) {
+            return $this->_jsonMessage(500,  ['message' => '不允许上传']);
+        }
+
+        $fileSize = $file->getSize();
+        if ($fileSize > $size) {
+//            $result[$idx] = ErrorCode::ATTACHMENT_SIZE_EXCEEDED;
+            return $this->_jsonMessage(500,  ['message' => '文件大小超过限制']);
+        }
+        $fileMimeType = $file->getMimeType();
+
+        if (!empty($mimeType) && !in_array($fileMimeType, $mimeType)) {
+            return $this->_jsonMessage(500,  ['message' => '文件格式不被允许']);
+        }
+        $clientName = $file->getClientOriginalName();
+        $md5 = md5($clientName . time());
+        $md5_filename = $md5 . '.' . $file->getClientOriginalExtension();
+
+        if(isset($request['from']) && $request['from'] == 'crop') {
+            $clientName = isset($request['name']) ? $request['name'] : '裁剪.png';
+            $md5_filename = $md5_filename . 'png';
+        }
+
+        try {
+            if(!$file->move($path, $md5_filename)){
+                return $this->_jsonMessage(500,  ['message' => '上传失败']);
+            }
+
+            $real_path = $path . '/' . $md5_filename;
+            $url_path = $rel_path . '/' . $md5_filename;
+
+            $source_info = null;
+            if(($source_info = getimagesize($real_path)) != null) {
+                $source_width = $source_info[0];
+                $source_height = $source_info[1];
+                \Log::info('$source_width'.$source_width.'$source_height'.$source_height);
+                if($sizex || $sizey){
+                    if($sizex==0){
+                        $sizex = $source_width*($sizey/$source_height);
+                    }
+                    if($sizey==0){
+                        $sizey = $source_height*($sizex/$source_width);
+                    }
+                    \Log::info('$sizex'.$sizex.'$sizey'.$sizey);
+                    Image::make($real_path)->resize($sizex, $sizey)->save($real_path);
+                }
+            }
+
+            return $this->_jsonMessage(200,  ['message' => "上传成功", 'fileurl' => $url_path,'name'=>$md5_filename]);
+
+        } catch (FileException $e) {
+            return $this->_jsonMessage(500,  ['message' => '上传失败']);
+        }
+    }
+
+}

+ 18 - 0
app/Services/Base/BaseProcess.php

xqd
@@ -0,0 +1,18 @@
+<?php
+/**
+ *------------------------------------------------------
+ * BaseProcess.php
+ *------------------------------------------------------
+ *
+ * @author    qqiu@qq.com
+ * @date      2016/5/26 11:17
+ * @version   V1.0
+ *
+ */
+
+namespace App\Services\Base;
+
+abstract class BaseProcess extends AbstractService
+{
+
+}

+ 145 - 0
app/Services/Base/DictData.php

xqd
@@ -0,0 +1,145 @@
+<?php
+/**
+ *------------------------------------------------------
+ * 全局数据字典的调用,提供配置缓存的类型
+ *------------------------------------------------------
+ *
+ * @author    qqiu@qq.com
+ * @date      2016/5/26 11:17
+ * @version   V1.0
+ *
+ */
+
+namespace App\Services\Base;
+
+use App\Models\BaseDictDataModel;
+use Illuminate\Support\Facades\Cache;
+
+class DictData
+{
+    private $_dict;
+    private $_model;
+    private $_mmCache = 'table_dict_data_all';
+
+    public function __construct() {
+        if( !$this->_model ) $this->_model = new BaseDictDataModel();
+    }
+
+    /**
+     * 取得数据字典对应数据
+     *
+     * @param string $table_code 数据字典的类型
+     * @param string $code 数据字典代码
+     * @param string $val 数据字典数据对应下标
+     * @return array  返回数据字典数组
+     * @throws CException  $table_code, $code 不能为空
+     *
+     */
+    public function get($table_code, $code, $val = null)
+    {
+        $mKey = Cache::get($this->_mmCache);
+        if(isset($mKey[$table_code][$code])) {
+            $arr = $mKey[$table_code][$code];
+        }else{
+            $this->updateCache();
+            if(isset($this->_dict[$table_code][$code])) {
+                $arr = $this->_dict[$table_code][$code];
+            }else{
+                $arr = [];
+            }
+        }
+        if(!$arr) {
+            return null;
+        }
+        if(isset($val)) {
+            if(array_key_exists($val, $arr)) {
+                return $arr[$val];
+            }else{
+                return '';
+            }
+        }else{
+            return $arr;
+        }
+    }
+
+    /**
+     * 创建Select代码
+     *
+     * @param string $table_code 数据字典的类型
+     * @param string $code 数据字典代码
+     * @param string $selection 被选中的值。
+     * @param array $htmlOptions
+     * 额外的HTML属性:如 [name=>'cate', id=>'cate'] 这些属性作用在select上。
+     * 若使用特定关键字empty时,自动创建一个option,
+     *     empty: 字符串,指定空选项的文本,它的值为空。
+     *     empty: 数组,option的value值对应key,文本对应value。
+     */
+    public function select($table_code, $code, $selection = null, $htmlOptions = [])
+    {
+        $selectOption = $htmlOptions;
+        unset($selectOption['empty']);
+        $html = "<select";
+        foreach($selectOption as $key => $val) {
+            $html .= " {$key}=\"{$val}\"";
+        }
+        $html .= ">\n";
+        if (isset ( $htmlOptions ['empty'] )) {
+            $value = "";
+            $label = $htmlOptions ['empty'];
+            if (is_array ( $label )) {
+                $value = array_keys ( $label );
+                $value = $value [0];
+                $label = array_values ( $label );
+                $label = $label [0];
+            }
+            $html .= "<option value=\"{$value}\">{$label}</option>\n";
+        }
+        $optionHtml = $this->option($table_code, $code, $selection);
+        $html .= $optionHtml;
+        $html .= "</select>";
+        return $html;
+    }
+
+    /**
+     * 创建select的option选项
+     *
+     * @param $table_code
+     * @param $code
+     * @param null $selection
+     * @return string
+     */
+    public function option($table_code, $code, $selection = null)
+    {
+        $data = $this->get($table_code, $code);
+        $html = "";
+        foreach ($data as $k => $v) {
+            $html .= "<option value=\"{$k}\"";
+            if($k == $selection) {
+                $html .= " selected ";
+            }
+            $html .= ">{$v}</option>\n";
+        }
+        return $html;
+    }
+
+    /**
+     * 更新对应数据字典,如参数都为空全部更新
+     *
+     * @param string $table_code 需要更新的类型
+     * @param string $code 需要更新的代码
+     * @return bool  返回成功失败
+     * @throws CException
+     */
+    public function updateCache()
+    {
+        $obData = $this->_model->all();
+        $dict = array();
+        foreach($obData as $key => $value) {
+            $dict[$value->dict_table_code][$value->dict_code][$value->value] = $value->name;
+        }
+        $this->_dict = $dict;
+        Cache::forever($this->_mmCache, $this->_dict);
+        return true;
+    }
+
+}

+ 207 - 0
app/Services/Base/Dictionary.php

xqd
@@ -0,0 +1,207 @@
+<?php
+namespace App\Services\Base;
+
+use Illuminate\Support\Facades\Cache;
+use App\Models\BaseDictionaryModel;
+use App\Models\BaseAreaModel;
+/**
+ *  全局数据字典的调用
+ *  
+ *  提供配置缓存的类型
+ *  
+ *  @author  wangzhoudong  <admin@zhen.pl>
+ *  @version    1.0
+ *
+ */
+class Dictionary {
+
+	public $cacheType;
+	
+	private $ckey_length = 4;
+	private $mmCache = 'table_dictionary_option_all';
+	
+	private $dict;
+	
+	public function __construct() {
+		
+	}
+	/**
+	 * 取得数据字典对应数据
+	 *
+	 * @author wangzhoudong
+	 * @param string $table_code 数据字典的类型
+	 * @param string $code 数据字典代码
+	 * @param string $val 数据字典数据对应下标
+	 * @return array  返回数据字典数组
+	 * @throws CException  $table_code,$code 不能为空
+	 *
+	 */
+	
+	public function get($table_code,$code,$val=null) {
+		$mKey = Cache::get($this->mmCache);
+		if(isset($mKey[$table_code][$code])) {
+			$arr =  $mKey[$table_code][$code];
+		}else{
+			$this->update($table_code,$code);
+			if(isset($this->dict[$table_code][$code])) {
+				$arr =  $this->dict[$table_code][$code];
+			}else{
+				$arr = [];
+			}
+		}
+	    if(!$arr) {
+	        return null;
+	    }
+		if($val !== null) {
+
+			if(array_key_exists($val, $arr)) {
+				return $arr[$val];
+			}else{
+				return '';
+			}
+		}else{
+			return $arr;
+		}
+	}
+	
+	/**
+	 * 获取地区数据名称
+	 * @param int $areaId
+	 * $start 排除前面的层级
+	 */
+	public function areaName($areaId,$spec=" ",$start=1) {
+	    if(!$areaId) {
+	        return '';
+	    }
+	    $objArea = new BaseAreaModel();
+	    $sMerger = "";
+	    $arr = $objArea->select("merger_name")->find($areaId);
+	    if(isset($arr->merger_name)) {
+	        $aMerger = explode(',',$arr->merger_name);
+	         
+	        for($i=1,$j=count($aMerger);$i<$j;$i++) {
+	            $sMerger .= $spec . $aMerger[$i];
+	        }
+	        if($sMerger) {
+	            $sMerger =  substr($sMerger,strlen($spec));
+	        }
+	    }
+	    return $sMerger;
+	}
+	
+	public function area($areaId) {
+	    if(!$areaId) {
+	        return '';
+	    }
+	    $objArea = new BaseAreaModel();
+	    $arr = $objArea->find($areaId);
+	    if($arr) {
+	        $arr = $arr->toArray();
+	    }
+	    return $arr;
+	}
+	/**
+	 * 
+ 	 * @param string $table_code 数据字典的类型
+	 * @param string $code 数据字典代码
+	 * @param string $selection 被选中的值。
+	 * @param array $htmlOptions  额外的HTML属性。如name='cate' ,id='cate'下面两个特定的属性是被认可: 
+	 * 						      empty: 字符串,指定空选项的文本,它的值为空。
+	 * 							       'empty'选项也可以是一个值-标签对形式的数组。
+	 * 							                  在一开始每个对都会用于渲染一个列表的选项。注意,
+	 *  							       文本标签不会被HTML编码。 
+     *
+	 * 
+	 */
+	public function select($table_code, $code, $selection=null, $htmlOptions=array()) {
+		$selectOption = $htmlOptions;
+		unset($selectOption['empty']);
+		$html = "<select ";
+		foreach($htmlOptions as $key=>$val) {
+			$html .= " $key='$val'";
+		}
+		$html .= ' >';
+		if (isset ( $htmlOptions ['empty'] )) {
+			$value = "";
+			$label = $htmlOptions ['empty'];
+			if (is_array ( $label )) {
+				$value = array_keys ( $label );
+				$value = $value [0];
+				$label = array_values ( $label );
+				$label = $label [0];
+			}
+			$html .= '<option value="' . $value . '">' . ($label) . "</option>\n";
+		}
+		$optionHtml =  $this->option($table_code, $code,$selection);
+		$html .= $optionHtml;
+     	$html .= "</select>";
+		return $html;
+	}
+	
+	public function option($table_code,$code,$selection=null) {
+	    $data = $this->get($table_code,$code);
+	    $html = "";
+	    foreach ($data as $k=>$v) {
+	        $html .= "<option value='$k'";
+	        if($k==$selection) {
+	            $html .= " selected";
+	        }
+	        $html .= ">$v</option>";
+	    }
+	    return $html;
+	}
+	
+	/**
+	 * 更新对应数据字典,如参数都为空全部更新
+	 * 
+	 * @author wangzhoudong
+	 * @param string $table_code 需要更新的类型
+	 * @param string $code 需要更新的代码
+	 * @return bool  返回成功失败
+	 * @throws CException
+	 * 
+	 */
+	public function update($table_code=null,$code=null) {
+		
+		$oBaseDictionary = new BaseDictionaryModel();
+		
+		$oData = $oBaseDictionary->all();
+		$dict = array();
+		foreach($oData as $key=>$value) {
+			$dict[$value->dictionary_table_code][$value->dictionary_code][$value->value] = $value->name;
+		}
+		$this->dict = $dict;
+		Cache::forever($this->mmCache,$this->dict);
+		return true;	
+	}
+
+	/**
+	 * 获取联动数据
+	 * @param $table_code
+	 * @param $code
+	 */
+	public function linkageData($table_code, $code)
+	{
+		$array = [];
+		$oBaseDictionary = new BaseDictionaryModel();
+		$data = $oBaseDictionary
+			->where("dictionary_table_code", $table_code)
+			->where("dictionary_code", $code)
+			->where("key", "")
+			->orderBy("sort", "DESc")
+			->get()->toArray();
+		foreach($data AS $key => $item){
+			$array[$key] = $item;
+			$array[$key]['childs'] = $oBaseDictionary
+				->where("dictionary_table_code", $table_code)
+				->where("dictionary_code", $code)
+				->where("key", $item['value'])
+				->orderBy("sort", "DESc")
+				->get()->toArray();
+		}
+		return $array;
+	}
+
+}
+
+?>

+ 128 - 0
app/Services/Base/ErrorCode.php

xqd
@@ -0,0 +1,128 @@
+<?php
+/**
+ *------------------------------------------------------
+ * BaseProcess.php
+ *------------------------------------------------------
+ *
+ * @author    Mike
+ * @date      2016/5/26 11:17
+ * @version   V1.0
+ *
+ */
+
+namespace App\Services\Base;
+
+final class ErrorCode {
+    //错误常量定义
+    const ATTACHMENT_DELETE_FAILED = 605;
+    const ATTACHMENT_MOVE_FAILED = 604;
+    const ATTACHMENT_RECORD_DELETE_FAILED = 606;
+    const ATTACHMENT_MKDIR_FAILED = 601;
+    const SAVE_USER_FAILED = 600;
+    const ATTACHMENT_SAVE_FAILED = 603;
+    const ATTACHMENT_UPLOAD_INVALID = 602;
+    const ATTACHMENT_SIZE_EXCEEDED = 1201;
+    const ILLEGAL_REQUEST = 701;
+    const ATTACHMENT_NOT_EXIST = 1203;
+    const ATTACHMENT_MIME_NOT_ALLOWED = 1202;
+    const MERCHANT_CREDIT_NOT_ENOUGH = 1304;
+    const MEMBER_CREDIT_NOT_ENOUGH = 1305;
+    const MERCHANT_NOT_EXIST = 1300;
+    const FAVORITE_NOT_EXIST = 1900;
+    const MERCHANT_ADD_MEMBER_FAILED = 1301;
+    const MERCHANT_STATUS_NOT_OK = 1302;
+    const MERCHANT_BALANCE_NOT_ENOUGH = 1303;
+    const PAY_TYPE_UNSUPPORTED = 2000;
+    const MEMBER_NOT_EXIST = 1500;
+    const MEMBER_BALANCE_NOT_ENOUGH = 1501;
+    const MERCHANT_SERVICE_NOT_EXIST = 1400;
+    const MERCHANT_SERVICE_ADD_FAILED = 1401;
+    const CONTENT_GET_DETAIL_FAILED = 1402;
+    const MERCHANT_SERVICE_STATUS_INVALID = 1403;
+    const MERCHANT_SERVICE_EXPIRED = 1404;
+    const CANT_ADD_SERVICE_SAME_MERCHANT = 1405;
+    const SERVICE_STATUS_INVALID_CHANGE = 1406;
+    const SERVICE_COST_OVERFLOW_BALANCE = 1407;
+    const CREATE_SERVICE_OVER_MAX = 1408;
+    const SAVE_MODEL_FAILED = 700;
+    const REMOVE_MODEL_FAILED = 701;
+    const MODEL_NOT_EXIST = 702;
+    const ATTACHMENT_UPLOAD_FAILED = 1200;
+    const PROTO_PATH_NOT_EXIST = 100;
+    const PROTO_TRY_TO_SET_VALUE_ON_NULL = 101;
+    const ACTIVITY_NOT_EXIST = 1700;
+    const ORDER_GENERATE_FAILED = 1800;
+    const CONSUME_LOG_NOT_EXIST = 1600;
+    const SERVICE_CODE_FAILED= 1610;
+    const PHONE_NUMBER_ALREADY_REGISTERED = 1100;
+    const INCORRECT_VERIFY_CODE = 1101;
+    const INCORRECT_USER_OR_PASS = 1102;
+    const VERIFY_CODE_TOO_MUCH = 1103;
+    const LOGOUT_FAILED = 1104;
+    const USER_DOES_NOT_EXIST = 1105;
+    const USER_DOES_EXIST = 1106;
+    const DELETE_OP_FAILED = 1001;
+    const CLIENT_WRONG_PARAMS = 1000;
+
+    //错误常量枚举
+    private static $_msg = [
+        self::ATTACHMENT_DELETE_FAILED => '删除附件文件失败',
+        self::ATTACHMENT_MOVE_FAILED => '移动附件失败',
+        self::ATTACHMENT_RECORD_DELETE_FAILED => '删除附件记录失败',
+        self::ATTACHMENT_MKDIR_FAILED => '创建附件目录失败',
+        self::SAVE_USER_FAILED => '保存用户数据失败',
+        self::ATTACHMENT_SAVE_FAILED => '保存附件失败',
+        self::ATTACHMENT_UPLOAD_INVALID => '上传附件文件无效',
+        self::ATTACHMENT_SIZE_EXCEEDED => '附件大小超过限制',
+        self::ILLEGAL_REQUEST => '非法请求',
+        self::ATTACHMENT_NOT_EXIST => '附件不存在',
+        self::ATTACHMENT_MIME_NOT_ALLOWED => '附件类型不允许',
+        self::MEMBER_CREDIT_NOT_ENOUGH => '会员卡金不足',
+        self::MERCHANT_CREDIT_NOT_ENOUGH => '商户卡金不足',
+        self::MERCHANT_NOT_EXIST => '商户不存在',
+        self::FAVORITE_NOT_EXIST => '收藏不存在',
+        self::MERCHANT_ADD_MEMBER_FAILED => '添加会员失败',
+        self::MERCHANT_STATUS_NOT_OK => '申请成功,客服会在3个工作日内与您取得联系!',
+        self::MERCHANT_BALANCE_NOT_ENOUGH => '商户余额不足',
+        self::PAY_TYPE_UNSUPPORTED => '不支持的支付方式',
+        self::MEMBER_NOT_EXIST => '会员不存在',
+        self::MEMBER_BALANCE_NOT_ENOUGH => '会员余额不足',
+        self::SERVICE_COST_OVERFLOW_BALANCE => '余额不足,请充值',
+        self::CREATE_SERVICE_OVER_MAX => '服务数量达到系统上限',
+        self::MERCHANT_SERVICE_STATUS_INVALID => '服务状态不正确',
+        self::CONTENT_GET_DETAIL_FAILED => '获取内容详情失败',
+        self::MERCHANT_SERVICE_ADD_FAILED => '发出服务失败',
+        self::MERCHANT_SERVICE_NOT_EXIST => '服务不存在',
+        self::SERVICE_STATUS_INVALID_CHANGE => '服务状态转换无效',
+        self::CANT_ADD_SERVICE_SAME_MERCHANT => '服务发出方与创建方一致',
+        self::MERCHANT_SERVICE_EXPIRED => '服务已过期',
+        self::SAVE_MODEL_FAILED => '保存模型失败',
+        self::REMOVE_MODEL_FAILED => '删除模型失败',
+        self::MODEL_NOT_EXIST => '模型不存在',
+        self::ATTACHMENT_UPLOAD_FAILED => '附件上传失败',
+        self::PROTO_PATH_NOT_EXIST => '指定API路径不存在',
+        self::PROTO_TRY_TO_SET_VALUE_ON_NULL => '企图操作NULL对象并赋值',
+        self::ACTIVITY_NOT_EXIST => '活动不存在',
+        self::ORDER_GENERATE_FAILED => '生成订单失败',
+        self::CONSUME_LOG_NOT_EXIST => '消费记录不存在',
+        self::LOGOUT_FAILED => '退出失败',
+        self::SERVICE_CODE_FAILED=>'验证码错误',
+        self::USER_DOES_EXIST => '手机已经注册',
+        self::USER_DOES_NOT_EXIST => '用户不存在',
+        self::INCORRECT_USER_OR_PASS => '用户名或密码不正确',
+        self::PHONE_NUMBER_ALREADY_REGISTERED => '该手机号已注册',
+        self::INCORRECT_VERIFY_CODE => '输入验证码错误',
+        self::VERIFY_CODE_TOO_MUCH => '24小时内验证码发送过多',
+        self::DELETE_OP_FAILED => '删除操作失败',
+        self::CLIENT_WRONG_PARAMS => '输入不正确',
+    ];
+
+    public static function message($code) {
+        if (isset(self::$_msg[$code])) {
+            return self::$_msg[$code];
+        } else {
+            return null;
+        }
+    }
+
+}

+ 274 - 0
app/Services/Base/Routes.php

xqd
@@ -0,0 +1,274 @@
+<?php
+/**
+ *------------------------------------------------------
+ * Routes.php 路由控制器
+ *------------------------------------------------------
+ *
+ * @author    qqiu@qq.com
+ * @date      2016/5/26 11:17
+ * @version   V1.0
+ *
+ */
+
+namespace App\Services\Base;
+
+use Route;
+
+/**
+ * 系统路由
+ * 注:大部分的路由及控制器所执行的动作来说
+ * 你需要返回完整的 Illuminate\Http\Response 实例或是一个视图
+ */
+class Routes
+{
+    private $_adminDomain;
+    private $_mobileDomain;
+
+    /**
+     * 初始化,取得配置
+     */
+    public function __construct()
+    {
+        $this->_adminDomain = config('sys.sys_admin_domain');
+        $this->_mobileDomain = config('sys.sys_mobile_domain');
+    }
+
+    /**
+     * 后台的通用路由
+     * 覆盖通用的路由一定要带上别名,且別名的值为module.class.action
+     * 即我们使用别名传入了当前请求所属的module,controller和action
+     */
+    public function admin()
+    {
+        Route::group(
+            ['domain' => $this->_adminDomain], function () {
+            ### 登录页
+            Route::any('login', 'Admin\Foundation\LoginController@index');
+            ### 退出页
+            Route::get('logout', 'Admin\Foundation\LoginController@logout');
+
+            ### 登录验证
+            Route::group(
+                [], function () {
+                $routeUri = request()->path();
+                if ($routeUri == '/') {
+                    //后台首页
+                    Route::any('/', 'Admin\Foundation\IndexController@index');
+                } else {
+                    //后台通用路由
+                    $routeArr = explode('/', $routeUri);
+                    if (count($routeArr) > 1) {
+                        $action = array_pop($routeArr);
+                        $filePath = app_path() . '/Http/Controllers/Admin/' . implode(
+                                '/', $routeArr) . 'Controller.php';
+                        if (file_exists($filePath)) {
+                            $controllerPath = 'Admin\\' . implode('\\', $routeArr) . 'Controller@' . $action;
+                            Route::any(request()->path(), ['uses' => $controllerPath]);
+                        }
+                    }
+                }
+            });
+
+            /**************************** 后台接口 ****************************/
+
+            #============================ 代加工 ============================#
+            //代加工管理
+            Route::any(
+                'remake/demand/list/{limit}/{page}/{sort}/{order}/complex', 'Admin\Remake\DemandController@lists');
+            Route::any('remake/demand/detail/{id}', 'Admin\Remake\DemandController@detail');
+            Route::any('remake/demand/update', 'Admin\Remake\DemandController@update');
+            Route::any('remake/demand/audit/{id}', 'Admin\Remake\DemandController@audit');
+            Route::any('remake/demand/auditOffer/{id}', 'Admin\Remake\DemandController@auditOffer');
+
+            //代加订单
+            Route::any('remake/order/list/{limit}/{page}/{sort}/{order}/complex', 'Admin\Remake\OrderController@lists');
+            Route::any('remake/order/detail/{id}', 'Admin\Remake\OrderController@detail');
+            Route::any('remake/order/update', 'Admin\Remake\OrderController@update');
+            Route::any('remake/order/audit/{id}', 'Admin\Remake\OrderController@audit');
+            Route::any('remake/order/auditOffer/{id}', 'Admin\Remake\OrderController@auditOffer');
+            Route::any('remake/order/auditContract/{id}', 'Admin\Remake\OrderController@auditContract');
+            Route::any('remake/order/auditProduction/{id}', 'Admin\Remake\OrderController@auditProduction');
+            Route::any('remake/order/auditFinal/{id}', 'Admin\Remake\OrderController@auditFinal');
+
+            //工厂
+            Route::any('user/factory/list/{limit}/{page}/{sort}/{order}/complex', 'Admin\User\FactoryController@lists');
+            Route::any('user/factory/detail/{id}', 'Admin\User\FactoryController@detail');
+            Route::any('user/factory/update', 'Admin\User\FactoryController@update');
+            Route::any('user/factory/audit/{id}', 'Admin\User\FactoryController@audit');
+
+            #============================ 订单 ============================#
+            //期货订单
+            Route::any(
+                'order/futures/list/{limit}/{page}/{sort}/{order}/complex', 'Admin\Order\FuturesController@lists');
+            Route::any('order/futures/create', 'Admin\Order\FuturesController@create');
+            Route::any('order/futures/changePrice', 'Admin\Order\FuturesController@changePrice');
+            Route::any('order/futures/cancel', 'Admin\Order\FuturesController@cancel');
+            Route::any('order/futures/confirmDeposit', 'Admin\Order\FuturesController@confirmDeposit');
+            Route::any('order/futures/confirmArrivePort', 'Admin\Order\FuturesController@confirmArrivePort');
+            Route::any('order/futures/confirmFinal', 'Admin\Order\FuturesController@confirmFinal');
+            Route::any('order/futures/logistics', 'Admin\Order\FuturesController@logistics');
+            Route::any('order/futures/detail/{orderNo}', 'Admin\Order\FuturesController@detail');
+
+            //现货订单
+            Route::any(
+                'order/commodity/list/{limit}/{page}/{sort}/{order}/complex', 'Admin\Order\CommodityController@lists');
+            Route::any('order/commodity/create', 'Admin\Order\CommodityController@create');
+            Route::any('order/commodity/changePrice', 'Admin\Order\CommodityController@changePrice');
+            Route::any('order/commodity/cancel', 'Admin\Order\CommodityController@cancel');
+            Route::any('order/commodity/confirmReceipt', 'Admin\Order\CommodityController@confirmReceipt');
+            Route::any('order/commodity/logistics', 'Admin\Order\CommodityController@logistics');
+            Route::any('order/commodity/detail/{orderNo}', 'Admin\Order\CommodityController@detail');
+
+            #============================ 财务 ============================#
+            //商家结算
+            Route::any(
+                'finance/settlement/list/{limit}/{page}/{sort}/{order}/complex',
+                'Admin\Finance\SettlementController@lists');
+            Route::any('finance/settlement/detail/{id}', 'Admin\Finance\SettlementController@detail');
+            Route::any('finance/settlement/payment', 'Admin\Finance\SettlementController@payment');
+
+            //还款管理
+            Route::any(
+                'finance/repayment/list/{limit}/{page}/{sort}/{order}/complex',
+                'Admin\Finance\RepaymentController@lists');
+            Route::any('finance/repayment/affirmAccount', 'Admin\Finance\RepaymentController@affirmAccount');
+
+            //授信管理
+            Route::any(
+                'finance/credit/list/{limit}/{page}/{sort}/{order}/complex', 'Admin\Finance\CreditController@lists');
+            Route::any('finance/credit/create', 'Admin\Finance\CreditController@create');
+            Route::any('finance/credit/update', 'Admin\Finance\CreditController@update');
+            Route::any('finance/credit/delete/{id}', 'Admin\Finance\CreditController@delete');
+
+            #============================ 用户 ============================#
+            //用户管理
+            Route::any('user/list/{limit}/{page}/{sort}/{order}/complex', 'Admin\User\InfoController@lists');
+            Route::any('user/detail/{id}', 'Admin\User\InfoController@detail');
+            Route::any('user/contractCommodity', 'Admin\User\InfoController@contractCommodity');
+
+            //商家认证
+            Route::any('user/store/list/{limit}/{page}/{sort}/{order}/complex', 'Admin\User\StoreController@lists');
+            Route::any('user/store/detail/{id}', 'Admin\User\StoreController@detail');
+            Route::any('user/store/audit/{id}', 'Admin\User\StoreController@audit');
+
+            //买家认证
+            Route::any('user/buyers/list/{limit}/{page}/{sort}/{order}/complex', 'Admin\User\BuyersController@lists');
+            Route::any('user/buyers/detail/{id}', 'Admin\User\BuyersController@detail');
+            Route::any('user/buyers/audit/{id}', 'Admin\User\BuyersController@audit');
+
+            //团购管理
+            Route::put('tuan/index', 'Admin\Activities\TuanController@index');
+            Route::put('tuan/store', 'Admin\Activities\TuanController@store');
+            Route::put('tuan/detail', 'Admin\Activities\TuanController@detail');
+            Route::put('tuan/update', 'Admin\Activities\TuanController@update');
+            Route::put('tuan/destroy', 'Admin\Activities\TuanController@destroy');
+            Route::put('tuan/view', 'Admin\Activities\TuanController@view');
+            Route::put('tuan/goods-search', 'Admin\Activities\TuanController@goodsSearch');
+
+            //商品管理
+            //==========================================商品分类=============================================//
+            Route::any(
+                'commodity/cate/list/{limit}/{page}/{sort}/{order}/complex', 'Admin\Commodity\CateController@index');
+            Route::any('commodity/cate/detail/{id}', 'Admin\Commodity\CateController@detail');
+            Route::any('commodity/cate/delete/{id}', 'Admin\Commodity\CateController@destroy');
+            Route::any('commodity/cate/update', 'Admin\Commodity\CateController@update');
+            Route::any('commodity/cate/all', 'Admin\Commodity\CateController@all');
+            Route::any('commodity/cate/create', 'Admin\Commodity\CateController@store');
+            Route::get('commodity/cate/get-child/{id}', 'Admin\Commodity\CateController@getChild');
+            //==========================================商品信息=============================================//
+            Route::any(
+                'commodity/goods/list/{limit}/{page}/{sort}/{order}/complex',
+                'Admin\Commodity\CommodityController@index');
+            Route::any('commodity/goods/delete/{id}', 'Admin\Commodity\CommodityController@destroy');
+            Route::any('commodity/goods/detail/{id}', 'Admin\Commodity\CommodityController@detail');
+            Route::get('commodity/goods/attr/{id}', 'Admin\Commodity\CommodityController@getAttr');
+            Route::get('commodity/goods/spec/{id}', 'Admin\Commodity\CommodityController@getSpec');
+            Route::post('commodity/goods', 'Admin\Commodity\CommodityController@store');
+            //==========================================商品SKU=============================================//
+            Route::any(
+                '/commodity/product/list/{limit}/{page}/{sort}/{order}/complex', 'Admin\Commodity\SkuController@index');
+            Route::put('commodity/product/price/{id}/{price}', 'Admin\Commodity\SkuController@changePrice');
+            Route::put('commodity/product/stock/{id}/{stock}', 'Admin\Commodity\SkuController@changeStock');
+            Route::put('commodity/product/down/{id}', 'Admin\Commodity\SkuController@down');
+            Route::put('commodity/product/up/{id}', 'Admin\Commodity\SkuController@up');
+            //==========================================商品品牌=============================================//
+            Route::get('commodity/brand/except-self/{id}', 'Admin\Commodity\BrandController@getExceptSelf');
+            Route::get('commodity/brand/self/{id}', 'Admin\Commodity\BrandController@getSelf');
+            Route::post('commodity/brands', 'Admin\Commodity\BrandController@adds');
+            Route::post('commodity/brand', 'Admin\Commodity\BrandController@add');
+            Route::put('commodity/brand/all/{id}', 'Admin\Commodity\BrandController@removeAll');
+            Route::put('commodity/self-brand', 'Admin\Commodity\BrandController@removes');
+            Route::get('commodity/brand/search/{id}/{name}', 'Admin\Commodity\BrandController@search');
+            Route::get('commodity/brand/search/{id}', 'Admin\Commodity\BrandController@search');
+
+            //==========================================商品分类属性=============================================//
+            Route::get('commodity/cate/attr/{id}', 'Admin\Commodity\CateAttrController@cateAttr');
+            Route::delete('commodity/cate/attr/select/{id}', 'Admin\Commodity\CateAttrController@removeSelect');
+            Route::delete('commodity/cate/attr/select/value/{id}', 'Admin\Commodity\CateAttrController@removeSelectValue');
+            Route::delete('commodity/cate/attr/text/{id}', 'Admin\Commodity\CateAttrController@removeText');
+            Route::post('commodity/cate/attr/text', 'Admin\Commodity\CateAttrController@addText');
+            Route::post('commodity/cate/attr/select', 'Admin\Commodity\CateAttrController@addSelect');
+            //==========================================商品销售属性=============================================//
+            Route::get('commodity/cate/spec/{id}', 'Admin\Commodity\CateSpecController@cateSpec');
+            Route::delete('commodity/cate/spec/value/{id}', 'Admin\Commodity\CateSpecController@removeSpecValue');
+            Route::delete('commodity/cate/spec/{id}', 'Admin\Commodity\CateSpecController@removeSpec');
+            Route::post('commodity/cate/spec', 'Admin\Commodity\CateSpecController@addSpec');
+            //==========================================商品基本属性=============================================//
+            Route::post('commodity/attr', 'Admin\Commodity\AttrController@findOrCreateValue');
+        });
+
+        return $this;
+    }
+
+    /**
+     * 移动端
+     */
+    public function mobile()
+    {
+        Route::group(
+            ['middleware' => ['web'], 'domain' => $this->_mobileDomain], function () {
+
+        });
+
+        return $this;
+    }
+
+    /**
+     * API接口
+     */
+    public function api()
+    {
+        //附件上传
+        Route::any(
+            'attachment/webupload',
+            ['uses' => 'Api\AttachmentController@webUpload', 'as' => 'api.attachment.webupload']);
+        //附件下载
+        Route::any(
+            'api/attachment/download',
+            ['uses' => 'Api\AttachmentController@download', 'as' => 'api.attachment.download']);
+        //区域相关
+        Route::any('api/area/index', ['uses' => 'Api\AreaController@index', 'as' => 'api.area.index']);
+
+        ## 修改购物车商品数量
+        Route::any('api/order/cart/lists', 'Api\CartController@lists');
+        Route::any('api/order/cart/modifyQuantity', 'Api\CartController@modifyQuantity');
+        Route::any('api/order/cart/remove/{id}', 'Api\CartController@remove');
+
+        ## 收货地址
+        Route::any('api/user/consignee/storeAddress', 'Api\ConsigneeController@storeAddress');
+        Route::any('api/user/consignee/updateAddress', 'Api\ConsigneeController@updateAddress');
+        Route::any('api/user/consignee/getAddress', 'Api\ConsigneeController@getAddress');
+        Route::any('api/user/consignee/setDefault/{id}', 'Api\ConsigneeController@setDefault');
+        ## 关注喜欢
+        Route::any('api/user/favorite/add', 'Api\FavoriteController@add');
+
+        // 现货订单
+        Route::any('api/order/commodity/cancel', 'Api\Order\CommodityController@cancel');
+        Route::any('api/order/commodity/finish', 'Api\Order\CommodityController@finish');
+        Route::any('api/order/commodity/payment', 'Api\Order\CommodityController@payment');
+        Route::any('api/order/commodity/detail/{orderNo}', 'Api\Order\CommodityController@detail');
+
+        return $this;
+    }
+
+}

+ 71 - 0
app/Services/Base/System.php

xqd
@@ -0,0 +1,71 @@
+<?php
+/**
+ * User: Mike
+ * Email: m@9026.com
+ * Date: 2016/7/26
+ * Time: 15:24
+ */
+namespace App\Services\Base;
+
+use App\Models\SysConfigModel;
+use Illuminate\Support\Facades\Cache;
+
+/**
+ *  全局数据字典的调用
+ *
+ *  提供配置缓存的类型
+ *
+ *  @author  wangzhoudong  <admin@zhen.pl>
+ *  @version    1.0
+ *
+ */
+class System {
+
+    private $cacheKey = 'sys_config';
+
+    public function __construct() {
+
+    }
+
+    public function getCoufig($key=null) {
+
+        $config = Cache::get($this->cacheKey);
+        if($config){
+            if($key){
+                $data = isset($config[$key]) ? $config[$key] : '';
+            }else{
+                $data = $config;
+            }
+        }else {
+            $obj = new SysConfigModel();
+            if ($key) {
+                $data = $obj->select("value")->where("key", $key)->first();
+                if ($data) {
+                    $data = $data->value;
+                }
+            } else {
+                $data = $obj->pluck('value', 'key');
+            }
+        }
+        return $data;
+    }
+
+    public function saveConfig($data) {
+        $obj = new SysConfigModel();
+        foreach($data as $key=>$val) {
+            $objVal = $obj->find($key);
+            if ($objVal){
+                $objVal->value = $val;
+                $objVal->save();
+            }else{
+                $obj->create(['key' => $key,'value'=>$val]);
+            }
+        }
+
+        $config = $obj->lists('value', 'key')->toArray();
+        Cache::forever($this->cacheKey, $config);
+
+        return true;
+    }
+
+}

+ 197 - 0
app/Services/Base/Tree.php

xqd
@@ -0,0 +1,197 @@
+<?php
+/**
+ *------------------------------------------------------
+ * Tree.php
+ *------------------------------------------------------
+ *
+ * @author    qqiu@qq.com
+ * @date      2016/5/26 11:17
+ * @version   V1.0
+ *
+ */
+
+namespace App\Services\Base;
+
+class Tree {
+    
+    /**
+    * 生成树型结构所需要的2维数组
+    */
+    public $arr = array();
+
+    /**
+    * 生成树型结构所需修饰符号
+    */
+    public $icon = array('│','├','└');
+    public $nbsp = "&nbsp;";
+    public $treeArr = array();
+
+    /**
+    * 构造函数,初始化类
+    * @param array 2维数组,例如:
+    * array(
+    *      1 => array('id'=>'1','pid'=>0,'name'=>'一级栏目一'),
+    *      2 => array('id'=>'2','pid'=>0,'name'=>'一级栏目二'),
+    *      3 => array('id'=>'3','pid'=>1,'name'=>'二级栏目一'),
+    *      4 => array('id'=>'4','pid'=>1,'name'=>'二级栏目二'),
+    *      5 => array('id'=>'5','pid'=>2,'name'=>'二级栏目三'),
+    *      6 => array('id'=>'6','pid'=>3,'name'=>'三级栏目一'),
+    *      7 => array('id'=>'7','pid'=>3,'name'=>'三级栏目二'),
+    *   )
+    */
+    public function init($arr = [])
+    {
+        $data = array();
+        foreach ($arr AS $val){
+            $data[$val['id']] = $val;
+        }
+        $this->arr = $data;
+        $this->treeArr = array();
+        return is_array($data);
+    }
+
+    /**
+    * 得到父级数组
+    * @param int
+    * @return array
+    */
+    public function getParent($myid)
+    {
+        $newarr = array();
+        if(!isset($this->arr[$myid])) return false;
+        $pid = $this->arr[$myid]['pid'];
+        if(isset($this->arr[$pid]['pid'])){
+            $pid = $this->arr[$pid]['pid'];
+        }
+        if(is_array($this->arr)){
+            foreach($this->arr as $id => $val){
+                if($val['pid'] == $pid) $newarr[$id] = $val;
+            }
+        }
+        return $newarr;
+    }
+    
+    /**
+     * 得到所有父级数组
+     * @param int
+     * @return array
+     */
+    public function getAllParents($myid, &$newarr = [])
+    {
+        
+        if(!isset($this->arr[$myid])) return false;
+        $pid = $this->arr[$myid]['pid'];
+
+        if(isset($this->arr[$pid])){
+            $newarr[$pid] = $this->arr[$pid];
+            $this->getAllParents($pid, $newarr);
+        }
+        
+        return array_reverse($newarr, true);
+    }
+
+    /**
+    * 得到子级数组
+    * @param int
+    * @return array
+    */
+    public function getChild($myid)
+    {
+        $newarr = array();
+        if(is_array($this->arr)){
+            foreach($this->arr as $id => $val){
+                if($val['pid'] == $myid) $newarr[$id] = $val;
+            }
+        }
+        return $newarr ? $newarr : false;
+    }
+
+    /**
+    * 得到当前位置数组
+    * @param int
+    * @return array
+    */
+    public function getPos($myid, &$newarr = [])
+    {
+        $a = array();
+        if(!isset($this->arr[$myid])) return false;
+        $newarr[] = $this->arr[$myid];
+        $pid = $this->arr[$myid]['pid'];
+        if(isset($this->arr[$pid])){
+            $this->getPos($pid, $newarr);
+        }
+        if(is_array($newarr)){
+            krsort($newarr);
+            foreach($newarr as $v){
+                $a[$v['id']] = $v;
+            }
+        }
+        return $a;
+    }
+    
+    /**
+     * 得到树型结构
+     * @param $myid        表示获得这个ID下的所有子级, 默认不包括自身
+     * @param $spacer      间隔缩进     
+     * @param $self        是否包含自身      
+     */
+    public function getTree($myid = 0, $spacer = '', $self = false)
+    {
+        if($self){
+            $spacer = $spacer ? $spacer : $this->nbsp;
+            $selfArr = $this->arr[$myid];
+            $selfArr['spacer'] = '';
+            $this->treeArr[] = $selfArr;
+        }
+        $number = 1;
+        $child = $this->getChild($myid);
+        if(is_array($child)){
+            $total = count($child);
+            foreach($child as $value){
+                $j = $k = '';
+                if($number == $total){
+                    $j .= $this->icon[2];
+                }else{
+                    $j .= $this->icon[1];
+                    $k = $spacer ? $this->icon[0] : '';
+                }
+                
+                $nbsp = $this->nbsp;
+                //间隔缩进
+                $value['spacer'] = $spacer ? $spacer.$j : '';
+                //层级关系
+                $value['level'] = count(explode($nbsp, $value['spacer']));
+                //生成带树状结构的新数组
+                $this->treeArr[] = $value;
+                $this->getTree($value['id'], $spacer.$k.$nbsp);
+                $number++;
+            }
+        }
+        return $this->_cateAppendChild($this->treeArr);
+    }
+
+    /**
+     * 栏目是否含有子栏目
+     * @param $cateArr
+     * @return mixed
+     */
+    private function _cateAppendChild($cateArr)
+    {
+        //PID集合
+        $pidArr = [];
+        foreach($cateArr AS $val){
+            $pidArr[$val['pid']] = $val['pid'];
+        }
+        //栏目ID在PID集合内,则含有子栏目
+        foreach($cateArr AS $key => $val){
+            if(in_array($val['id'], $pidArr)){
+                $cateArr[$key]['child'] = 1;
+            }else{
+                $cateArr[$key]['child'] = 0;
+            }
+        }
+        return $cateArr;
+    }
+
+}
+

+ 502 - 0
app/Services/CRUD/CRUD.php

xqd
@@ -0,0 +1,502 @@
+<?php
+/**
+ * User: Mike
+ * Email: m@9026.com
+ * Date: 2016/7/28
+ * Time: 15:09
+ */
+
+namespace App\Services\CRUD;
+
+use App\Models\AdminMenusModel;
+use App\Models\ModuleTagModel;
+use App\Services\Base\BaseProcess;
+
+class CRUD extends BaseProcess
+{
+
+    private $_data;
+
+    private $_date;
+    private $_modelTpl;
+    private $_repositoriesTpl;
+    private $_CriteriaMultiWhereTpl;
+    private $_controlTpl;
+    private $_viewTpl;
+
+    private $_fieldData;
+
+    private $_fieldContentData;
+
+    private $_fieldPrimary;
+
+    public $notFillable = ['created_at','updated_at',"deleted_at"];
+
+    private $_coverage = true; //强制覆盖
+    /**
+     * 创建CRUD
+     * @param $data
+     *
+     */
+    public function create($data) {
+
+        $this->_dealData($data);
+        \DB::beginTransaction();
+
+        if(!$this->_addMenu()) {
+            dd(1);
+            $this->setMsg("添加菜单失败");
+            \DB::rollback();
+            return false;
+        }
+
+        if(!$this->_addModel()) {
+            dd(2);
+            $this->setMsg("添加模型失败");
+            \DB::rollback();
+            return false;
+        }
+
+        if(!$this->_addService()) {
+            dd(3);
+            $this->setMsg("添加Service失败");
+            \DB::rollback();
+            return false;
+        }
+        if(!$this->_addCriteriaMultiWhere()) {
+            dd(4);
+            $this->setMsg("添加Service失败");
+            \DB::rollback();
+            return false;
+        }
+
+        if(!$this->_addControl()) {
+            dd(5);
+            $this->setMsg("添加控制器失败");
+            \DB::rollback();
+            return false;
+        }
+        \DB::commit();
+        return true;
+    }
+
+    public function _dealData($data) {
+        $data['modelPath'] =  app_path() . "/Models/" . $data['model'] . ".php";
+        $data['modelUse'] =   'App\Models\\' . $data['model'];
+        $data['modelName'] =   $data['model'];
+
+        $data['repositoriesPath'] =  app_path() . "/Repositories/" . $data['repositories'] . ".php";
+        $data['repositoriesUse'] =  'App\Repositories\\' . str_replace('/','\\',$data['repositories']);
+        $data['CriteriaMultiWherePath'] =  app_path() . "/Repositories/" . substr($data['repositories'],0,strrpos ($data['repositories'], "/")) . "/Criteria/MultiWhere" . ".php"; ;
+        $data['CriteriaMultiWhereUse'] =  substr($data['repositoriesUse'],0,strrpos ($data['repositoriesUse'], "\\")) . "\\Criteria\\MultiWhere" ;
+        $data['repositoriesName'] =  substr(strrchr( $data['repositories'], '/'), 1);
+        $data['controlPath'] =  app_path() . "/Http/Controllers/Admin/" . $data['control'] . ".php";
+        $data['controlUse'] =  'App\Repositories\\' . str_replace('/','\\',$data['control']);
+        $data['controlName'] =  substr(strrchr( $data['control'], '/'), 1);
+
+        $data['viewBaseSort'] =   'admin/'. strtolower(substr($data['control'],0,-10));
+        $data['viewPath'] = base_path() . "/resources/views/" . $data['viewBaseSort'];
+        $data['viewSortPath'] = str_replace('/','.',$data['viewBaseSort']);
+
+        $this->_modelTpl = __DIR__ . "/tpl/model.tpl";
+        $this->_repositoriesTpl = __DIR__ . "/tpl/repositories.tpl";
+        $this->_CriteriaMultiWhereTpl = __DIR__ . "/tpl/creteriaMultiWhere.tpl";
+        $this->_controlTpl = __DIR__ . "/tpl/controller.tpl";
+        $this->_viewTpl = __DIR__ . "/tpl/view/";
+        $this->_data = $data;
+        $this->_date =  date("Y-m-d H:i:s");
+        $this->_fieldData = $resultRow = \DB::select("SELECT COLUMN_NAME,COLUMN_KEY,DATA_TYPE,COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA= ? AND TABLE_NAME= ? ",[env('DB_DATABASE'),$this->_data['table']]);
+        foreach($this->_fieldData as $data) {
+            if($data->COLUMN_KEY == "PRI") {
+                $this->_fieldPrimary = $data->COLUMN_NAME;
+                break;
+            }
+        }
+
+    }
+
+    /**
+     *
+     * 添加菜单
+     *
+     */
+
+    public function _addMenu(){
+        $obj = new AdminMenusModel();
+        $addData['pid'] = $this->_data['menu_pid'];
+        $addData['display'] = 1;
+        $addData['name'] = $this->_data['desc'];
+        $addData['path'] = $this->_data['path'] . "/index";
+        $baseObj = $obj->create($addData);
+        if(!$baseObj) {
+            return false;
+        }
+        //添加
+        $addData['display'] = 0;
+        $addData['path'] = $this->_data['path'] . "/create";
+        $addData['pid'] = $baseObj->id;
+        $addData['name'] = "添加";
+        $ok = $obj->create($addData);
+        if(!$ok) {
+            return false;
+        }
+
+        //修改
+        $addData['display'] = 0;
+        $addData['path'] = $this->_data['path'] . "/update";
+        $addData['pid'] = $baseObj->id;
+        $addData['name'] = "修改";
+        $ok = $obj->create($addData);
+
+        if(!$ok) {
+            return false;
+        }
+        //删除
+        $addData['display'] = 0;
+        $addData['path'] = $this->_data['path'] . "/destroy";
+        $addData['pid'] = $baseObj->id;
+        $addData['name'] = "删除";
+        $ok = $obj->create($addData);
+
+        if(!$ok) {
+            return false;
+        }
+
+        //查看
+        $addData['display'] = 0;
+        $addData['path'] = $this->_data['path'] . "/view";
+        $addData['pid'] = $baseObj->id;
+        $addData['name'] = "查看";
+        $ok = $obj->create($addData);
+
+        if(!$ok) {
+            return false;
+        }
+        //check
+        $addData['display'] = 0;
+        $addData['path'] = $this->_data['path'] . "/check";
+        $addData['pid'] = $baseObj->id;
+        $addData['name'] = "选择数据";
+        $ok = $obj->create($addData);
+
+        if(!$ok) {
+            return false;
+        }
+        if(dict($this->_data['table'],'status')) {
+            //check
+            $addData['display'] = 0;
+            $addData['path'] = $this->_data['path'] . "/status";
+            $addData['pid'] = $baseObj->id;
+            $addData['name'] = "状态变更";
+            if(!$ok) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * 添加模型
+     */
+    public function _addModel() {
+        $filePath = $this->_data['modelPath'];
+        if(file_exists($filePath) && $this->_coverage===false) {
+            return true;
+        }
+        $notFillable = $this->notFillable;
+
+        $date = $this->_date;
+        $tpl = file_get_contents($this->_modelTpl);
+        $table_primary = '';
+        $fillable = "";
+        foreach($this->_fieldData as $data) {
+            if($data->COLUMN_KEY == "PRI") {
+                $table_primary = $data->COLUMN_NAME;
+            }elseif(!in_array($data->COLUMN_NAME,$notFillable)) {
+                $fillable .= "\r\n                           '{$data->COLUMN_NAME}',";
+            }
+        }
+       
+        $fillable = $fillable ?  '['. substr($fillable,0,-1) ."\r\n                          ]": $fillable;
+        $str = str_replace("{{table_comment}}", $this->_data['desc'], $tpl);
+        $str = str_replace("{{table_name}}", $this->_data['table'], $str);
+        $str = str_replace("{{table_primary}}", $table_primary, $str);
+        $str = str_replace("{{fillable}}", $fillable, $str);
+        $str = str_replace("{{class_name}}", $this->_data['model'], $str);
+        $str = str_replace("{{date}}", $this->_date, $str);
+        $ok = file_put_contents($filePath, $str);
+        if(!$ok) {
+            return true;
+        }
+
+        return true;
+    }
+
+    /**
+     * 添加Service
+     */
+    public function _addService() {
+        if(file_exists($this->_data['repositoriesPath']) && $this->_coverage===false) {
+            return true;
+        }
+        $tpl = file_get_contents($this->_repositoriesTpl);
+        $queryKeyord = "";
+        foreach($this->_fieldData as $data) {
+
+            $queryKeyord = " if(isset(\$this->search['{$data->COLUMN_NAME}']) && \$this->search['{$data->COLUMN_NAME}']) {
+                                    \$model = \$model->where('{$data->COLUMN_NAME}',\$this->search['{$data->COLUMN_NAME}']);
+                                 }\r\n";
+        }
+
+
+        $this->customMkdir(substr($this->_data['repositoriesPath'],0,strrpos ($this->_data['repositoriesPath'], "/")),  $mode = 0777, $recursive = true);
+        $str = str_replace("{{desc}}", $this->_data['desc'], $tpl);
+        $str = str_replace("{{modelUse}}", $this->_data['modelUse'], $str);
+        $str = str_replace("{{sortPath}}", str_replace('/','\\',substr($this->_data['repositories'],0,strrpos ($this->_data['repositories'], "/"))), $str);
+        $str = str_replace("{{repositoriesName}}", $this->_data['repositoriesName'], $str);
+        $str = str_replace("{{modelName}}", $this->_data['modelName'], $str);
+        $str = str_replace("{{primaryKey}}", $this->_fieldPrimary, $str);
+        $str = str_replace("{{queryKeyord}}", $queryKeyord, $str);
+        $str = str_replace("{{date}}", $this->_date, $str);
+        $ok = file_put_contents($this->_data['repositoriesPath'], $str);
+        return true;
+    }
+
+
+
+    /**
+     * 添加Service
+     */
+    public function _addCriteriaMultiWhere() {
+        if(file_exists($this->_data['CriteriaMultiWherePath']) && $this->_coverage===false) {
+            return true;
+        }
+        $tpl = file_get_contents($this->_CriteriaMultiWhereTpl);
+        $queryKeyord = "";
+        foreach($this->_fieldData as $data) {
+
+            $queryKeyord = " if(isset(\$this->search['{$data->COLUMN_NAME}']) && \$this->search['{$data->COLUMN_NAME}']) {
+                                    \$model = \$model->where('{$data->COLUMN_NAME}',\$this->search['{$data->COLUMN_NAME}']);
+                                 }\r\n";
+        }
+
+
+        $this->customMkdir(substr($this->_data['CriteriaMultiWherePath'],0,strrpos ($this->_data['CriteriaMultiWherePath'], "/")),  $mode = 0777, $recursive = true);
+
+        $str = str_replace("{{desc}}", $this->_data['desc'], $tpl);
+        $str = str_replace("{{sortPath}}", str_replace('/','\\',substr($this->_data['repositories'],0,strrpos ($this->_data['repositories'], "/"))), $str);
+
+        $str = str_replace("{{queryKeyord}}", $queryKeyord, $str);
+        $ok = file_put_contents($this->_data['CriteriaMultiWherePath'], $str);
+        return true;
+    }
+
+
+    public function _addControl() {
+        if(file_exists($this->_data['controlPath']) && $this->_coverage===false) {
+            return true;
+        }
+        $this->customMkdir(substr($this->_data['controlPath'],0,strrpos ($this->_data['controlPath'], "/")),  $mode = 0777, $recursive = true);
+        $str = file_get_contents($this->_controlTpl);
+
+        $str = str_replace("{{desc}}", $this->_data['desc'], $str);
+        $str = str_replace("{{path}}", $this->_data['path'], $str);
+        $str = str_replace("{{repositoriesUse}}", $this->_data['repositoriesUse'], $str);
+        $str = str_replace("{{sortPath}}", str_replace('/','\\',substr($this->_data['control'],0,strrpos ($this->_data['control'], "/"))), $str);
+        $str = str_replace("{{repositoriesName}}", $this->_data['repositoriesName'], $str);
+        $str = str_replace("{{CriteriaMultiWhereUse}}", $this->_data['CriteriaMultiWhereUse'], $str);
+
+        $str = str_replace("{{controlName}}", $this->_data['controlName'], $str);
+        $str = str_replace("{{viewSortPath}}", $this->_data['viewSortPath'], $str);
+        $str = str_replace("{{date}}", $this->_date, $str);
+
+        $ok = file_put_contents($this->_data['controlPath'], $str);
+        $this->_addView();
+        return true;
+
+    }
+
+    public function _addView(){
+        if(file_exists($this->_data['viewPath']) && $this->_coverage===false) {
+            return true;
+        }
+        $this->customMkdir($this->_data['viewPath'],  $mode = 0777, $recursive = true);
+
+        ###index
+        $str = file_get_contents($this->_viewTpl . "/index.blade.php");
+
+        $listThStr = "";
+        $listTdStr = "";
+        $i = 0;
+        foreach($this->_fieldData as $key=> $data) {
+            if(!in_array($data->COLUMN_NAME,["deleted_at"]) && $data->DATA_TYPE !='text') {
+                if($data->COLUMN_NAME =="id") $this->_fieldData[$key]->COLUMN_COMMENT ="ID";
+                if($data->COLUMN_NAME =="created_at") $this->_fieldData[$key]->COLUMN_COMMENT ="创建时间";
+                if($data->COLUMN_NAME =="updated_at") $this->_fieldData[$key]->COLUMN_COMMENT ="更新时间";
+                $i++;
+                if($i>7) break;
+                $listThStr .= "\r\n            <th class=\"sorting\" data-sort=\"{$data->COLUMN_NAME}\"> {$data->COLUMN_COMMENT} </th>";
+
+                switch($data->DATA_TYPE) {
+                    case "tinyint":
+                        if(dict()->get($this->_data['table'],$data->COLUMN_NAME)) {
+                            $listTdStr .= "\r\n            <td>{{ dict()->get('{$this->_data['table']}','{$data->COLUMN_NAME}',\$item->{$data->COLUMN_NAME}) }}</td>";
+
+                        }elseif(dict()->get('global',$data->COLUMN_NAME)) {
+                            $listTdStr .= "\r\n            <td>{{ dict()->get('global','{$data->COLUMN_NAME}',\$item->{$data->COLUMN_NAME}) }}</td>";
+
+                        }else{
+                            $listTdStr .= "\r\n            <td>{{ \$item->{$data->COLUMN_NAME} }}</td>";
+                        }
+                        break;
+                    default:
+                        $listTdStr .= "\r\n            <td>{{ \$item->{$data->COLUMN_NAME} }}</td>";
+
+                        break;
+
+                }
+
+            }
+        }
+
+        $str = str_replace("{{desc}}", $this->_data['desc'], $str);
+        $str = str_replace("{{path}}", $this->_data['path'], $str);
+        $str = str_replace("{{primaryKey}}",  $this->_fieldPrimary, $str);
+        $str = str_replace("{{listThStr}}",  $listThStr, $str);
+        $str = str_replace("{{listTdStr}}",  $listTdStr, $str);
+
+        $ok = file_put_contents($this->_data['viewPath'] . "/index.blade.php", $str);
+        ###check
+        $str = file_get_contents($this->_viewTpl . "/check.blade.php");
+
+        $str = str_replace("{{desc}}", $this->_data['desc'], $str);
+        $str = str_replace("{{path}}", $this->_data['path'], $str);
+        $str = str_replace("{{primaryKey}}",  $this->_fieldPrimary, $str);
+        $str = str_replace("{{listThStr}}",  $listThStr, $str);
+        $str = str_replace("{{listTdStr}}",  $listTdStr, $str);
+        $ok = file_put_contents($this->_data['viewPath'] . "/check.blade.php", $str);
+
+        #view
+        $str = file_get_contents($this->_viewTpl . "/view.blade.php");
+
+        $str = str_replace("{{desc}}", $this->_data['desc'], $str);
+        $str = str_replace("{{path}}", $this->_data['path'], $str);
+
+        $str = str_replace("{{primaryKey}}",  $this->_fieldPrimary, $str);
+        $viewTdStr = "";
+        foreach($this->_fieldData as $key=> $data) {
+            if($data->COLUMN_NAME == 'id') continue;
+            if($data->COLUMN_NAME == 'created_at') continue;
+            if($data->COLUMN_NAME == 'updated_at') continue;
+            if($data->COLUMN_NAME == 'deleted_at') continue;
+            $viewTdStr .= "                     \r\n               <div class=\"list-group-item\">
+                                                  \r\n                   <h3 class=\"list-group-item-heading\">{$data->COLUMN_COMMENT}</h3>
+                                                   \r\n                   <p class=\"list-group-item-text\">";
+
+            switch($data->DATA_TYPE) {
+                case "tinyint":
+                    if(dict()->get($this->_data['table'],$data->COLUMN_NAME)) {
+                        $viewTdStr .= "{{ dict()->get('{$this->_data['table']}','{$data->COLUMN_NAME}',\$data['{$data->COLUMN_NAME}']) }}";
+
+                    }elseif(dict()->get('global',$data->COLUMN_NAME)) {
+                        $viewTdStr .= "{{ dict()->get('global','{$data->COLUMN_NAME}',\$data['{$data->COLUMN_NAME}']) }}";
+
+                    }else{
+                        $viewTdStr .= " {{ \$data['{$data->COLUMN_NAME}'] or ''}}";
+                    }
+                    break;
+                default:
+                    $viewTdStr .= " {{ \$data['{$data->COLUMN_NAME}'] or ''}}";
+                    break;
+
+            }
+
+            $viewTdStr .= "</p>
+                                                 \r\n               </div>";
+        }
+
+        $str = str_replace("{{viewTdStr}}",  $viewTdStr, $str);
+
+        $ok = file_put_contents($this->_data['viewPath'] . "/view.blade.php", $str);
+
+        #edit
+
+        $str = file_get_contents($this->_viewTpl . "/edit.blade.php");
+
+        $str = str_replace("{{desc}}", $this->_data['desc'], $str);
+        $str = str_replace("{{path}}", $this->_data['path'], $str);
+
+        $str = str_replace("{{primaryKey}}",  $this->_fieldPrimary, $str);
+        $editTdStr = "";
+        foreach($this->_fieldData as $data) {
+            if(!in_array($data->COLUMN_NAME,[$this->_fieldPrimary,'created_at','updated_at',"deleted_at"])) {
+                $editTdStr .= "    \r\n                <div class=\"form-group\">
+                                    \r\n                 <label class=\"control-label col-sm-3\">{$data->COLUMN_COMMENT}</label>
+                                    \r\n                   <div class=\"col-sm-9\">";
+
+                switch($data->DATA_TYPE) {
+                    case "tinyint":
+
+
+                        if(dict()->get($this->_data['table'],$data->COLUMN_NAME)) {
+                            $editTdStr .= " @foreach(dict()->get('{$this->_data['table']}','{$data->COLUMN_NAME}') as \$key=>\$val)
+                                                   <label class=\"radio-inline\">
+                                                       <input type=\"radio\" name=\"data[{$data->COLUMN_NAME}]\" value=\"\$key\" @if(isset(\$data['{$data->COLUMN_NAME}']) && \$data['{$data->COLUMN_NAME}'] == \$key)checked=\"checked\" @endif/>{{\$val}}
+                                                   </label>
+                                            @endforeach";
+
+                        }elseif(dict()->get('global',$data->COLUMN_NAME)) {
+                            $editTdStr .= " @foreach(dict()->get('global','{$data->COLUMN_NAME}') as \$key=>\$val)
+                                                   <label class=\"radio-inline\">
+                                                       <input type=\"radio\" name=\"data[{$data->COLUMN_NAME}]\" value=\"\{{\$key}}\" @if(isset(\$data['{$data->COLUMN_NAME}']) && \$data['{$data->COLUMN_NAME}'] == \$key)checked=\"checked\" @endif/>{{\$val}}
+                                                   </label>
+                                            @endforeach";
+
+                        }else{
+                            $editTdStr .= "\r\n                     <input id=\"data_{$data->COLUMN_NAME}\" name=\"data[{$data->COLUMN_NAME}]\" class=\"form-control\" value=\"{{ \$data['{$data->COLUMN_NAME}'] or ''}}\" required=\"\" aria-required=\"true\"  placeholder=\"\">";
+                        }
+                        break;
+                    case "text":
+                        $editTdStr .= "\r\n                     {!! editor('') !!}
+                                       \r\n                     <script id=\"container\" name=\"data[{$data->COLUMN_NAME}]\" type=\"text/plain\">{!! \$data['{$data->COLUMN_NAME}'] or '' !!}</script>
+                                           ";
+
+                        break;
+                    case "datetime":
+                        $editTdStr .= "\r\n  <input name=\"data[{$data->COLUMN_NAME}]\" class=\"form-control laydate-icon help-block m-b-none\" style=\"width:200px; height:34px;\" value=\"{{ \$data['{$data->COLUMN_NAME}'] or ''}}\" placeholder=\"{$data->COLUMN_COMMENT}\" onclick=\"laydate({istime: true, format: 'YYYY-MM-DD hh:mm:ss'})\" aria-invalid=\"false\">";
+
+
+                        break;
+                    default:
+                        if($data->COLUMN_NAME == 'image' || $data->COLUMN_NAME == 'pic' || $data->COLUMN_NAME == 'picture' || $data->COLUMN_NAME == 'photo' || $data->COLUMN_NAME == 'avatar'){
+                            $editTdStr .= "\r\n   {!!  widget('Tools.ImgUpload')->single('{$data->COLUMN_NAME}','data[{$data->COLUMN_NAME}]', isset(\$data['{$data->COLUMN_NAME}'])? \$data['{$data->COLUMN_NAME}'] : '') !!}  ";
+                        }else{
+                            $editTdStr .= "\r\n                     <input id=\"data_{$data->COLUMN_NAME}\" name=\"data[{$data->COLUMN_NAME}]\" class=\"form-control\" value=\"{{ \$data['{$data->COLUMN_NAME}'] or ''}}\" required=\"\" aria-required=\"true\"  placeholder=\"\">";
+                        }
+
+                        break;
+
+                }
+                $editTdStr .=" \r\n                    </div>
+                                \r\n                </div>";
+
+            }
+        }
+
+        $str = str_replace("{{editTdStr}}",  $editTdStr, $str);
+
+        $ok = file_put_contents($this->_data['viewPath'] . "/edit.blade.php", $str);
+        return true;
+    }
+
+    public function customMkdir($dir)
+    {
+        if(!file_exists($dir)) {
+            \File::makeDirectory($dir,  $mode = 0755, $recursive = true);
+        }
+    }
+
+
+
+}

+ 138 - 0
app/Services/CRUD/tpl/controller.tpl

xqd
@@ -0,0 +1,138 @@
+<?php
+/**
+ *  {{desc}}
+ *  @author  system
+ *  @version    1.0
+ *  @date {{date}}
+ *
+ */
+namespace App\Http\Controllers\Admin\{{sortPath}};
+use App\Http\Controllers\Admin\Controller;
+use Illuminate\Http\Request;
+use App\Repositories\Base\Criteria\OrderBy;
+use {{CriteriaMultiWhereUse}};
+use {{repositoriesUse}};
+
+class {{controlName}} extends Controller
+{
+    private $repository;
+
+    public function __construct({{repositoriesName}} $repository) {
+        if(!$this->repository) $this->repository = $repository;
+    }
+
+    function index(Request $request) {
+        $search['keyword'] = $request->input('keyword');
+        $query = $this->repository->pushCriteria(new MultiWhere($search));
+
+        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
+        $query = $query->pushCriteria(new OrderBy($request['sort_field'],$request['sort_field_by']));
+        }else{
+            $query = $query->pushCriteria(new OrderBy('updated_at','DESC'));
+        }
+        $list = $query->paginate();
+        return view('{{viewSortPath}}.index',compact('list'));
+    }
+
+
+    function check(Request $request) {
+        $request = $request->all();
+        $search['keyword'] = $request->input('keyword');
+        $orderby = array();
+        if(isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
+            $orderby[$request['sort_field']] = $request['sort_field_by'];
+        }
+        $list = $this->repository->search($search,$orderby);
+        return view('{{viewSortPath}}.check',compact('list'));
+    }
+
+
+    /**
+     * 添加
+     * 
+     */
+    public function create(Request $request)
+    {
+        if($request->method() == 'POST') {
+            return $this->_createSave();
+        }
+        return view('{{viewSortPath}}.edit');
+    }
+
+    /**
+     * 保存修改
+     */
+    private function _createSave(){
+        $data = (array) request('data');
+        $id = $this->repository->create($data);
+        if($id) {
+            $url[] = array('url'=>U( '{{path}}/index'),'title'=>'返回列表');
+            $url[] = array('url'=>U( '{{path}}/create'),'title'=>'继续添加');
+            $this->showMessage('添加成功',$url);
+        }else{
+            $url[] = array('url'=>U( '{{path}}/index'),'title'=>'返回列表');
+            return $this->showWarning('添加失败',$url);
+        }
+    }
+    
+    /**
+     * 
+     * 修改
+     * 
+     * 
+     */
+    public function update(Request $request) {
+        if($request->method() == 'POST') {
+            return $this->_updateSave();
+        }
+        $data = $this->repository->find($request->get('id'));
+        return view('{{viewSortPath}}.edit',compact('data'));
+    }
+
+    /**
+     * 保存修改
+     */
+    private function _updateSave() {
+        $data = (array) request('data');
+        $ok = $this->repository->update(request('id'),$data);
+        if($ok) {
+            $url[] = array('url'=>U( '{{path}}/index'),'title'=>'返回列表');
+            return $this->showMessage('操作成功',urldecode(request('_referer')));
+        }else{
+            $url[] = array('url'=>U( '{{path}}/index'),'title'=>'返回列表');
+            return $this->showWarning('操作失败',$url);
+        }
+    }
+
+    public function view(Request $request) {
+        $data = $this->repository->find(request('id'));
+        return view('{{viewSortPath}}.view',compact('data'));
+    }
+
+
+    /**
+     *
+     * 状态改变
+     *
+     */
+    public function status(Request $request) {
+        $ok = $this->repository->updateStatus(request('id'),request('status'));
+        if($ok) {
+            return $this->showMessage('操作成功');
+        }else{
+            return $this->showWarning('操作失败');
+        }
+    }
+    
+    /**
+     * 删除
+     */
+    public function destroy(Request $request) {
+        $bool = $this->repository->destroy($request->get('id'));
+        if($bool) {
+            return  $this->showMessage('操作成功');
+        }else{
+            return  $this->showWarning("操作失败");
+        }
+    }
+}

+ 42 - 0
app/Services/CRUD/tpl/creteriaMultiWhere.tpl

xqd
@@ -0,0 +1,42 @@
+<?php
+/**
+ * User: Mike
+ * Email: m@9026.com
+ * Date: 2017/1/12
+ * Time: 17:52
+ */
+
+namespace App\Repositories\{{sortPath}}\Criteria;
+
+
+
+
+use App\Repositories\Base\Criteria;
+use App\Repositories\Contracts\RepositoryInterface as Repository;
+
+class MultiWhere extends Criteria {
+
+    private $search = [];
+
+    /**
+     * MultiWhere constructor.
+     * @param array $search
+     *
+     */
+    public function __construct(array $search)
+    {
+        $this->search = $search;
+    }
+
+    /**
+    * @param $model
+    * @param RepositoryInterface $repository
+    * @return mixed
+    */
+    public function apply($model, Repository $repository)
+    {
+         {{queryKeyord}}
+         return $model;
+    }
+
+}

+ 35 - 0
app/Services/CRUD/tpl/model.tpl

xqd
@@ -0,0 +1,35 @@
+<?php
+namespace App\Models;
+use App\Models\BaseModel;
+/**
+ *  @description {{table_comment}}
+ *  @author  system;
+ *  @version    1.0
+ *  @date {{date}}
+ *
+ */
+class {{class_name}} extends BaseModel
+{
+    /**
+     * 数据表名
+     *
+     * @var string
+     *
+     */
+    protected $table = '{{table_name}}';
+    /**
+    主键
+     */
+    protected $primaryKey = '{{table_primary}}';
+
+    //分页
+    protected $perPage = PAGE_NUMS;
+
+    /**
+     * 可以被集体附值的表的字段
+     *
+     * @var string
+     */
+    protected $fillable = {{fillable}};
+
+}

+ 21 - 0
app/Services/CRUD/tpl/repositories.tpl

xqd
@@ -0,0 +1,21 @@
+<?php
+/**
+ *   {{desc}}
+ *  @author  system
+ *  @version    1.0
+ *  @date {{date}}
+ *
+ */
+namespace App\Repositories\{{sortPath}};
+
+use App\Repositories\Base\Repository;
+
+
+class {{repositoriesName}} extends Repository {
+
+    public function model() {
+        return \App\Models\{{modelName}}::class;
+    }
+
+    
+}

+ 118 - 0
app/Services/CRUD/tpl/service.tpl

xqd
@@ -0,0 +1,118 @@
+<?php
+/**
+ *   {{desc}}
+ *  @author  system
+ *  @version    1.0
+ *  @date {{date}}
+ *
+ */
+namespace App\Services\{{sortPath}};
+
+use App\Services\Base\BaseProcess;
+use {{modelUse}};
+
+class {{serviceName}} extends BaseProcess {
+    /**
+     * 模型
+     *
+     * @var object
+     * 
+     */
+    private $_objModel;
+    
+
+    /**
+     * 初始化
+     *
+     * @access public
+     * 
+     */
+    public function __construct()
+    {
+        if( ! $this->_objModel) $this->_objModel = new {{modelName}}();
+    }
+    
+    public function model() {
+        return $this->_objModel;
+    }
+    public function search(array $search,array $orderby=['{{primaryKey}}'=>'desc'],$pagesize=PAGE_NUMS)
+    {
+        $currentQuery = $this->_objModel;
+        if(isset($search['keyword']) && ! empty($search['keyword'])) {
+            $keywords = '%' . $search['keyword'] . '%';
+            $currentQuery = $currentQuery->where(function ($query) use ($keywords) {
+                {{queryKeyord}}
+            });
+        }
+        if($orderby && is_array($orderby)){
+            foreach ($orderby AS $field => $value){
+                $currentQuery = $currentQuery -> orderBy($field, $value);
+            }
+        }
+        
+        $currentQuery = $currentQuery->paginate($pagesize);
+        return $currentQuery;
+    }
+    
+    public function getAll($where,$orderby=null) {
+        //条件
+        $currentQuery = $this->_objModel;
+        if($where && is_array($where)){
+            foreach ($where AS $field => $value){
+               $currentQuery=   $currentQuery -> where($field, $value);
+            }
+        }
+        
+        //排序
+        if($orderby && is_array($orderby)){
+            foreach ($orderby AS $field => $value){
+               $currentQuery =  $currentQuery -> orderBy($field, $value);
+            }
+        }
+        return $currentQuery->get();
+    }
+    
+    public function find($id) {
+        return $this->_objModel->find($id);
+    }
+    /**
+     * 添加
+     * @param unknown $data
+     */
+    public function create($data)
+    {
+        return $this->_objModel->create($data);
+    }
+    
+    /**
+     * 更新
+     * @param unknown $id
+     * @param unknown $data
+     */
+    public function update($id,$data)
+    {
+        $obj = $this->_objModel->find($id);
+        if(!$obj) {
+            $this->setMsg("没有找到要修改的数据");
+            return false;
+        }
+        $ok = $obj->update($data);
+        return $ok;
+    }
+    
+    public function updateStatus($id,$status) {
+        $data = $this->_objModel->find($id);
+        $data->status = $status;
+        return $data->save();
+    }
+    /**
+     * 删除
+     * @param unknown $id
+     */
+    public function destroy($id)
+    {
+        return $this->_objModel->destroy($id);
+    }
+    
+    
+}

+ 76 - 0
app/Services/CRUD/tpl/view/check.blade.php

xqd
@@ -0,0 +1,76 @@
+@extends('admin.layout')
+
+@section('content')
+		<div class="row">
+			<div class="col-sm-12">
+				<div class="ibox float-e-margins">
+					<div class="ibox-title">
+						<h5>{{desc}}</h5>
+						<div class="ibox-tools">
+							<a class="collapse-link"> <i class="fa fa-chevron-up"></i>
+							</a>
+						</div>
+					</div>
+					<div class="ibox-content">
+						<div class="row">
+							<form method="GET" action="" accept-charset="UTF-8">
+
+								<div class="col-sm-4">
+									<div class="input-group">
+										<input type="text" value="{{Request::get('keyword')}}"	placeholder="请输入关键词" name="keyword"class="input-sm form-control">
+								<span class="input-group-btn">
+									<button type="submit" class="btn btn-sm btn-primary">搜索</button>
+								</span>
+									</div>
+								</div>
+							</form>
+							@if(role('{{path}}/create'))
+								<div class="col-sm-3 pull-right">
+									<a href="{{ U('{{path}}/create')}}" class="btn btn-sm btn-primary pull-right">添加</a>
+								</div>
+							@endif
+						</div>
+
+						<table class="table table-striped table-bordered table-hover dataTables-example dataTable dataCheckTable">
+							<thead>
+							<tr>
+								<th><input class="btSelectAll" name="btSelectAll" type="checkbox"></th>
+								{{listThStr}}
+								<th width="22%">相关操作</th>
+							</tr>
+							</thead>
+							<tbody>
+							@if(isset($list))
+								@foreach($list as $key => $item)
+									<tr>
+									<td><input data-json='{!! json_encode($item) !!}'  name="btSelectItem" class="data_key" type="checkbox" value="{{ $item->{{primaryKey}} or 0 }}" /></td>
+									{{listTdStr}}
+									<td>
+										@if(role('{{path}}/view'))
+											<button onclick="layer.open({type: 2,area: ['80%', '90%'],content: '{{ U('{{path}}/view',['{{primaryKey}}'=>$item->{{primaryKey}}])}}'});"  class="btn btn-primary ">查看</button>
+										@endif
+									</td>
+								</tr>
+								@endforeach
+							@endif
+
+							</tbody>
+						</table>
+						<div class="row">
+							<div class="col-sm-6">
+								<div class="dataTables_info" id="DataTables_Table_0_info"
+									 role="alert" aria-live="polite" aria-relevant="all">每页{{ $list->count() }}条,共{{ $list->lastPage() }}页,总{{ $list->total() }}条。</div>
+							</div>
+							<div class="col-sm-6">
+								<div class="dataTables_paginate paging_simple_numbers" id="DataTables_Table_0_paginate">
+									{!! $list->setPath('')->appends(Request::all())->render() !!}
+								</div>
+							</div>
+						</div>
+					</div>
+				</div>
+			</div>
+		</div>
+	@include('admin.tools.check_script');
+
+@endsection

+ 59 - 0
app/Services/CRUD/tpl/view/edit.blade.php

xqd
@@ -0,0 +1,59 @@
+@extends('admin.layout')
+
+@section('content')
+
+<?php
+    if(!isset($data)) $data = array();
+    if(!$data && session("data")){
+        $data = session("data");
+    }
+    if(!$data && session('_old_input')){
+        $data = session("_old_input");
+    }
+?>
+	<div class="row">
+		<div class="col-sm-12">
+			<div class="ibox float-e-margins">
+				<div class="ibox-title">
+					<h5>{{desc}}</h5>
+					<div class="ibox-tools">
+						<a class="collapse-link"> <i class="fa fa-chevron-up"></i>
+						</a>
+					</div>
+				</div>
+				<div class="ibox-content">
+                    @if(role('{{path}}/index'))
+				    <div class="row">
+    					<div class="col-sm-3 pull-right">
+    					   <a href="{{ U('{{path}}/index')}}" class="btn btn-sm btn-primary pull-right">返回列表</a>
+    					</div>
+					</div>
+                    @endif
+
+		            <div class="row">
+                        <div class="col-lg-10">
+                            <form name="form_product" id="form-validation" action="" class="form-horizontal form-validation" accept-charset="UTF-8" method="post">
+
+                                {{editTdStr}}
+                                
+                                <div class="form-group">
+                                    <label class="control-label col-sm-3">&nbsp;</label>
+                                    <div class="col-sm-9">
+                                        <input type="hidden" name="_referer" value="<?php echo urlencode(request()->server('HTTP_REFERER'));?>"/>
+                                        <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>"/>
+                                        <input type="submit" class="btn btn-success" style="margin-right:20px;">
+                                        <input type="reset" class="btn btn-default" >
+                                    </div>
+                                </div>
+        
+                            </form>
+                        </div>
+                        <!-- /.col-lg-10 -->
+                    </div>
+                    <!-- /.row -->
+				</div>
+			</div>
+		</div>
+	</div>
+
+@endsection

+ 91 - 0
app/Services/CRUD/tpl/view/index.blade.php

xqd
@@ -0,0 +1,91 @@
+@extends('admin.layout') 
+
+@section('content')
+	<div class="row">
+		<div class="col-sm-12">
+			<div class="ibox float-e-margins">
+				<div class="ibox-title">
+					<h5>{{desc}}</h5>
+					<div class="ibox-tools">
+						<a class="collapse-link"> <i class="fa fa-chevron-up"></i>
+						</a>
+					</div>
+				</div>
+				<div class="ibox-content">
+				    <div class="row">
+				        <form method="GET" action="" accept-charset="UTF-8">
+
+				        <div class="col-sm-4">
+				            <div class="input-group">
+								<input type="text" value="{{Request::get('keyword')}}"	placeholder="请输入关键词" name="keyword"class="input-sm form-control"> 
+								<span class="input-group-btn">
+									<button type="submit" class="btn btn-sm btn-primary">搜索</button>
+								</span>
+    						</div>
+				        </div>
+				        </form>
+						@if(role('{{path}}/create'))
+    					<div class="col-sm-3 pull-right">
+    					   <a href="{{ U('{{path}}/create')}}" class="btn btn-sm btn-primary pull-right">添加</a>
+    					</div>
+						@endif
+					</div>
+					
+					<table class="table table-striped table-bordered table-hover dataTables-example dataTable">
+						<thead>
+    						<tr>
+								{{listThStr}}
+        						<th width="22%">相关操作</th>
+        					</tr>
+						</thead>
+						<tbody>
+						@if(isset($list))
+							@foreach($list as $key => $item)							<tr>
+								{{listTdStr}}
+								<td>
+									<div class="btn-group">
+										<button data-toggle="dropdown"
+											class="btn btn-warning btn-sm dropdown-toggle"
+											aria-expanded="false">
+											操作 <span class="caret"></span>
+										</button>
+										<ul class="dropdown-menu">
+
+
+											@if(role('{{path}}/update'))
+											<li><a href="{{ U('{{path}}/update',['id'=>$item->id])}}" class="font-bold">修改</a></li>
+											@endif
+
+											@if(role('{{path}}/destroy'))
+											<li class="divider"></li>
+											<li><a href="{{ U('{{path}}/destroy',['id'=>$item->id])}}" onclick="return confirm('你确定执行删除操作?');">删除</a></li>
+											@endif
+
+										</ul>
+									</div>
+								@if(role('{{path}}/view'))
+										<button onclick="layer.open({type: 2,area: ['80%', '90%'],content: '{{ U('{{path}}/view',['{{primaryKey}}'=>$item->{{primaryKey}}])}}'});"  class="btn btn-primary ">查看</button>
+									@endif
+								</td>
+							</tr>
+							@endforeach
+							@endif
+
+						</tbody>
+					</table>
+					<div class="row">
+						<div class="col-sm-6">
+							<div class="dataTables_info" id="DataTables_Table_0_info"
+								role="alert" aria-live="polite" aria-relevant="all">每页{{ $list->count() }}条,共{{ $list->lastPage() }}页,总{{ $list->total() }}条。</div>
+						</div>
+						<div class="col-sm-6">
+						<div class="dataTables_paginate paging_simple_numbers" id="DataTables_Table_0_paginate">
+						{!! $list->setPath('')->appends(Request::all())->render() !!}
+						</div>
+						</div>
+					</div>
+				</div>
+			</div>
+		</div>
+	</div>
+@endsection

+ 11 - 0
app/Services/CRUD/tpl/view/view.blade.php

xqd
@@ -0,0 +1,11 @@
+@extends('admin.layout')
+
+@section('content')
+<div class="row">
+    <div class="ibox-content">
+        <div class="list-group">
+            {{viewTdStr}}
+        </div>
+    </div>
+</div>
+@endsection

+ 61 - 0
app/Services/Log/LogRemark.php

xqd
@@ -0,0 +1,61 @@
+<?php
+/**
+ *  日志记录
+ *  @author  system
+ *  @version    1.0
+ *  @date 2016-12-28 11:54:01
+ *
+ */
+
+namespace App\Services\Log;
+
+use App\Models\LogRemarkModel;
+use App\Services\Base\BaseProcess;
+
+class LogRemark extends BaseProcess
+{
+    /**
+     * 模型
+     */
+    private $_model;
+
+    /**
+     * 初始化
+     */
+    public function __construct()
+    {
+        if( ! $this->_model ) $this->_model = new LogRemarkModel();
+    }
+
+    /**
+     * 添加日志记录
+     * @param $system 所属系统
+     * @param $system_primary 所属系统ID
+     * @param $system_key 所属系统二级主键ID
+     * @param array $data
+     * @return static
+     */
+    public function createRecord($system, $system_primary, $system_key, array $data)
+    {
+        $data['system'] = $system;
+        $data['system_primary'] = $system_primary;
+        $data['system_key'] = $system_key;
+
+        if( isset($data['status']) ){
+            $model = $this->_model
+                ->where('system', $data['system'])
+                ->where('system_primary', $data['system_primary'])
+                ->where('system_key', $data['system_key'])
+                ->where('status', $data['status'])
+                ->first();
+        }else{
+            $model = $this->_model
+                ->where('system', $data['system'])
+                ->where('system_primary', $data['system_primary'])
+                ->where('system_key', $data['system_key'])
+                ->first();
+        }
+        return $model ? $model->update($data) : $this->_model->create($data);
+    }
+
+}

+ 187 - 0
app/Services/OSS.php

xqd
@@ -0,0 +1,187 @@
+<?php
+
+namespace App\Services;
+
+use JohnLui\AliyunOSS;
+
+use Exception;
+use DateTime;
+
+class OSS {
+
+    /* 城市名称:
+     *
+     *  经典网络下可选:杭州、上海、青岛、北京、张家口、深圳、香港、硅谷、弗吉尼亚、新加坡、悉尼、日本、法兰克福、迪拜
+     *  VPC 网络下可选:杭州、上海、青岛、北京、张家口、深圳、硅谷、弗吉尼亚、新加坡、悉尼、日本、法兰克福、迪拜
+     */
+    private $city = '北京';
+
+    // 经典网络 or VPC
+    private $networkType = '经典网络';
+
+    private $AccessKeyId;
+    private $AccessKeySecret;
+
+
+    private $ossClient;
+
+    /**
+     * 私有初始化 API,非 API,不用关注
+     * @param boolean 是否使用内网
+     */
+    public function __construct($isInternal = false)
+    {
+        if ($this->networkType == 'VPC' && !$isInternal) {
+            throw new Exception("VPC 网络下不提供外网上传、下载等功能");
+        }
+        $this->ossClient = AliyunOSS::boot(
+            $this->city,
+            $this->networkType,
+            $isInternal,
+            $this->AccessKeyId = config('alioss.AccessKeyId'),
+            $this->AccessKeySecret = config('alioss.AccessKeySecret')
+        );
+    }
+
+
+    /**
+     * 使用外网上传文件
+     * @param  string bucket名称
+     * @param  string 上传之后的 OSS object 名称
+     * @param  string 上传文件路径
+     * @return boolean 上传是否成功
+     */
+    public static function publicUpload($bucketName, $ossKey, $filePath, $options = [])
+    {
+        $oss = new OSS();
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->uploadFile($ossKey, $filePath, $options);
+    }
+
+    /**
+     * 使用阿里云内网上传文件
+     * @param  string bucket名称
+     * @param  string 上传之后的 OSS object 名称
+     * @param  string 上传文件路径
+     * @return boolean 上传是否成功
+     */
+    public static function privateUpload($bucketName, $ossKey, $filePath, $options = [])
+    {
+        $oss = new OSS(true);
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->uploadFile($ossKey, $filePath, $options);
+    }
+
+
+    /**
+     * 使用外网直接上传变量内容
+     * @param  string bucket名称
+     * @param  string 上传之后的 OSS object 名称
+     * @param  string 上传的变量
+     * @return boolean 上传是否成功
+     */
+    public static function publicUploadContent($bucketName, $ossKey, $content, $options = [])
+    {
+        $oss = new OSS();
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->uploadContent($ossKey, $content, $options);
+    }
+
+    /**
+     * 使用阿里云内网直接上传变量内容
+     * @param  string bucket名称
+     * @param  string 上传之后的 OSS object 名称
+     * @param  string 上传的变量
+     * @return boolean 上传是否成功
+     */
+    public static function privateUploadContent($bucketName, $ossKey, $content, $options = [])
+    {
+        $oss = new OSS(true);
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->uploadContent($ossKey, $content, $options);
+    }
+
+
+    /**
+     * 使用外网删除文件
+     * @param  string bucket名称
+     * @param  string 目标 OSS object 名称
+     * @return boolean 删除是否成功
+     */
+    public static function publicDeleteObject($bucketName, $ossKey)
+    {
+        $oss = new OSS();
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->deleteObject($bucketName, $ossKey);
+    }
+
+    /**
+     * 使用阿里云内网删除文件
+     * @param  string bucket名称
+     * @param  string 目标 OSS object 名称
+     * @return boolean 删除是否成功
+     */
+    public static function privateDeleteObject($bucketName, $ossKey)
+    {
+        $oss = new OSS(true);
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->deleteObject($bucketName, $ossKey);
+    }
+
+
+    /**
+     * -------------------------------------------------
+     *
+     *
+     *  下面不再分公网内网出 API,也不注释了,大家自行体会吧。。。
+     *
+     *
+     * -------------------------------------------------
+     */
+
+    public function copyObject($sourceBuckt, $sourceKey, $destBucket, $destKey)
+    {
+        $oss = new OSS();
+        return $oss->ossClient->copyObject($sourceBuckt, $sourceKey, $destBucket, $destKey);
+    }
+
+    public function moveObject($sourceBuckt, $sourceKey, $destBucket, $destKey)
+    {
+        $oss = new OSS();
+        return $oss->ossClient->moveObject($sourceBuckt, $sourceKey, $destBucket, $destKey);
+    }
+
+    // 获取公开文件的 URL
+    public static function getPublicObjectURL($bucketName, $ossKey)
+    {
+        $oss = new OSS();
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->getPublicUrl($ossKey);
+    }
+    // 获取私有文件的URL,并设定过期时间,如 \DateTime('+1 day')
+    public static function getPrivateObjectURLWithExpireTime($bucketName, $ossKey, DateTime $expire_time)
+    {
+        $oss = new OSS();
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->getUrl($ossKey, $expire_time);
+    }
+
+    public static function createBucket($bucketName)
+    {
+        $oss = new OSS();
+        return $oss->ossClient->createBucket($bucketName);
+    }
+
+    public static function getAllObjectKey($bucketName)
+    {
+        $oss = new OSS();
+        return $oss->ossClient->getAllObjectKey($bucketName);
+    }
+
+    public static function getObjectMeta($bucketName, $ossKey)
+    {
+        $oss = new OSS();
+        return $oss->ossClient->getObjectMeta($bucketName, $ossKey);
+    }
+
+}

+ 132 - 0
app/Services/User/Info.php

xqd
@@ -0,0 +1,132 @@
+<?php
+/**
+ *   用户管理
+ *  @author  system
+ *  @version    1.0
+ *  @date 2017-03-23 12:56:46
+ *
+ */
+namespace App\Services\User;
+
+use App\Services\Base\BaseProcess;
+use App\Models\UserInfoModel;
+
+class Info extends BaseProcess {
+    /**
+     * 模型
+     *
+     * @var object
+     * 
+     */
+    private $_objModel;
+    
+
+    /**
+     * 初始化
+     *
+     * @access public
+     * 
+     */
+    public function __construct()
+    {
+        if( ! $this->_objModel) $this->_objModel = new UserInfoModel();
+    }
+    
+    public function model() {
+        return $this->_objModel;
+    }
+    public function search(array $search,array $orderby=['id'=>'desc'],$pagesize=PAGE_NUMS)
+    {
+        $currentQuery = $this->_objModel;
+        if(isset($search['keyword']) && ! empty($search['keyword'])) {
+            $keywords = '%' . $search['keyword'] . '%';
+            $currentQuery = $currentQuery->where(function ($query) use ($keywords) {
+                $query->where('id'  , 'like', $keywords)             
+                ->orwhere('username', 'like', $keywords)
+                ->orwhere('real_name', 'like', $keywords)
+                ->orwhere('password', 'like', $keywords)
+                ->orwhere('email', 'like', $keywords)
+                ->orwhere('mobile', 'like', $keywords)
+                ->orwhere('avatar', 'like', $keywords)
+                ->orwhere('address', 'like', $keywords)
+                ->orwhere('idcard', 'like', $keywords)
+                ->orwhere('idcard_positive', 'like', $keywords)
+                ->orwhere('idcard_back', 'like', $keywords)
+                ->orwhere('contact_name', 'like', $keywords)
+                ->orwhere('contact_mobile', 'like', $keywords)
+                ->orwhere('other_contact_name', 'like', $keywords)
+                ->orwhere('other_contact_mobile', 'like', $keywords);
+            });
+        }
+        if($orderby && is_array($orderby)){
+            foreach ($orderby AS $field => $value){
+                $currentQuery = $currentQuery -> orderBy($field, $value);
+            }
+        }
+        
+        $currentQuery = $currentQuery->paginate($pagesize);
+        return $currentQuery;
+    }
+    
+    public function getAll($where,$orderby=null) {
+        //条件
+        $currentQuery = $this->_objModel;
+        if($where && is_array($where)){
+            foreach ($where AS $field => $value){
+               $currentQuery=   $currentQuery -> where($field, $value);
+            }
+        }
+        
+        //排序
+        if($orderby && is_array($orderby)){
+            foreach ($orderby AS $field => $value){
+               $currentQuery =  $currentQuery -> orderBy($field, $value);
+            }
+        }
+        return $currentQuery->get();
+    }
+    
+    public function find($id) {
+        return $this->_objModel->find($id);
+    }
+    /**
+     * 添加
+     * @param unknown $data
+     */
+    public function create($data)
+    {
+        return $this->_objModel->create($data);
+    }
+    
+    /**
+     * 更新
+     * @param unknown $id
+     * @param unknown $data
+     */
+    public function update($id,$data)
+    {
+        $obj = $this->_objModel->find($id);
+        if(!$obj) {
+            $this->setMsg("没有找到要修改的数据");
+            return false;
+        }
+        $ok = $obj->update($data);
+        return $ok;
+    }
+    
+    public function updateStatus($id,$status) {
+        $data = $this->_objModel->find($id);
+        $data->status = $status;
+        return $data->save();
+    }
+    /**
+     * 删除
+     * @param unknown $id
+     */
+    public function destroy($id)
+    {
+        return $this->_objModel->destroy($id);
+    }
+    
+    
+}

+ 29 - 0
app/User.php

xqd
@@ -0,0 +1,29 @@
+<?php
+
+namespace App;
+
+use Illuminate\Notifications\Notifiable;
+use Illuminate\Foundation\Auth\User as Authenticatable;
+
+class User extends Authenticatable
+{
+    use Notifiable;
+
+    /**
+     * The attributes that are mass assignable.
+     *
+     * @var array
+     */
+    protected $fillable = [
+        'name', 'email', 'password',
+    ];
+
+    /**
+     * The attributes that should be hidden for arrays.
+     *
+     * @var array
+     */
+    protected $hidden = [
+        'password', 'remember_token',
+    ];
+}

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác