init 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #!/usr/bin/env php
  2. <?php
  3. /**
  4. * Yii Application Initialization Tool
  5. *
  6. * In order to run in non-interactive mode:
  7. *
  8. * init --env=Development --overwrite=n
  9. */
  10. if (!extension_loaded('openssl')) {
  11. die('The OpenSSL PHP extension is required by Yii2.');
  12. }
  13. $params = getParams();
  14. $root = str_replace('\\', '/', __DIR__);
  15. $envs = require "$root/environments/index.php";
  16. $envNames = array_keys($envs);
  17. echo "Yii Application Initialization Tool v1.0\n\n";
  18. $envName = null;
  19. $params['env'] = 'Production';
  20. if (empty($params['env']) || $params['env'] === true) {
  21. echo "Which environment do you want the application to be initialized in?\n\n";
  22. foreach ($envNames as $i => $name) {
  23. echo " [$i] $name\n";
  24. }
  25. echo "\n Your choice [0-" . (count($envs) - 1) . ', or "q" to quit] ';
  26. $answer = trim(fgets(STDIN));
  27. if (!ctype_digit($answer) || !in_array($answer, range(0, count($envs) - 1))) {
  28. echo "\n Quit initialization.\n";
  29. exit(0);
  30. }
  31. if (isset($envNames[$answer])) {
  32. $envName = $envNames[$answer];
  33. }
  34. } else {
  35. $envName = $params['env'];
  36. }
  37. if (!in_array($envName, $envNames, true)) {
  38. $envsList = implode(', ', $envNames);
  39. echo "\n $envName is not a valid environment. Try one of the following: $envsList. \n";
  40. exit(2);
  41. }
  42. $envName = 'Production';
  43. $env = $envs[$envName];
  44. if (empty($params['env'])) {
  45. echo "\n Initialize the application under '{$envNames[$answer]}' environment? [yes|no] ";
  46. $answer = trim(fgets(STDIN));
  47. if (strncasecmp($answer, 'y', 1)) {
  48. echo "\n Quit initialization.\n";
  49. exit(0);
  50. }
  51. }
  52. $rootPath = "$root/environments/{$env['path']}";
  53. if (!is_dir($rootPath)) {
  54. printError("$rootPath directory does not exist. Check path in $envName environment.");
  55. exit(3);
  56. }
  57. echo "\n Start initialization ...\n\n";
  58. $files = getFileList($rootPath);
  59. if (isset($env['skipFiles'])) {
  60. $skipFiles = $env['skipFiles'];
  61. array_walk($skipFiles, function(&$value) use($env, $root) { $value = "$root/$value"; });
  62. $files = array_diff($files, array_intersect_key($env['skipFiles'], array_filter($skipFiles, 'file_exists')));
  63. }
  64. $all = false;
  65. foreach ($files as $file) {
  66. if (!copyFile($root, "environments/{$env['path']}/$file", $file, $all, $params)) {
  67. break;
  68. }
  69. }
  70. $callbacks = ['setCookieValidationKey', 'setWritable', 'setExecutable', 'createSymlink'];
  71. foreach ($callbacks as $callback) {
  72. if (!empty($env[$callback])) {
  73. $callback($root, $env[$callback]);
  74. }
  75. }
  76. echo "\n ... initialization completed.\n\n";
  77. function getFileList($root, $basePath = '')
  78. {
  79. $files = [];
  80. $handle = opendir($root);
  81. while (($path = readdir($handle)) !== false) {
  82. if ($path === '.git' || $path === '.svn' || $path === '.' || $path === '..') {
  83. continue;
  84. }
  85. $fullPath = "$root/$path";
  86. $relativePath = $basePath === '' ? $path : "$basePath/$path";
  87. if (is_dir($fullPath)) {
  88. $files = array_merge($files, getFileList($fullPath, $relativePath));
  89. } else {
  90. $files[] = $relativePath;
  91. }
  92. }
  93. closedir($handle);
  94. return $files;
  95. }
  96. function copyFile($root, $source, $target, &$all, $params)
  97. {
  98. if (!is_file($root . '/' . $source)) {
  99. echo " skip $target ($source not exist)\n";
  100. return true;
  101. }
  102. if (is_file($root . '/' . $target)) {
  103. if (file_get_contents($root . '/' . $source) === file_get_contents($root . '/' . $target)) {
  104. echo " unchanged $target\n";
  105. return true;
  106. }
  107. if ($all) {
  108. echo " overwrite $target\n";
  109. } else {
  110. echo " exist $target\n";
  111. echo " ...overwrite? [Yes|No|All|Quit] ";
  112. //$answer = !empty($params['overwrite']) ? $params['overwrite'] : trim(fgets(STDIN));
  113. $answer = 'y';
  114. if (!strncasecmp($answer, 'q', 1)) {
  115. return false;
  116. } else {
  117. if (!strncasecmp($answer, 'y', 1)) {
  118. echo " overwrite $target\n";
  119. } else {
  120. if (!strncasecmp($answer, 'a', 1)) {
  121. echo " overwrite $target\n";
  122. $all = true;
  123. } else {
  124. echo " skip $target\n";
  125. return true;
  126. }
  127. }
  128. }
  129. }
  130. file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
  131. return true;
  132. }
  133. echo " generate $target\n";
  134. @mkdir(dirname($root . '/' . $target), 0777, true);
  135. file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source));
  136. return true;
  137. }
  138. function getParams()
  139. {
  140. $rawParams = [];
  141. if (isset($_SERVER['argv'])) {
  142. $rawParams = $_SERVER['argv'];
  143. array_shift($rawParams);
  144. }
  145. $params = [];
  146. foreach ($rawParams as $param) {
  147. if (preg_match('/^--([\w-]*\w)(=(.*))?$/', $param, $matches)) {
  148. $name = $matches[1];
  149. $params[$name] = isset($matches[3]) ? $matches[3] : true;
  150. } else {
  151. $params[] = $param;
  152. }
  153. }
  154. return $params;
  155. }
  156. function setWritable($root, $paths)
  157. {
  158. foreach ($paths as $writable) {
  159. if (is_dir("$root/$writable")) {
  160. if (@chmod("$root/$writable", 0777)) {
  161. echo " chmod 0777 $writable\n";
  162. } else {
  163. printError("Operation chmod not permitted for directory $writable.");
  164. }
  165. } else {
  166. printError("Directory $writable does not exist.");
  167. }
  168. }
  169. }
  170. function setExecutable($root, $paths)
  171. {
  172. foreach ($paths as $executable) {
  173. if (file_exists("$root/$executable")) {
  174. if (@chmod("$root/$executable", 0755)) {
  175. echo " chmod 0755 $executable\n";
  176. } else {
  177. printError("Operation chmod not permitted for $executable.");
  178. }
  179. } else {
  180. printError("$executable does not exist.");
  181. }
  182. }
  183. }
  184. function setCookieValidationKey($root, $paths)
  185. {
  186. foreach ($paths as $file) {
  187. echo " generate cookie validation key in $file\n";
  188. $file = $root . '/' . $file;
  189. $length = 32;
  190. $bytes = openssl_random_pseudo_bytes($length);
  191. $key = strtr(substr(base64_encode($bytes), 0, $length), '+/=', '_-.');
  192. $content = preg_replace('/(("|\')cookieValidationKey("|\')\s*=>\s*)(""|\'\')/', "\\1'$key'", file_get_contents($file));
  193. file_put_contents($file, $content);
  194. }
  195. }
  196. function createSymlink($root, $links)
  197. {
  198. foreach ($links as $link => $target) {
  199. //first removing folders to avoid errors if the folder already exists
  200. @rmdir($root . "/" . $link);
  201. //next removing existing symlink in order to update the target
  202. if (is_link($root . "/" . $link)) {
  203. @unlink($root . "/" . $link);
  204. }
  205. if (@symlink($root . "/" . $target, $root . "/" . $link)) {
  206. echo " symlink $root/$target $root/$link\n";
  207. } else {
  208. printError("Cannot create symlink $root/$target $root/$link.");
  209. }
  210. }
  211. }
  212. /**
  213. * Prints error message.
  214. * @param string $message message
  215. */
  216. function printError($message)
  217. {
  218. echo "\n " . formatMessage("Error. $message", ['fg-red']) . " \n";
  219. }
  220. /**
  221. * Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.
  222. *
  223. * - windows without ansicon
  224. * - not tty consoles
  225. *
  226. * @return boolean true if the stream supports ANSI colors, otherwise false.
  227. */
  228. function ansiColorsSupported()
  229. {
  230. return DIRECTORY_SEPARATOR === '\\'
  231. ? getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON'
  232. : function_exists('posix_isatty') && @posix_isatty(STDOUT);
  233. }
  234. /**
  235. * Get ANSI code of style.
  236. * @param string $name style name
  237. * @return integer ANSI code of style.
  238. */
  239. function getStyleCode($name)
  240. {
  241. $styles = [
  242. 'bold' => 1,
  243. 'fg-black' => 30,
  244. 'fg-red' => 31,
  245. 'fg-green' => 32,
  246. 'fg-yellow' => 33,
  247. 'fg-blue' => 34,
  248. 'fg-magenta' => 35,
  249. 'fg-cyan' => 36,
  250. 'fg-white' => 37,
  251. 'bg-black' => 40,
  252. 'bg-red' => 41,
  253. 'bg-green' => 42,
  254. 'bg-yellow' => 43,
  255. 'bg-blue' => 44,
  256. 'bg-magenta' => 45,
  257. 'bg-cyan' => 46,
  258. 'bg-white' => 47,
  259. ];
  260. return $styles[$name];
  261. }
  262. /**
  263. * Formats message using styles if STDOUT supports it.
  264. * @param string $message message
  265. * @param string[] $styles styles
  266. * @return string formatted message.
  267. */
  268. function formatMessage($message, $styles)
  269. {
  270. if (empty($styles) || !ansiColorsSupported()) {
  271. return $message;
  272. }
  273. return sprintf("\x1b[%sm", implode(';', array_map('getStyleCode', $styles))) . $message . "\x1b[0m";
  274. }