ProjectTask.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  10. * @link http://cakephp.org CakePHP(tm) Project
  11. * @since CakePHP(tm) v 1.2
  12. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  13. */
  14. namespace Cake\Console\Command\Task;
  15. use Cake\Console\Shell;
  16. use Cake\Core\App;
  17. use Cake\Core\Configure;
  18. use Cake\Utility\File;
  19. use Cake\Utility\Folder;
  20. use Cake\Utility\Security;
  21. use Cake\Utility\String;
  22. /**
  23. * Task class for creating new project apps and plugins
  24. *
  25. * @package Cake.Console.Command.Task
  26. */
  27. class ProjectTask extends Shell {
  28. /**
  29. * configs path (used in testing).
  30. *
  31. * @var string
  32. */
  33. public $configPath = null;
  34. /**
  35. * Checks that given project path does not already exist, and
  36. * finds the app directory in it. Then it calls bake() with that information.
  37. *
  38. * @return mixed
  39. */
  40. public function execute() {
  41. $project = null;
  42. if (isset($this->args[0])) {
  43. $project = $this->args[0];
  44. } else {
  45. $appContents = array_diff(scandir(APP), array('.', '..'));
  46. if (empty($appContents)) {
  47. $suggestedPath = rtrim(APP, DS);
  48. } else {
  49. $suggestedPath = APP . 'myapp';
  50. }
  51. }
  52. while (!$project) {
  53. $prompt = __d('cake_console', "What is the path to the project you want to bake?");
  54. $project = $this->in($prompt, null, $suggestedPath);
  55. }
  56. if ($project && !Folder::isAbsolute($project) && isset($_SERVER['PWD'])) {
  57. $project = $_SERVER['PWD'] . DS . $project;
  58. }
  59. $response = false;
  60. while (!$response && is_dir($project) === true && file_exists($project . 'Config' . 'boostrap.php')) {
  61. $prompt = __d('cake_console', '<warning>A project already exists in this location:</warning> %s Overwrite?', $project);
  62. $response = $this->in($prompt, array('y', 'n'), 'n');
  63. if (strtolower($response) === 'n') {
  64. $response = $project = false;
  65. }
  66. }
  67. $success = true;
  68. if ($this->bake($project)) {
  69. $path = Folder::slashTerm($project);
  70. if ($this->securitySalt($path) === true) {
  71. $this->out(__d('cake_console', ' * Random hash key created for \'Security.salt\''));
  72. } else {
  73. $this->err(__d('cake_console', 'Unable to generate random hash for \'Security.salt\', you should change it in %s', APP . 'Config' . DS . 'app.php'));
  74. $success = false;
  75. }
  76. if ($this->securityCipherSeed($path) === true) {
  77. $this->out(__d('cake_console', ' * Random seed created for \'Security.cipherSeed\''));
  78. } else {
  79. $this->err(__d('cake_console', 'Unable to generate random seed for \'Security.cipherSeed\', you should change it in %s', APP . 'Config' . DS . 'app.php'));
  80. $success = false;
  81. }
  82. if ($this->cachePrefix($path)) {
  83. $this->out(__d('cake_console', ' * Cache prefix set'));
  84. } else {
  85. $this->err(__d('cake_console', 'The cache prefix was <error>NOT</error> set'));
  86. $success = false;
  87. }
  88. $hardCode = false;
  89. if ($this->cakeOnIncludePath()) {
  90. $this->out(__d('cake_console', '<info>CakePHP is on your `include_path`. CAKE_CORE_INCLUDE_PATH will be set, but commented out.</info>'));
  91. } else {
  92. $this->out(__d('cake_console', '<warning>CakePHP is not on your `include_path`, CAKE_CORE_INCLUDE_PATH will be hard coded.</warning>'));
  93. $this->out(__d('cake_console', 'You can fix this by adding CakePHP to your `include_path`.'));
  94. $hardCode = true;
  95. }
  96. $success = $this->corePath($path, $hardCode) === true;
  97. if ($success) {
  98. $this->out(__d('cake_console', ' * CAKE_CORE_INCLUDE_PATH set to %s in Config/paths.php', CAKE_CORE_INCLUDE_PATH));
  99. } else {
  100. $this->err(__d('cake_console', 'Unable to set CAKE_CORE_INCLUDE_PATH, you should change it in %s', $path . 'Config' . DS . 'paths.php'));
  101. $success = false;
  102. }
  103. if ($success && $hardCode) {
  104. $this->out(__d('cake_console', ' * <warning>Remember to check these values after moving to production server</warning>'));
  105. }
  106. $Folder = new Folder($path);
  107. if (!$Folder->chmod($path . 'tmp', 0777)) {
  108. $this->err(__d('cake_console', 'Could not set permissions on %s', $path . DS . 'tmp'));
  109. $this->out(__d('cake_console', 'chmod -R 0777 %s', $path . DS . 'tmp'));
  110. $success = false;
  111. }
  112. if ($success) {
  113. $this->out(__d('cake_console', '<success>Project baked successfully!</success>'));
  114. } else {
  115. $this->out(__d('cake_console', 'Project baked but with <warning>some issues.</warning>.'));
  116. }
  117. return $path;
  118. }
  119. }
  120. /**
  121. * Checks PHP's include_path for CakePHP.
  122. *
  123. * @return boolean Indicates whether or not CakePHP exists on include_path
  124. */
  125. public function cakeOnIncludePath() {
  126. $paths = explode(PATH_SEPARATOR, ini_get('include_path'));
  127. foreach ($paths as $path) {
  128. if (file_exists($path . DS . 'Cake/bootstrap.php')) {
  129. return true;
  130. }
  131. }
  132. return false;
  133. }
  134. /**
  135. * Looks for a skeleton template of a Cake application,
  136. * and if not found asks the user for a path. When there is a path
  137. * this method will make a deep copy of the skeleton to the project directory.
  138. *
  139. * @param string $path Project path
  140. * @param string $skel Path to copy from
  141. * @param string $skip array of directories to skip when copying
  142. * @return mixed
  143. */
  144. public function bake($path, $skel = null, $skip = array('empty')) {
  145. if (!$skel && !empty($this->params['skel'])) {
  146. $skel = $this->params['skel'];
  147. }
  148. while (!$skel) {
  149. $skel = $this->in(
  150. __d('cake_console', "What is the path to the directory layout you wish to copy?"),
  151. null,
  152. CAKE . 'Console' . DS . 'Templates' . DS . 'skel'
  153. );
  154. if (!$skel) {
  155. $this->err(__d('cake_console', 'The directory path you supplied was empty. Please try again.'));
  156. } else {
  157. while (is_dir($skel) === false) {
  158. $skel = $this->in(
  159. __d('cake_console', 'Directory path does not exist please choose another:'),
  160. null,
  161. CAKE . 'Console' . DS . 'Templates' . DS . 'skel'
  162. );
  163. }
  164. }
  165. }
  166. $app = basename($path);
  167. $this->out(__d('cake_console', '<info>Skel Directory</info>: ') . $skel);
  168. $this->out(__d('cake_console', '<info>Will be copied to</info>: ') . $path);
  169. $this->hr();
  170. $looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y', 'n', 'q'), 'y');
  171. switch (strtolower($looksGood)) {
  172. case 'y':
  173. $Folder = new Folder($skel);
  174. if (!empty($this->params['empty'])) {
  175. $skip = array();
  176. }
  177. if ($Folder->copy(array('to' => $path, 'skip' => $skip))) {
  178. $this->hr();
  179. $this->out(__d('cake_console', '<success>Created:</success> %s in %s', $app, $path));
  180. $this->hr();
  181. } else {
  182. $this->err(__d('cake_console', "<error>Could not create</error> '%s' properly.", $app));
  183. return false;
  184. }
  185. foreach ($Folder->messages() as $message) {
  186. $this->out(String::wrap(' * ' . $message), 1, Shell::VERBOSE);
  187. }
  188. return true;
  189. case 'n':
  190. unset($this->args[0]);
  191. $this->execute();
  192. return false;
  193. case 'q':
  194. $this->out(__d('cake_console', '<error>Bake Aborted.</error>'));
  195. return false;
  196. }
  197. }
  198. /**
  199. * Generates and writes 'Security.salt'
  200. *
  201. * @param string $path Project path
  202. * @return boolean Success
  203. */
  204. public function securitySalt($path) {
  205. $File = new File($path . 'Config/app.php');
  206. $contents = $File->read();
  207. $newSalt = Security::generateAuthKey();
  208. $contents = preg_replace(
  209. "/^(\s+'salt'\s+\=\>\s+')([^']+)(',)/m",
  210. '${1}' . $newSalt . '\\3',
  211. $contents,
  212. -1,
  213. $count
  214. );
  215. if ($count && $File->write($contents)) {
  216. return true;
  217. }
  218. return false;
  219. }
  220. /**
  221. * Generates and writes 'Security.cipherSeed'
  222. *
  223. * @param string $path Project path
  224. * @return boolean Success
  225. */
  226. public function securityCipherSeed($path) {
  227. $File = new File($path . 'Config/app.php');
  228. $contents = $File->read();
  229. $newCipher = substr(bin2hex(Security::generateAuthKey()), 0, 30);
  230. $contents = preg_replace(
  231. "/^(\s+'cipherSeed'\s+\=\>\s+')([^']+)(',)/m",
  232. '${1}' . $newCipher . '\\3',
  233. $contents,
  234. -1,
  235. $count
  236. );
  237. if ($count && $File->write($contents)) {
  238. return true;
  239. }
  240. return false;
  241. }
  242. /**
  243. * Writes cache prefix using app's name
  244. *
  245. * @param string $dir Path to project
  246. * @return boolean Success
  247. */
  248. public function cachePrefix($dir) {
  249. $app = basename($dir);
  250. $File = new File($dir . 'Config/cache.php');
  251. $contents = $File->read();
  252. if (preg_match('/(\$prefix = \'myapp_\';)/', $contents, $match)) {
  253. $result = str_replace($match[0], '$prefix = \'' . $app . '_\';', $contents);
  254. return $File->write($result);
  255. }
  256. return false;
  257. }
  258. /**
  259. * Generates and writes CAKE_CORE_INCLUDE_PATH
  260. *
  261. * @param string $path Project path
  262. * @param boolean $hardCode Wether or not define calls should be hardcoded.
  263. * @return boolean Success
  264. */
  265. public function corePath($path, $hardCode = true) {
  266. if (dirname($path) !== CAKE_CORE_INCLUDE_PATH) {
  267. $filename = $path . 'Config/paths.php';
  268. if (!$this->_replaceCorePath($filename, $hardCode)) {
  269. return false;
  270. }
  271. return true;
  272. }
  273. }
  274. /**
  275. * Replaces the __CAKE_PATH__ placeholder in the template files.
  276. *
  277. * @param string $filename The filename to operate on.
  278. * @param boolean $hardCode Whether or not the define should be uncommented.
  279. * @return boolean Success
  280. */
  281. protected function _replaceCorePath($filename, $hardCode) {
  282. $contents = file_get_contents($filename);
  283. $root = strpos(CAKE_CORE_INCLUDE_PATH, '/') === 0 ? " DS . '" : "'";
  284. $corePath = $root . str_replace(DS, "' . DS . '", trim(CAKE_CORE_INCLUDE_PATH, DS)) . "'";
  285. $result = str_replace('__CAKE_PATH__', $corePath, $contents, $count);
  286. if ($hardCode) {
  287. $result = str_replace('//define(\'CAKE_CORE', 'define(\'CAKE_CORE', $result);
  288. }
  289. if (!file_put_contents($filename, $result)) {
  290. return false;
  291. }
  292. return (bool)$count;
  293. }
  294. /**
  295. * Enables Configure::read('Routing.prefixes') in /app/Config/routes.php
  296. *
  297. * @param string $name Name to use as admin routing
  298. * @return boolean Success
  299. */
  300. public function cakeAdmin($name) {
  301. $path = (empty($this->configPath)) ? APP . 'Config/' : $this->configPath;
  302. $File = new File($path . 'routes.php');
  303. $contents = $File->read();
  304. if (preg_match('%(\s*[/]*Configure::write\(\'Routing.prefixes\',[\s\'a-z,\)\(]*\);)%', $contents, $match)) {
  305. $result = str_replace($match[0], "\n" . 'Configure::write(\'Routing.prefixes\', array(\'' . $name . '\'));', $contents);
  306. if ($File->write($result)) {
  307. Configure::write('Routing.prefixes', array($name));
  308. return true;
  309. } else {
  310. return false;
  311. }
  312. } else {
  313. return false;
  314. }
  315. }
  316. /**
  317. * Checks for Configure::read('Routing.prefixes') and forces user to input it if not enabled
  318. *
  319. * @return string Admin route to use
  320. */
  321. public function getPrefix() {
  322. $admin = '';
  323. $prefixes = Configure::read('Routing.prefixes');
  324. if (!empty($prefixes)) {
  325. if (count($prefixes) === 1) {
  326. return $prefixes[0] . '_';
  327. }
  328. if ($this->interactive) {
  329. $this->out();
  330. $this->out(__d('cake_console', 'You have more than one routing prefix configured'));
  331. }
  332. $options = array();
  333. foreach ($prefixes as $i => $prefix) {
  334. $options[] = $i + 1;
  335. if ($this->interactive) {
  336. $this->out($i + 1 . '. ' . $prefix);
  337. }
  338. }
  339. $selection = $this->in(__d('cake_console', 'Please choose a prefix to bake with.'), $options, 1);
  340. return $prefixes[$selection - 1] . '_';
  341. }
  342. if ($this->interactive) {
  343. $this->hr();
  344. $this->out(__d('cake_console', 'You need to enable Configure::write(\'Routing.prefixes\',array(\'admin\')) in /app/Config/routes.php to use prefix routing.'));
  345. $this->out(__d('cake_console', 'What would you like the prefix route to be?'));
  346. $this->out(__d('cake_console', 'Example: www.example.com/admin/controller'));
  347. while (!$admin) {
  348. $admin = $this->in(__d('cake_console', 'Enter a routing prefix:'), null, 'admin');
  349. }
  350. if ($this->cakeAdmin($admin) !== true) {
  351. $this->out(__d('cake_console', '<error>Unable to write to</error> /app/Config/routes.php.'));
  352. $this->out(__d('cake_console', 'You need to enable Configure::write(\'Routing.prefixes\',array(\'admin\')) in /app/Config/routes.php to use prefix routing.'));
  353. $this->_stop();
  354. }
  355. return $admin . '_';
  356. }
  357. return '';
  358. }
  359. /**
  360. * get the option parser.
  361. *
  362. * @return ConsoleOptionParser
  363. */
  364. public function getOptionParser() {
  365. $parser = parent::getOptionParser();
  366. return $parser->description(
  367. __d('cake_console', 'Generate a new CakePHP project skeleton.')
  368. )->addArgument('name', array(
  369. 'help' => __d('cake_console', 'Application directory to make, if it starts with "/" the path is absolute.')
  370. ))->addOption('empty', array(
  371. 'boolean' => true,
  372. 'help' => __d('cake_console', 'Create empty files in each of the directories. Good if you are using git')
  373. ))->addOption('skel', array(
  374. 'default' => current(App::core('Console')) . 'Templates' . DS . 'skel',
  375. 'help' => __d('cake_console', 'The directory layout to use for the new application skeleton. Defaults to cake/Console/Templates/skel of CakePHP used to create the project.')
  376. ));
  377. }
  378. }