AppController.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: NODELOG
  5. * Date: 16/7/6
  6. * Time: 下午3:35
  7. */
  8. namespace console\controllers;
  9. use common\modules\user\models\User;
  10. use yii\console\Controller;
  11. use Yii;
  12. use yii\helpers\Console;
  13. class AppController extends Controller
  14. {
  15. public $defaultAction = 'install';
  16. public $writablePaths = [
  17. '@root/web/assets',
  18. '@root/web/admin/assets',
  19. '@root/web/storage',
  20. '@root/cache',
  21. '@api/runtime',
  22. '@backend/runtime',
  23. '@frontend/runtime',
  24. '@wechat/runtime',
  25. ];
  26. public $executablePaths = [
  27. '@root/yii',
  28. ];
  29. public $envPath = '@root/.env';
  30. public $installFile = '@root/web/storage/install.txt';
  31. /**
  32. * 设置可写
  33. */
  34. public function actionSetWritable()
  35. {
  36. $this->setWritable($this->writablePaths);
  37. }
  38. /**
  39. * 设置可执行
  40. */
  41. public function actionSetExecutable()
  42. {
  43. $this->setExecutable($this->executablePaths);
  44. }
  45. /**
  46. * 设置cookie加密key
  47. */
  48. public function actionSetKeys()
  49. {
  50. $this->setKeys($this->envPath);
  51. }
  52. public function setWritable($paths)
  53. {
  54. foreach ($paths as $writable) {
  55. $writable = Yii::getAlias($writable);
  56. Console::output("Setting writable: {$writable}");
  57. @chmod($writable, 0777);
  58. }
  59. }
  60. public function setExecutable($paths)
  61. {
  62. foreach ($paths as $executable) {
  63. $executable = Yii::getAlias($executable);
  64. Console::output("Setting executable: {$executable}");
  65. @chmod($executable, 0755);
  66. }
  67. }
  68. public function setKeys($file)
  69. {
  70. $file = Yii::getAlias($file);
  71. Console::output("Generating keys in {$file}");
  72. $content = file_get_contents($file);
  73. $content = preg_replace_callback('/<generated_key>/', function () {
  74. $length = 32;
  75. $bytes = openssl_random_pseudo_bytes(32, $cryptoStrong);
  76. return strtr(substr(base64_encode($bytes), 0, $length), '+/', '_-');
  77. }, $content);
  78. file_put_contents($file, $content);
  79. }
  80. /**
  81. * 设置数据库
  82. * @throws \yii\base\InvalidConfigException
  83. */
  84. public function actionSetDb()
  85. {
  86. do {
  87. $dbHost = $this->prompt('dbhost(默认为中括号内的值)' . PHP_EOL, ['default' => '127.0.0.1']);
  88. $dbPort = $this->prompt('dbport(默认为中括号内的值)' . PHP_EOL, ['default' => '3306']);
  89. $dbDbname = $this->prompt('dbname(不存在则自动创建)' . PHP_EOL, ['default' => 'yii']);
  90. $dbUsername = $this->prompt('dbusername(默认为中括号内的值)' . PHP_EOL, ['default' => 'root']);
  91. $dbPassword = $this->prompt('dbpassword' . PHP_EOL);
  92. $dbDsn = "mysql:host={$dbHost};port={$dbPort}";
  93. } while(!$this->testConnect($dbDsn, $dbDbname, $dbUsername, $dbPassword));
  94. $dbDsn = "mysql:host={$dbHost};port={$dbPort};dbname={$dbDbname}";
  95. $dbTablePrefix = $this->prompt('tableprefix(默认为中括号内的值)' . PHP_EOL, ['default' => 'yii2cmf_']);
  96. $this->setEnv('DB_USERNAME', $dbUsername);
  97. $this->setEnv('DB_PASSWORD', $dbPassword);
  98. $this->setEnv('DB_TABLE_PREFIX', $dbTablePrefix);
  99. $this->setEnv('DB_DSN', $dbDsn);
  100. Yii::$app->set('db', Yii::createObject([
  101. 'class' => 'yii\db\Connection',
  102. 'dsn' => $dbDsn,
  103. 'username' => $dbUsername,
  104. 'password' => $dbPassword,
  105. 'tablePrefix' => $dbTablePrefix,
  106. 'charset' => 'utf8'
  107. ])
  108. );
  109. }
  110. public function testConnect($dsn = '', $dbname, $username = '', $password = '')
  111. {
  112. try{
  113. $pdo = new \PDO($dsn, $username, $password);
  114. $sql = "CREATE DATABASE IF NOT EXISTS {$dbname} DEFAULT CHARSET utf8 COLLATE utf8_general_ci;";
  115. $pdo->query($sql);
  116. } catch(\Exception $e) {
  117. $this->stderr("\n" . $e->getMessage(), Console::FG_RED);
  118. $this->stderr("\n ... 连接失败,核对数据库信息.\n\n", Console::FG_RED, Console::BOLD);
  119. return false;
  120. }
  121. return true;
  122. }
  123. public function setEnv($name, $value)
  124. {
  125. $file = Yii::getAlias($this->envPath);
  126. $content = preg_replace("/({$name}\s*=)\s*(.*)/", "\${1}$value", file_get_contents($file));// \${1}修复后边跟数字的bug
  127. file_put_contents($file, $content);
  128. }
  129. public function checkInstalled()
  130. {
  131. return file_exists(Yii::getAlias($this->installFile));
  132. }
  133. public function setInstalled()
  134. {
  135. file_put_contents(Yii::getAlias($this->installFile), time());
  136. }
  137. // 重置安装
  138. public function resetInstall()
  139. {
  140. $this->run('/migrate/down', ['all', 'interactive' => false]);
  141. @unlink(Yii::getAlias($this->installFile));
  142. @unlink(Yii::getAlias($this->envPath));
  143. }
  144. // 安装
  145. public function actionInstall()
  146. {
  147. if ($this->checkInstalled()) {
  148. $this->stdout("\n ... 已经安装过.\n\n", Console::FG_RED);
  149. die;
  150. }
  151. $start = <<<STR
  152. +==========================================+
  153. | Welcome to setup yii2cmf |
  154. | 欢迎使用 yii2cmf 安装程序 |
  155. +------------------------------------------+
  156. | Follow the on-screen instructions please |
  157. | 请按照屏幕上的提示操作以完成安装 |
  158. +==========================================+
  159. STR;
  160. $this->stdout($start, Console::FG_GREEN);
  161. copy(Yii::getAlias('@root/.env.example'), Yii::getAlias($this->envPath));
  162. $this->runAction('set-writable', ['interactive' => $this->interactive]);
  163. $this->runAction('set-executable', ['interactive' => $this->interactive]);
  164. $this->runAction('set-keys', ['interactive' => $this->interactive]);
  165. $this->runAction('set-db', ['interactive' => $this->interactive]);
  166. $appStatus = $this->select('设置当前应用模式', ['dev' => 'dev', 'prod' => 'prod']);
  167. $this->setEnv('YII_DEBUG', $appStatus == 'prod' ? 'false' : 'true');
  168. $this->setEnv('YII_ENV', $appStatus);
  169. // 迁移
  170. Yii::$app->runAction('migrate/up', ['interactive' => false]);
  171. //创建默认用户
  172. $this->runAction('create-admin', ['interactive' => $this->interactive]);
  173. $this->setEnv('SITE_URL', $this->prompt('siteUrl'));
  174. // 清缓存
  175. Yii::$app->runAction('cache/flush-all', ['interactive' => false]);
  176. $this->setInstalled();
  177. $end = <<<STR
  178. +=================================================+
  179. | Installation completed successfully, Thanks you |
  180. | 安装成功,感谢选择和使用 yii2cmf |
  181. +------------------------------------------+
  182. | 默认后台账号:hehe 密码: 111111
  183. +=================================================+
  184. STR;
  185. $this->stdout($end, Console::FG_GREEN);
  186. }
  187. public function actionCreateAdmin()
  188. {
  189. $user = new User();
  190. $user->setScenario("create");
  191. $user->email = 'hehe@hehe.com';
  192. $user->username = 'hehe';
  193. $user->password = '111111';
  194. $user->create();
  195. }
  196. public function actionReset()
  197. {
  198. if (!$this->checkInstalled()) {
  199. $this->stdout("\n ... 还没安装.\n\n", Console::FG_RED);
  200. die;
  201. }
  202. if ($this->confirm('确定要重置安装状态吗?')) {
  203. $this->resetInstall();
  204. }
  205. }
  206. public function actionUpdate()
  207. {
  208. \Yii::$app->runAction('migrate/up', ['interactive' => $this->interactive]);
  209. }
  210. }