Projekt

Obecné

Profil

Stáhnout (98.5 KB) Statistiky
| Větev: | Tag: | Revize:
1
#!/usr/bin/php -q
2
<?php
3
/* SVN FILE: $Id: bake.php 5117 2007-05-18 16:46:55Z phpnut $ */
4
/**
5
 * Command-line code generation utility to automate programmer chores.
6
 *
7
 * Bake is CakePHP's code generation script, which can help you kickstart
8
 * application development by writing fully functional skeleton controllers,
9
 * models, and views. Going further, Bake can also write Unit Tests for you.
10
 *
11
 * PHP versions 4 and 5
12
 *
13
 * CakePHP(tm) :  Rapid Development Framework <http://www.cakephp.org/>
14
 * Copyright 2005-2007,	Cake Software Foundation, Inc.
15
 *								1785 E. Sahara Avenue, Suite 490-204
16
 *								Las Vegas, Nevada 89104
17
 *
18
 * Licensed under The MIT License
19
 * Redistributions of files must retain the above copyright notice.
20
 *
21
 * @filesource
22
 * @copyright		Copyright 2005-2007, Cake Software Foundation, Inc.
23
 * @link				http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
24
 * @package			cake
25
 * @subpackage		cake.cake.scripts.bake
26
 * @since			CakePHP(tm) v 0.10.0.1232
27
 * @version			$Revision: 5117 $
28
 * @modifiedby		$LastChangedBy: phpnut $
29
 * @lastmodified	$Date: 2007-05-18 11:46:55 -0500 (Fri, 18 May 2007) $
30
 * @license			http://www.opensource.org/licenses/mit-license.php The MIT License
31
 */
32
	define ('DS', DIRECTORY_SEPARATOR);
33
	if (function_exists('ini_set')) {
34
		ini_set('display_errors', '1');
35
		ini_set('error_reporting', '7');
36
		ini_set('max_execution_time',0);
37
	}
38

    
39
	$app = null;
40
	$root = dirname(dirname(dirname(__FILE__)));
41
	$core = null;
42
	$here = $argv[0];
43
	$help = null;
44
	$project = null;
45

    
46
	for ($i = 1; $i < count($argv); $i += 2) {
47
		switch ($argv[$i]) {
48
			case '-a':
49
			case '-app':
50
				$app = $argv[$i + 1];
51
			break;
52
			case '-c':
53
			case '-core':
54
				$core = $argv[$i + 1];
55
			break;
56
			case '-r':
57
			case '-root':
58
				$root = $argv[$i + 1];
59
			break;
60
			case '-h':
61
			case '-help':
62
				$help = true;
63
			break;
64
			case '-p':
65
			case '-project':
66
				$project = true;
67
				$projectPath = $argv[$i + 1];
68
				$app = $argv[$i + 1];
69
			break;
70
		}
71
	}
72

    
73
	if(!$app && isset($argv[1])) {
74
		$app = $argv[1];
75
	} elseif(!$app) {
76
		$app = 'app';
77
	}
78
	if(!is_dir($app)) {
79
		$project = true;
80
		$projectPath = $app;
81

    
82
	}
83
	if($project) {
84
		$app = $projectPath;
85
	}
86

    
87
	$shortPath = str_replace($root, '', $app);
88
	$shortPath = str_replace('..'.DS, '', $shortPath);
89
	$shortPath = str_replace(DS.DS, DS, $shortPath);
90

    
91
	$pathArray = explode(DS, $shortPath);
92
	if(end($pathArray) != '') {
93
		$appDir = array_pop($pathArray);
94
	} else {
95
		array_pop($pathArray);
96
		$appDir = array_pop($pathArray);
97
	}
98
	$rootDir = implode(DS, $pathArray);
99
	$rootDir = str_replace(DS.DS, DS, $rootDir);
100

    
101
	if(!$rootDir) {
102
		$rootDir = $root;
103
		$projectPath = $root.DS.$appDir;
104
	}
105

    
106
	define ('ROOT', $rootDir);
107
	define ('APP_DIR', $appDir);
108
	define ('DEBUG', 1);
109

    
110
	if(!empty($core)){
111
		define('CAKE_CORE_INCLUDE_PATH', dirname($core));
112
	}else{
113
		define('CAKE_CORE_INCLUDE_PATH', $root);
114
	}
115

    
116
	if(function_exists('ini_set')) {
117
		ini_set('include_path',ini_get('include_path').
118
													PATH_SEPARATOR.CAKE_CORE_INCLUDE_PATH.DS.
119
													PATH_SEPARATOR.ROOT.DS.APP_DIR.DS);
120
		define('APP_PATH', null);
121
		define('CORE_PATH', null);
122
	} else {
123
		define('APP_PATH', ROOT . DS . APP_DIR . DS);
124
		define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
125
	}
126

    
127
	require_once (CORE_PATH.'cake'.DS.'basics.php');
128
	require_once (CORE_PATH.'cake'.DS.'config'.DS.'paths.php');
129
	require_once (CORE_PATH.'cake'.DS.'scripts'.DS.'templates'.DS.'skel'.DS.'config'.DS.'core.php');
130
	require_once (CORE_PATH.'cake'.DS.'dispatcher.php');
131
	uses('object', 'session', 'security', 'configure', 'inflector', 'model'.DS.'connection_manager');
132

    
133
	$pattyCake = new Bake();
134
	if($help === true)
135
	{
136
		$pattyCake->help();
137
		exit();
138
	}
139
	if($project === true)
140
	{
141
		$pattyCake->project($projectPath);
142
		exit();
143
	}
144
	$pattyCake->main();
145
/**
146
 * Bake is a command-line code generation utility for automating programmer chores.
147
 *
148
 * @package		cake
149
 * @subpackage	cake.cake.scripts
150
 */
151
class Bake {
152

    
153
/**
154
 * Standard input stream.
155
 *
156
 * @var filehandle
157
 */
158
	var $stdin;
159
/**
160
 * Standard output stream.
161
 *
162
 * @var filehandle
163
 */
164
	var $stdout;
165
/**
166
 * Standard error stream.
167
 *
168
 * @var filehandle
169
 */
170
	var $stderr;
171
/**
172
 * Associated controller name.
173
 *
174
 * @var string
175
 */
176
	var $controllerName = null;
177
/**
178
 * If true, Bake will ask for permission to perform actions.
179
 *
180
 * @var boolean
181
 */
182
	var $interactive = false;
183

    
184
	var $__modelAlias = false;
185
/**
186
 * Private helper function for constructor
187
 * @access private
188
 */
189
	function __construct() {
190
		$this->stdin = fopen('php://stdin', 'r');
191
		$this->stdout = fopen('php://stdout', 'w');
192
		$this->stderr = fopen('php://stderr', 'w');
193
		$this->welcome();
194
	}
195
/**
196
 * Constructor.
197
 *
198
 * @return Bake
199
 */
200
	function Bake() {
201
		return $this->__construct();
202
	}
203
/**
204
 * Main-loop method.
205
 *
206
 */
207
	function main() {
208

    
209
		$this->stdout('');
210
		$this->stdout('');
211
		$this->stdout('Baking...');
212
		$this->hr();
213
		$this->stdout('Name: '. APP_DIR);
214
		$this->stdout('Path: '. ROOT.DS.APP_DIR);
215
		$this->hr();
216

    
217
		if(!file_exists(CONFIGS.'database.php')) {
218
			$this->stdout('');
219
			$this->stdout('Your database configuration was not found. Take a moment to create one:');
220
			$this->doDbConfig();
221
		}
222
		require_once (CONFIGS.'database.php');
223
		$this->stdout('[M]odel');
224
		$this->stdout('[C]ontroller');
225
		$this->stdout('[V]iew');
226
		$invalidSelection = true;
227

    
228
		while ($invalidSelection) {
229
			$classToBake = strtoupper($this->getInput('What would you like to Bake?', array('M', 'V', 'C')));
230
			switch($classToBake) {
231
				case 'M':
232
					$invalidSelection = false;
233
					$this->doModel();
234
					break;
235
				case 'V':
236
					$invalidSelection = false;
237
					$this->doView();
238
					break;
239
				case 'C':
240
					$invalidSelection = false;
241
					$this->doController();
242
					break;
243
				default:
244
					$this->stdout('You have made an invalid selection. Please choose a type of class to Bake by entering M, V, or C.');
245
			}
246
		}
247
	}
248
/**
249
 * Database configuration setup.
250
 *
251
 */
252
	function doDbConfig() {
253
		$this->hr();
254
		$this->stdout('Database Configuration:');
255
		$this->hr();
256

    
257
		$driver = '';
258

    
259
		while ($driver == '') {
260
			$driver = $this->getInput('What database driver would you like to use?', array('mysql','mysqli','mssql','sqlite','postgres', 'odbc'), 'mysql');
261
			if ($driver == '') {
262
				$this->stdout('The database driver supplied was empty. Please supply a database driver.');
263
			}
264
		}
265

    
266
		switch($driver) {
267
			case 'mysql':
268
			$connect = 'mysql_connect';
269
			break;
270
			case 'mysqli':
271
			$connect = 'mysqli_connect';
272
			break;
273
			case 'mssql':
274
			$connect = 'mssql_connect';
275
			break;
276
			case 'sqlite':
277
			$connect = 'sqlite_open';
278
			break;
279
			case 'postgres':
280
			$connect = 'pg_connect';
281
			break;
282
			case 'odbc':
283
			$connect = 'odbc_connect';
284
			break;
285
			default:
286
			$this->stdout('The connection parameter could not be set.');
287
			break;
288
		}
289

    
290
		$host = '';
291

    
292
		while ($host == '') {
293
			$host = $this->getInput('What is the hostname for the database server?', null, 'localhost');
294
			if ($host == '') {
295
				$this->stdout('The host name you supplied was empty. Please supply a hostname.');
296
			}
297
		}
298
		$login = '';
299

    
300
		while ($login == '') {
301
			$login = $this->getInput('What is the database username?', null, 'root');
302

    
303
			if ($login == '') {
304
				$this->stdout('The database username you supplied was empty. Please try again.');
305
			}
306
		}
307
		$password = '';
308
		$blankPassword = false;
309

    
310
		while ($password == '' && $blankPassword == false) {
311
			$password = $this->getInput('What is the database password?');
312
			if ($password == '') {
313
				$blank = $this->getInput('The password you supplied was empty. Use an empty password?', array('y', 'n'), 'n');
314
				if($blank == 'y')
315
				{
316
					$blankPassword = true;
317
				}
318
			}
319
		}
320
		$database = '';
321

    
322
		while ($database == '') {
323
			$database = $this->getInput('What is the name of the database you will be using?', null, 'cake');
324

    
325
			if ($database == '')  {
326
				$this->stdout('The database name you supplied was empty. Please try again.');
327
			}
328
		}
329

    
330
		$prefix = '';
331

    
332
		while ($prefix == '') {
333
			$prefix = $this->getInput('Enter a table prefix?', null, 'n');
334
		}
335
		if(low($prefix) == 'n') {
336
			$prefix = '';
337
		}
338

    
339
		$this->stdout('');
340
		$this->hr();
341
		$this->stdout('The following database configuration will be created:');
342
		$this->hr();
343
		$this->stdout("Driver:        $driver");
344
		$this->stdout("Connection:    $connect");
345
		$this->stdout("Host:          $host");
346
		$this->stdout("User:          $login");
347
		$this->stdout("Pass:          " . str_repeat('*', strlen($password)));
348
		$this->stdout("Database:      $database");
349
		$this->stdout("Table prefix:  $prefix");
350
		$this->hr();
351
		$looksGood = $this->getInput('Look okay?', array('y', 'n'), 'y');
352

    
353
		if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
354
			$this->bakeDbConfig($driver, $connect, $host, $login, $password, $database, $prefix);
355
		} else {
356
			$this->stdout('Bake Aborted.');
357
		}
358
	}
359
/**
360
 * Action to create a Model.
361
 *
362
 */
363
	function doModel()
364
	{
365
		$this->hr();
366
		$this->stdout('Model Bake:');
367
		$this->hr();
368
		$this->interactive = true;
369

    
370
		$useTable = null;
371
		$primaryKey = 'id';
372
		$validate = array();
373
		$associations = array();
374
		/*$usingDefault = $this->getInput('Will your model be using a database connection setting other than the default?');
375
		if (low($usingDefault) == 'y' || low($usingDefault) == 'yes')
376
		{
377
			$useDbConfig = $this->getInput('Please provide the name of the connection you wish to use.');
378
		}*/
379
		$useDbConfig = 'default';
380
		$this->__doList($useDbConfig);
381

    
382

    
383
		$enteredModel = '';
384

    
385
		while ($enteredModel == '') {
386
			$enteredModel = $this->getInput('Enter a number from the list above, or type in the name of another model.');
387

    
388
			if ($enteredModel == '' || intval($enteredModel) > count($this->__modelNames)) {
389
				$this->stdout('Error:');
390
				$this->stdout("The model name you supplied was empty, or the number \nyou selected was not an option. Please try again.");
391
				$enteredModel = '';
392
			}
393
		}
394

    
395
		if (intval($enteredModel) > 0 && intval($enteredModel) <= count($this->__modelNames)) {
396
			$currentModelName = $this->__modelNames[intval($enteredModel) - 1];
397
		} else {
398
			$currentModelName = $enteredModel;
399
		}
400

    
401
		$db =& ConnectionManager::getDataSource($useDbConfig);
402

    
403
		$useTable = Inflector::tableize($currentModelName);
404
		$fullTableName = $db->fullTableName($useTable, false);
405
		if(array_search($useTable, $this->__tables) === false) {
406
			$this->stdout("\nGiven your model named '$currentModelName', Cake would expect a database table named '" . $fullTableName . "'.");
407
			$tableIsGood = $this->getInput('do you want to use this table?', array('y','n'), 'y');
408
		}
409

    
410
		if (low($tableIsGood) == 'n' || low($tableIsGood) == 'no') {
411
			$useTable = $this->getInput('What is the name of the table (enter "null" to use NO table)?');
412
		}
413
		$tableIsGood = false;
414
		while($tableIsGood == false && low($useTable) != 'null') {
415
			if (is_array($this->__tables) && !in_array($useTable, $this->__tables)) {
416
				$fullTableName = $db->fullTableName($useTable, false);
417
				$this->stdout($fullTableName . ' does not exist.');
418
				$useTable = $this->getInput('What is the name of the table (enter "null" to use NO table)?');
419
				$tableIsGood = false;
420
			} else {
421
				$tableIsGood = true;
422
			}
423
		}
424
		$wannaDoValidation = $this->getInput('Would you like to supply validation criteria for the fields in your model?', array('y','n'), 'y');
425

    
426
		if(in_array($useTable, $this->__tables)) {
427
			loadModel();
428
			$tempModel = new Model(false, $useTable);
429
			$modelFields = $db->describe($tempModel);
430
			if(isset($modelFields[0]['name']) && $modelFields[0]['name'] != 'id') {
431
				$primaryKey = $this->getInput('What is the primaryKey?', null, $modelFields[0]['name']);
432
			}
433
		}
434
		$validate = array();
435

    
436
		if (array_search($useTable, $this->__tables) !== false && (low($wannaDoValidation) == 'y' || low($wannaDoValidation) == 'yes')) {
437
			foreach($modelFields as $field) {
438
				$this->stdout('');
439
				$prompt = 'Name: ' . $field['name'] . "\n";
440
				$prompt .= 'Type: ' . $field['type'] . "\n";
441
				$prompt .= '---------------------------------------------------------------'."\n";
442
				$prompt .= 'Please select one of the following validation options:'."\n";
443
				$prompt .= '---------------------------------------------------------------'."\n";
444
				$prompt .= "1- VALID_NOT_EMPTY\n";
445
				$prompt .= "2- VALID_EMAIL\n";
446
				$prompt .= "3- VALID_NUMBER\n";
447
				$prompt .= "4- VALID_YEAR\n";
448
				$prompt .= "5- Do not do any validation on this field.\n\n";
449
				$prompt .= "... or enter in a valid regex validation string.\n\n";
450

    
451
				if($field['null'] == 1 || $field['name'] == $primaryKey || $field['name'] == 'created' || $field['name'] == 'modified') {
452
					$validation = $this->getInput($prompt, null, '5');
453
				} else {
454
					$validation = $this->getInput($prompt, null, '1');
455
				}
456

    
457
				switch ($validation) {
458
					case '1':
459
						$validate[$field['name']] = 'VALID_NOT_EMPTY';
460
						break;
461
					case '2':
462
						$validate[$field['name']] = 'VALID_EMAIL';
463
						break;
464
					case '3':
465
						$validate[$field['name']] = 'VALID_NUMBER';
466
						break;
467
					case '4':
468
						$validate[$field['name']] = 'VALID_YEAR';
469
						break;
470
					case '5':
471
						break;
472
					default:
473
						$validate[$field['name']] = $validation;
474
					break;
475
				}
476
			}
477
		}
478

    
479
		$wannaDoAssoc = $this->getInput('Would you like to define model associations (hasMany, hasOne, belongsTo, etc.)?', array('y','n'), 'y');
480

    
481
		if((low($wannaDoAssoc) == 'y' || low($wannaDoAssoc) == 'yes')) {
482
			$this->stdout('One moment while I try to detect any associations...');
483
			$possibleKeys = array();
484
			//Look for belongsTo
485
			$i = 0;
486
			foreach($modelFields as $field) {
487
				$offset = strpos($field['name'], '_id');
488
				if($field['name'] != $primaryKey && $offset !== false) {
489
					$tmpModelName = $this->__modelNameFromKey($field['name']);
490
					$associations['belongsTo'][$i]['alias'] = $tmpModelName;
491
					$associations['belongsTo'][$i]['className'] = $tmpModelName;
492
					$associations['belongsTo'][$i]['foreignKey'] = $field['name'];
493
					$i++;
494
				}
495
			}
496
			//Look for hasOne and hasMany and hasAndBelongsToMany
497
			$i = 0;
498
			$j = 0;
499
			foreach($this->__tables as $otherTable) {
500
				$tempOtherModel = & new Model(false, $otherTable);
501
				$modelFieldsTemp = $db->describe($tempOtherModel);
502
				foreach($modelFieldsTemp as $field) {
503
					if($field['type'] == 'integer' || $field['type'] == 'string') {
504
						$possibleKeys[$otherTable][] = $field['name'];
505
					}
506
					if($field['name'] != $primaryKey && $field['name'] == $this->__modelKey($currentModelName)) {
507
						$tmpModelName = $this->__modelName($otherTable);
508
						$associations['hasOne'][$j]['alias'] = $tmpModelName;
509
						$associations['hasOne'][$j]['className'] = $tmpModelName;
510
						$associations['hasOne'][$j]['foreignKey'] = $field['name'];
511

    
512
						$associations['hasMany'][$j]['alias'] = $tmpModelName;
513
						$associations['hasMany'][$j]['className'] = $tmpModelName;
514
						$associations['hasMany'][$j]['foreignKey'] = $field['name'];
515
						$j++;
516
					}
517
				}
518
				$offset = strpos($otherTable, $useTable . '_');
519
				if($offset !== false) {
520
					$offset = strlen($useTable . '_');
521
					$tmpModelName = $this->__modelName(substr($otherTable, $offset));
522
					$associations['hasAndBelongsToMany'][$i]['alias'] = $tmpModelName;
523
					$associations['hasAndBelongsToMany'][$i]['className'] = $tmpModelName;
524
					$associations['hasAndBelongsToMany'][$i]['foreignKey'] = $this->__modelKey($currentModelName);
525
					$associations['hasAndBelongsToMany'][$i]['associationForeignKey'] = $this->__modelKey($tmpModelName);
526
					$associations['hasAndBelongsToMany'][$i]['joinTable'] = $otherTable;
527
					$i++;
528
				}
529
				$offset = strpos($otherTable, '_' . $useTable);
530
				if ($offset !== false) {
531
					$tmpModelName = $this->__modelName(substr($otherTable, 0, $offset));
532
					$associations['hasAndBelongsToMany'][$i]['alias'] = $tmpModelName;
533
					$associations['hasAndBelongsToMany'][$i]['className'] = $tmpModelName;
534
					$associations['hasAndBelongsToMany'][$i]['foreignKey'] = $this->__modelKey($currentModelName);
535
					$associations['hasAndBelongsToMany'][$i]['associationForeignKey'] = $this->__modelKey($tmpModelName);
536
					$associations['hasAndBelongsToMany'][$i]['joinTable'] = $otherTable;
537
					$i++;
538
				}
539
			}
540
			$this->stdout('Done.');
541
			$this->hr();
542
			//if none found...
543
			if(empty($associations)) {
544
				$this->stdout('None found.');
545
			} else {
546
				$this->stdout('Please confirm the following associations:');
547
				$this->hr();
548
				if(!empty($associations['belongsTo'])) {
549
					$count = count($associations['belongsTo']);
550
					for($i = 0; $i < $count; $i++) {
551
						if($currentModelName == $associations['belongsTo'][$i]['alias']) {
552
							$response = $this->getInput("{$currentModelName} belongsTo {$associations['belongsTo'][$i]['alias']}\nThis looks like a self join. Do you want to specify an alternate association alias?", array('y','n'), 'y');
553
							if('y' == low($response) || 'yes' == low($response)) {
554
								$associations['belongsTo'][$i]['alias'] = $this->getInput("So what is the alias?", null, $associations['belongsTo'][$i]['alias']);
555
							}
556
							if($currentModelName != $associations['belongsTo'][$i]['alias']) {
557
								$response = $this->getInput("$currentModelName belongsTo {$associations['belongsTo'][$i]['alias']}?", array('y','n'), 'y');
558
							} else {
559
								$response = 'n';
560
							}
561
						} else {
562
							$response = $this->getInput("$currentModelName belongsTo {$associations['belongsTo'][$i]['alias']}?", array('y','n'), 'y');
563
						}
564
						if('n' == low($response) || 'no' == low($response)) {
565
							unset($associations['belongsTo'][$i]);
566
						}
567
					}
568
					$associations['belongsTo'] = array_merge($associations['belongsTo']);
569
				}
570

    
571
				if(!empty($associations['hasOne'])) {
572
					$count = count($associations['hasOne']);
573
					for($i = 0; $i < $count; $i++) {
574
						if($currentModelName == $associations['hasOne'][$i]['alias']) {
575
							$response = $this->getInput("{$currentModelName} hasOne {$associations['hasOne'][$i]['alias']}\nThis looks like a self join. Do you want to specify an alternate association alias?", array('y','n'), 'y');
576
							if('y' == low($response) || 'yes' == low($response)) {
577
								$associations['hasOne'][$i]['alias'] = $this->getInput("So what is the alias?", null, $associations['hasOne'][$i]['alias']);
578
							}
579
							if($currentModelName != $associations['hasOne'][$i]['alias']) {
580
								$response = $this->getInput("$currentModelName hasOne {$associations['hasOne'][$i]['alias']}?", array('y','n'), 'y');
581
							} else {
582
								$response = 'n';
583
							}
584
						} else {
585
							$response = $this->getInput("$currentModelName hasOne {$associations['hasOne'][$i]['alias']}?", array('y','n'), 'y');
586
						}
587
						if('n' == low($response) || 'no' == low($response)) {
588
							unset($associations['hasOne'][$i]);
589
						}
590
					}
591
					$associations['hasOne'] = array_merge($associations['hasOne']);
592
				}
593

    
594
				if(!empty($associations['hasMany'])) {
595
					$count = count($associations['hasMany']);
596
					for($i = 0; $i < $count; $i++) {
597
						if($currentModelName == $associations['hasMany'][$i]['alias']) {
598
							$response = $this->getInput("{$currentModelName} hasMany {$associations['hasMany'][$i]['alias']}\nThis looks like a self join. Do you want to specify an alternate association alias?", array('y','n'), 'y');
599
							if('y' == low($response) || 'yes' == low($response)) {
600
								$associations['hasMany'][$i]['alias'] = $this->getInput("So what is the alias?", null, $associations['hasMany'][$i]['alias']);
601
							}
602
							if($currentModelName != $associations['hasMany'][$i]['alias']) {
603
								$response = $this->getInput("$currentModelName hasMany {$associations['hasMany'][$i]['alias']}?", array('y','n'), 'y');
604
							} else {
605
								$response = 'n';
606
							}
607
						} else {
608
							$response = $this->getInput("$currentModelName hasMany {$associations['hasMany'][$i]['alias']}?", array('y','n'), 'y');
609
						}
610
						if('n' == low($response) || 'no' == low($response)) {
611
							unset($associations['hasMany'][$i]);
612
						}
613
					}
614
					$associations['hasMany'] = array_merge($associations['hasMany']);
615
				}
616

    
617
				if(!empty($associations['hasAndBelongsToMany'])) {
618
					$count = count($associations['hasAndBelongsToMany']);
619
					for($i = 0; $i < $count; $i++) {
620
						if($currentModelName == $associations['hasAndBelongsToMany'][$i]['alias']) {
621
							$response = $this->getInput("{$currentModelName} hasAndBelongsToMany {$associations['hasAndBelongsToMany'][$i]['alias']}\nThis looks like a self join. Do you want to specify an alternate association alias?", array('y','n'), 'y');
622
							if('y' == low($response) || 'yes' == low($response)) {
623
								$associations['hasAndBelongsToMany'][$i]['alias'] = $this->getInput("So what is the alias?", null, $associations['hasAndBelongsToMany'][$i]['alias']);
624
							}
625
							if($currentModelName != $associations['hasAndBelongsToMany'][$i]['alias']) {
626
								$response = $this->getInput("$currentModelName hasAndBelongsToMany {$associations['hasAndBelongsToMany'][$i]['alias']}?", array('y','n'), 'y');
627
							} else {
628
								$response = 'n';
629
							}
630
						} else {
631
							$response = $this->getInput("$currentModelName hasAndBelongsToMany {$associations['hasAndBelongsToMany'][$i]['alias']}?", array('y','n'), 'y');
632
						}
633
						if('n' == low($response) || 'no' == low($response)) {
634
							unset($associations['hasAndBelongsToMany'][$i]);
635
						}
636
					}
637
					$associations['hasAndBelongsToMany'] = array_merge($associations['hasAndBelongsToMany']);
638
				}
639
			}
640
			$wannaDoMoreAssoc = $this->getInput('Would you like to define some additional model associations?', array('y','n'), 'y');
641

    
642
			while((low($wannaDoMoreAssoc) == 'y' || low($wannaDoMoreAssoc) == 'yes')) {
643
				$assocs = array(1=>'belongsTo', 2=>'hasOne', 3=>'hasMany', 4=>'hasAndBelongsToMany');
644
				$bad = true;
645
				while($bad) {
646
					$this->stdout('What is the association type?');
647
					$prompt = "1- belongsTo\n";
648
					$prompt .= "2- hasOne\n";
649
					$prompt .= "3- hasMany\n";
650
					$prompt .= "4- hasAndBelongsToMany\n";
651
					$assocType = intval($this->getInput($prompt, null, null));
652

    
653
					if(intval($assocType) < 1 || intval($assocType) > 4) {
654
						$this->stdout('The selection you entered was invalid. Please enter a number between 1 and 4.');
655
					} else {
656
						$bad = false;
657
					}
658
				}
659
				$this->stdout('For the following options be very careful to match your setup exactly. Any spelling mistakes will cause errors.');
660
				$this->hr();
661
				$associationName = $this->getInput('What is the name of this association?');
662
				$className = $this->getInput('What className will '.$associationName.' use?', null, $associationName );
663
				$suggestedForeignKey = null;
664
				if($assocType == '1') {
665
					$showKeys = $possibleKeys[$useTable];
666
					$suggestedForeignKey = $this->__modelKey($associationName);
667
				} else {
668
					$otherTable = Inflector::tableize($className);
669
					if(in_array($otherTable, $this->__tables)) {
670
						if($assocType < '4') {
671
							$showKeys = $possibleKeys[$otherTable];
672
						} else {
673
							$showKeys = null;
674
						}
675
					} else {
676
						$otherTable = $this->getInput('What is the table for this class?');
677
						$showKeys = $possibleKeys[$otherTable];
678
					}
679
					$suggestedForeignKey = $this->__modelKey($currentModelName);
680
				}
681
				if(!empty($showKeys)) {
682
					$this->stdout('A helpful List of possible keys');
683
					for ($i = 0; $i < count($showKeys); $i++) {
684
						$this->stdout($i + 1 . ". " . $showKeys[$i]);
685
					}
686
					$foreignKey = $this->getInput('What is the foreignKey? Choose a number.');
687
					if (intval($foreignKey) > 0 && intval($foreignKey) <= $i ) {
688
						$foreignKey = $showKeys[intval($foreignKey) - 1];
689
					}
690
				}
691
				if(!isset($foreignKey)) {
692
					$foreignKey = $this->getInput('What is the foreignKey? Specify your own.', null, $suggestedForeignKey);
693
				}
694
				if($assocType == '4') {
695
					$associationForeignKey = $this->getInput('What is the associationForeignKey?', null, $this->__modelKey($currentModelName));
696
					$joinTable = $this->getInput('What is the joinTable?');
697
				}
698
				$associations[$assocs[$assocType]] = array_values($associations[$assocs[$assocType]]);
699
				$count = count($associations[$assocs[$assocType]]);
700
				$i = ($count > 0) ? $count : 0;
701
				$associations[$assocs[$assocType]][$i]['alias'] = $associationName;
702
				$associations[$assocs[$assocType]][$i]['className'] = $className;
703
				$associations[$assocs[$assocType]][$i]['foreignKey'] = $foreignKey;
704
				if($assocType == '4') {
705
					$associations[$assocs[$assocType]][$i]['associationForeignKey'] = $associationForeignKey;
706
					$associations[$assocs[$assocType]][$i]['joinTable'] = $joinTable;
707
				}
708
				$wannaDoMoreAssoc = $this->getInput('Define another association?', array('y','n'), 'y');
709
			}
710
		}
711
		$this->stdout('');
712
		$this->hr();
713
		$this->stdout('The following model will be created:');
714
		$this->hr();
715
		$this->stdout("Model Name:    $currentModelName");
716
		$this->stdout("DB Connection: " . ($usingDefault ? 'default' : $useDbConfig));
717
		$this->stdout("DB Table:   " . $fullTableName);
718
		if($primaryKey != 'id') {
719
			$this->stdout("Primary Key:   " . $primaryKey);
720
		}
721
		$this->stdout("Validation:    " . print_r($validate, true));
722

    
723
		if(!empty($associations)) {
724
			$this->stdout("Associations:");
725

    
726
			if(count($associations['belongsTo'])) {
727
				for($i = 0; $i < count($associations['belongsTo']); $i++) {
728
					$this->stdout("            $currentModelName belongsTo {$associations['belongsTo'][$i]['alias']}");
729
				}
730
			}
731

    
732
			if(count($associations['hasOne'])) {
733
				for($i = 0; $i < count($associations['hasOne']); $i++) {
734
					$this->stdout("            $currentModelName hasOne	{$associations['hasOne'][$i]['alias']}");
735
				}
736
			}
737

    
738
			if(count($associations['hasMany'])) {
739
				for($i = 0; $i < count($associations['hasMany']); $i++) {
740
					$this->stdout("            $currentModelName hasMany   {$associations['hasMany'][$i]['alias']}");
741
				}
742
			}
743

    
744
			if(count($associations['hasAndBelongsToMany'])) {
745
				for($i = 0; $i < count($associations['hasAndBelongsToMany']); $i++) {
746
					$this->stdout("            $currentModelName hasAndBelongsToMany {$associations['hasAndBelongsToMany'][$i]['alias']}");
747
				}
748
			}
749
		}
750
		$this->hr();
751
		$looksGood = $this->getInput('Look okay?', array('y','n'), 'y');
752

    
753
		if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
754
			if ($useTable == Inflector::tableize($currentModelName)) {
755
				// set it to null...
756
				// putting $useTable in the model
757
				// is unnecessary.
758
				$useTable = null;
759
			}
760
			$this->bakeModel($currentModelName, $useDbConfig, $useTable, $primaryKey, $validate, $associations);
761

    
762
			if ($this->doUnitTest()) {
763
				$this->bakeUnitTest('model', $currentModelName);
764
			}
765
		} else {
766
			$this->stdout('Bake Aborted.');
767
		}
768
	}
769
/**
770
 * Action to create a View.
771
 *
772
 */
773
	function doView() {
774
		$this->hr();
775
		$this->stdout('View Bake:');
776
		$this->hr();
777
		$uses = array();
778
		$wannaUseSession = 'y';
779
		$wannaDoScaffold = 'y';
780

    
781

    
782
		$useDbConfig = 'default';
783
		$this->__doList($useDbConfig, 'Controllers');
784

    
785
		$enteredController = '';
786

    
787
		while ($enteredController == '') {
788
			$enteredController = $this->getInput('Enter a number from the list above, or type in the name of another controller.');
789

    
790
			if ($enteredController == '' || intval($enteredController) > count($this->__controllerNames)) {
791
				$this->stdout('Error:');
792
				$this->stdout("The Controller name you supplied was empty, or the number \nyou selected was not an option. Please try again.");
793
				$enteredController = '';
794
			}
795
		}
796

    
797
		if (intval($enteredController) > 0 && intval($enteredController) <= count($this->__controllerNames) ) {
798
			$controllerName = $this->__controllerNames[intval($enteredController) - 1];
799
		} else {
800
			$controllerName = Inflector::camelize($enteredController);
801
		}
802

    
803
		$controllerPath = low(Inflector::underscore($controllerName));
804

    
805
		$doItInteractive = $this->getInput("Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite {$controllerClassName} views if it exist.", array('y','n'), 'y');
806

    
807
		if (low($doItInteractive) == 'y' || low($doItInteractive) == 'yes') {
808
			$this->interactive = true;
809
			$wannaDoScaffold = $this->getInput("Would you like to create some scaffolded views (index, add, view, edit) for this controller?\nNOTE: Before doing so, you'll need to create your controller and model classes (including associated models).", array('y','n'), 'n');
810
		}
811

    
812
		$admin = null;
813
		$admin_url = null;
814
		if (low($wannaDoScaffold) == 'y' || low($wannaDoScaffold) == 'yes') {
815
			$wannaDoAdmin = $this->getInput("Would you like to create the views for admin routing?", array('y','n'), 'n');
816
		}
817

    
818
		if ((low($wannaDoAdmin) == 'y' || low($wannaDoAdmin) == 'yes')) {
819
			require(CONFIGS.'core.php');
820
			if(defined('CAKE_ADMIN')) {
821
				$admin = CAKE_ADMIN . '_';
822
				$admin_url = '/'.CAKE_ADMIN;
823
			} else {
824
				$adminRoute = '';
825
				$this->stdout('You need to enable CAKE_ADMIN in /app/config/core.php to use admin routing.');
826
				$this->stdout('What would you like the admin route to be?');
827
				$this->stdout('Example: www.example.com/admin/controller');
828
				while ($adminRoute == '') {
829
					$adminRoute = $this->getInput("What would you like the admin route to be?", null, 'admin');
830
				}
831
				if($this->__addAdminRoute($adminRoute) !== true){
832
					$this->stdout('Unable to write to /app/config/core.php.');
833
					$this->stdout('You need to enable CAKE_ADMIN in /app/config/core.php to use admin routing.');
834
					exit();
835
				} else {
836
					$admin = $adminRoute . '_';
837
					$admin_url = '/'.$adminRoute;
838
				}
839
			}
840
		}
841
		if (low($wannaDoScaffold) == 'y' || low($wannaDoScaffold) == 'yes') {
842
			$file = CONTROLLERS . $controllerPath . '_controller.php';
843

    
844
			if(!file_exists($file)) {
845
				$shortPath = str_replace(ROOT, null, $file);
846
				$shortPath = str_replace('../', '', $shortPath);
847
				$shortPath = str_replace('//', '/', $shortPath);
848
				$this->stdout('');
849
				$this->stdout("The file '$shortPath' could not be found.\nIn order to scaffold, you'll need to first create the controller. ");
850
				$this->stdout('');
851
				die();
852
			} else {
853
				uses('controller'.DS.'controller');
854
				loadController($controllerName);
855
				//loadModels();
856
				if($admin) {
857
					$this->__bakeViews($controllerName, $controllerPath, $admin, $admin_url);
858
				}
859
				$this->__bakeViews($controllerName, $controllerPath, null, null);
860

    
861
				$this->hr();
862
				$this->stdout('');
863
				$this->stdout('View Scaffolding Complete.'."\n");
864
			}
865
		} else {
866
			$actionName = '';
867

    
868
			while ($actionName == '') {
869
				$actionName = $this->getInput('Action Name? (use camelCased function name)');
870

    
871
				if ($actionName == '') {
872
					$this->stdout('The action name you supplied was empty. Please try again.');
873
				}
874
			}
875
			$this->stdout('');
876
			$this->hr();
877
			$this->stdout('The following view will be created:');
878
			$this->hr();
879
			$this->stdout("Controller Name: $controllerName");
880
			$this->stdout("Action Name:     $actionName");
881
			$this->stdout("Path:            app/views/" . $controllerPath . DS . Inflector::underscore($actionName) . '.thtml');
882
			$this->hr();
883
			$looksGood = $this->getInput('Look okay?', array('y','n'), 'y');
884

    
885
			if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
886
				$this->bakeView($controllerName, $actionName);
887
			} else {
888
				$this->stdout('Bake Aborted.');
889
			}
890
		}
891
	}
892

    
893
	function __bakeViews($controllerName, $controllerPath, $admin= null, $admin_url = null) {
894
		$controllerClassName = $controllerName.'Controller';
895
		$controllerObj = & new $controllerClassName();
896

    
897
		if(!in_array('Html', $controllerObj->helpers)) {
898
			$controllerObj->helpers[] = 'Html';
899
		}
900
		if(!in_array('Form', $controllerObj->helpers)) {
901
			$controllerObj->helpers[] = 'Form';
902
		}
903

    
904
		$controllerObj->constructClasses();
905
		$currentModelName = $controllerObj->modelClass;
906
		$this->__modelClass = $currentModelName;
907
		$modelKey = Inflector::underscore($currentModelName);
908
		$modelObj =& ClassRegistry::getObject($modelKey);
909
		$singularName = $this->__singularName($currentModelName);
910
		$pluralName = $this->__pluralName($currentModelName);
911
		$singularHumanName = $this->__singularHumanName($currentModelName);
912
		$pluralHumanName = $this->__pluralHumanName($controllerName);
913

    
914
		$fieldNames = $controllerObj->generateFieldNames(null, false);
915

    
916
		//-------------------------[INDEX]-------------------------//
917
		$indexView = null;
918
		if(!empty($modelObj->alias)) {
919
			foreach ($modelObj->alias as $key => $value) {
920
				$alias[] = $key;
921
			}
922
		}
923
		$indexView .= "<div class=\"{$pluralName}\">\n";
924
		$indexView .= "<h2>" . $pluralHumanName . " - Seznam</h2>\n\n";
925
		$indexView .= "<table cellpadding=\"0\" cellspacing=\"0\">\n";
926
		$indexView .= "<tr>\n";
927

    
928
		foreach ($fieldNames as $fieldName) {
929
			$indexView .= "\t<th>".$fieldName['prompt']."</th>\n";
930
		}
931
		$indexView .= "\t<th>Akce</th>\n";
932
		$indexView .= "</tr>\n";
933
		$indexView .= "<?php foreach (\${$pluralName} as \${$singularName}): ?>\n";
934
		$indexView .= "<tr>\n";
935
		$count = 0;
936
		foreach($fieldNames as $field => $value) {
937
			if(isset($value['foreignKey'])) {
938
				$otherModelName = $this->__modelName($value['model']);
939
				$otherModelKey = Inflector::underscore($otherModelName);
940
				$otherModelObj =& ClassRegistry::getObject($otherModelKey);
941
				$otherControllerName = $this->__controllerName($otherModelName);
942
				$otherControllerPath = $this->__controllerPath($otherControllerName);
943
				if(is_object($otherModelObj)) {
944
					$displayField = $otherModelObj->getDisplayField();
945
					$indexView .= "\t<td>&nbsp;<?php echo \$html->link(\$".$singularName."['{$alias[$count]}']['{$displayField}'], '{$admin_url}/" . $otherControllerPath . "/view/' .\$".$singularName."['{$alias[$count]}']['{$otherModelObj->primaryKey}'])?></td>\n";
946
				} else {
947
					$indexView .= "\t<td><?php echo \$".$singularName."['{$modelObj->name}']['{$field}']; ?></td>\n";
948
				}
949
				$count++;
950
			} else {
951
				$indexView .= "\t<td><?php echo \$".$singularName."['{$modelObj->name}']['{$field}']; ?></td>\n";
952
			}
953
		}
954
		$indexView .= "\t<td class=\"actions\">\n";
955
		$indexView .= "\t\t<?php echo \$html->link('Detail','{$admin_url}/{$controllerPath}/view/' . \$".$singularName."['{$modelObj->name}']['{$modelObj->primaryKey}'])?>\n";
956
		$indexView .= "\t\t<?php echo \$html->link('Uprav','{$admin_url}/{$controllerPath}/edit/' . \$".$singularName."['{$modelObj->name}']['{$modelObj->primaryKey}'])?>\n";
957
		$indexView .= "\t\t<?php echo \$html->link(" ;
958
		$indexView .= "\t\t\t\t'Smaž'," ;
959
		$indexView .= "\t\t\t\t'{$admin_url}/{$controllerPath}/delete/' . \$".$singularName."['{$modelObj->name}']['{$modelObj->primaryKey}'], " .
960
					  "\t\t\t\t null, " .
961
					  "\t\t\t\t 'Opravdu chcete ".$singularName." smazat? ')?>\n";
962
		$indexView .= "\t</td>\n";
963
		$indexView .= "</tr>\n";
964
		$indexView .= "<?php endforeach; ?>\n";
965
		$indexView .= "</table>\n\n";
966
		$indexView .= "<ul class=\"actions\">\n";
967
		$indexView .= "\t<li><?php echo \$html->link('Přidej {$singularHumanName}', '{$admin_url}/{$controllerPath}/add'); ?></li>\n";
968
		$indexView .= "</ul>\n";
969
		$indexView .= "</div>";
970

    
971
		//-------------------------[VIEW]-------------------------//
972
		$viewView = null;
973

    
974
		$viewView .= "<div class=\"{$singularName}\">\n";
975
		$viewView .= "<h2>" . $singularHumanName . " - Detail</h2>\n\n";
976
		$viewView .= "<dl>\n";
977
		$count = 0;
978
		foreach($fieldNames as $field => $value) {
979
			$viewView .= "\t<dt>" . $value['prompt'] . "</dt>\n";
980
			if(isset($value['foreignKey'])) {
981
				$otherModelName = $this->__modelName($value['model']);
982
				$otherModelKey = Inflector::underscore($otherModelName);
983
				$otherModelObj =& ClassRegistry::getObject($otherModelKey);
984
				$otherControllerName = $this->__controllerName($otherModelName);
985
				$otherControllerPath = $this->__controllerPath($otherControllerName);
986
				$displayField = $otherModelObj->getDisplayField();
987
				$viewView .= "\t<dd>&nbsp;<?php echo \$html->link(\$".$singularName."['{$alias[$count]}']['{$displayField}'], '{$admin_url}/" . $otherControllerPath . "/view/' .\$".$singularName."['{$alias[$count]}']['{$otherModelObj->primaryKey}'])?></dd>\n";
988
				$count++;
989
			} else {
990
				$viewView .= "\t<dd>&nbsp;<?php echo \$".$singularName."['{$modelObj->name}']['{$field}']?></dd>\n";
991
			}
992
		}
993
		$viewView .= "</dl>\n";
994
		$viewView .= "<ul class=\"actions\">\n";
995
		$viewView .= "\t<li><?php echo \$html->link('Uprav " . $singularHumanName . "',   '{$admin_url}/{$controllerPath}/edit/' . \$".$singularName."['{$modelObj->name}']['{$modelObj->primaryKey}']) ?> </li>\n";
996
		$viewView .= "\t<li><?php echo \$html->link('Smaž " . $singularHumanName . "', '{$admin_url}/{$controllerPath}/delete/' . \$".$singularName."['{$modelObj->name}']['{$modelObj->primaryKey}'], null, 'Opravdu chcete " . $singularHumanName . " smazat? ') ?> </li>\n";
997
		$viewView .= "\t<li><?php echo \$html->link('Seznam " . $pluralHumanName ."',   '{$admin_url}/{$controllerPath}/index') ?> </li>\n";
998
		$viewView .= "\t<li><?php echo \$html->link('Přidej " . $singularHumanName . "',	'{$admin_url}/{$controllerPath}/add') ?> </li>\n";
999
		foreach( $fieldNames as $field => $value ) {
1000
			if( isset( $value['foreignKey'] ) ) {
1001
				$otherModelName = $this->__modelName($value['model']);
1002
				if($otherModelName != $currentModelName) {
1003
					$otherControllerName = $this->__controllerName($otherModelName);
1004
					$otherControllerPath = $this->__controllerPath($otherControllerName);
1005
					$otherSingularHumanName = $this->__singularHumanName($value['controller']);
1006
					$otherPluralHumanName = $this->__pluralHumanName($value['controller']);
1007
					$viewView .= "\t<li><?php echo \$html->link('Seznam " . $otherSingularHumanName . "', '{$admin_url}/" . $otherControllerPath . "/index/')?> </li>\n";
1008
					$viewView .= "\t<li><?php echo \$html->link('Přidej " . $otherPluralHumanName . "', '{$admin_url}/" . $otherControllerPath . "/add/')?> </li>\n";
1009
				}
1010
			}
1011
		}
1012
		$viewView .= "</ul>\n\n";
1013

    
1014
		$viewView .= "</div>\n";
1015

    
1016

    
1017
		foreach ($modelObj->hasOne as $associationName => $relation) {
1018
			$new = true;
1019

    
1020
			$otherModelName = $this->__modelName($relation['className']);
1021
			$otherControllerName = $this->__controllerName($otherModelName);
1022
			$otherControllerPath = $this->__controllerPath($otherControllerName);
1023
			$otherSingularName = $this->__singularName($associationName);
1024
			$otherPluralHumanName = $this->__pluralHumanName($associationName);
1025
			$otherSingularHumanName = $this->__singularHumanName($associationName);
1026

    
1027
			$viewView .= "<div class=\"related\">\n";
1028
			$viewView .= "<h3> " . $otherPluralHumanName . "</h3>\n";
1029
			$viewView .= "<?php if(!empty(\$".$singularName."['{$associationName}'])): ?>\n";
1030
			$viewView .= "<dl>\n";
1031
			$viewView .= "\t<?php foreach(\$".$singularName."['{$associationName}'] as \$field => \$value): ?>\n";
1032
			$viewView .= "\t\t<dt><?php echo \$field ?></dt>\n";
1033
			$viewView .= "\t\t<dd>&nbsp;<?php echo \$value ?></dd>\n";
1034
			$viewView .= "\t<?php endforeach; ?>\n";
1035
			$viewView .= "</dl>\n";
1036
			$viewView .= "<?php endif; ?>\n";
1037
			$viewView .= "<ul class=\"actions\">\n";
1038
			$viewView .= "\t<li><?php echo \$html->link('Uprav " . $otherSingularHumanName . "', '{$admin_url}/" .$otherControllerPath."/edit/' . \$".$singularName."['{$associationName}']['" . $modelObj->{$otherModelName}->primaryKey . "']);?></li>\n";
1039
			$viewView .= "\t<li><?php echo \$html->link('Přidej " . $otherSingularHumanName . "', '{$admin_url}/" .$otherControllerPath."/add/');?> </li>\n";
1040
			$viewView .= "</ul>\n";
1041
			$viewView .= "</div>\n";
1042
		}
1043
		$relations = array_merge($modelObj->hasMany, $modelObj->hasAndBelongsToMany);
1044

    
1045
		foreach($relations as $associationName => $relation) {
1046
			$otherModelName = $this->__modelName($relation['className']);
1047
			$otherControllerName = $this->__controllerName($otherModelName);
1048
			$otherControllerPath = $this->__controllerPath($otherControllerName);
1049
			$otherSingularName = $this->__singularName($associationName);
1050
			$otherPluralHumanName = $this->__pluralHumanName($associationName);
1051
			$otherSingularHumanName = $this->__singularHumanName($associationName);
1052
			$otherModelKey = Inflector::underscore($otherModelName);
1053
			$otherModelObj =& ClassRegistry::getObject($otherModelKey);
1054

    
1055
			$viewView .= "<div class=\"related\">\n";
1056
			$viewView .= "<h3> " . $otherPluralHumanName . "</h3>\n";
1057
			$viewView .= "<?php if(!empty(\$".$singularName."['{$associationName}'])):?>\n";
1058
			$viewView .= "<table cellpadding=\"0\" cellspacing=\"0\">\n";
1059
			$viewView .= "<tr>\n";
1060
			$viewView .= "<?php foreach(\$".$singularName."['{$associationName}']['0'] as \$column => \$value): ?>\n";
1061
			$viewView .= "<th><?php echo \$column?></th>\n";
1062
			$viewView .= "<?php endforeach; ?>\n";
1063
			$viewView .= "<th>Actions</th>\n";
1064
			$viewView .= "</tr>\n";
1065
			$viewView .= "<?php foreach(\$".$singularName."['{$associationName}'] as \$".$otherSingularName."):?>\n";
1066
			$viewView .= "<tr>\n";
1067
			$viewView .= "\t<?php foreach(\$".$otherSingularName." as \$column => \$value):?>\n";
1068
			$viewView .= "\t\t<td><?php echo \$value;?></td>\n";
1069
			$viewView .= "\t<?php endforeach;?>\n";
1070
			$viewView .= "\t<td class=\"actions\">\n";
1071
			$viewView .= "\t\t<?php echo \$html->link('Detail', '{$admin_url}/" . $otherControllerPath . "/view/' . \$".$otherSingularName."['{$otherModelObj->primaryKey}']);?>\n";
1072
			$viewView .= "\t\t<?php echo \$html->link('Uprav', '{$admin_url}/" . $otherControllerPath . "/edit/' . \$".$otherSingularName."['{$otherModelObj->primaryKey}']);?>\n";
1073
			$viewView .= "\t\t<?php echo \$html->link('Smaž', '{$admin_url}/" . $otherControllerPath . "/delete/' . \$".$otherSingularName."['{$otherModelObj->primaryKey}'], null, 'Opravdu chcete položku smazat?');?>\n";
1074
			$viewView .= "\t</td>\n";
1075
			$viewView .= "</tr>\n";
1076
			$viewView .= "<?php endforeach; ?>\n";
1077
			$viewView .= "</table>\n";
1078
			$viewView .= "<?php endif; ?>\n\n";
1079
			$viewView .= "<ul class=\"actions\">\n";
1080
			$viewView .= "\t<li><?php echo \$html->link('Přidej " . $otherSingularHumanName . "', '{$admin_url}/" .$otherControllerPath."/add/');?> </li>\n";
1081
			$viewView .= "</ul>\n";
1082

    
1083
			$viewView .= "</div>\n";
1084
		}
1085
		//-------------------------[ADD]-------------------------//
1086
		$addView = null;
1087
		$addView .= "<h2>Nový " . $singularHumanName . "</h2>\n";
1088
		$addView .= "<form action=\"<?php echo \$html->url('{$admin_url}/{$controllerPath}/add'); ?>\" method=\"post\">\n";
1089
		$addView .= $this->generateFields($controllerObj->generateFieldNames(null, true));
1090
		$addView .= $this->generateSubmitDiv('Přidej');
1091
		$addView .= "</form>\n";
1092
		$addView .= "<ul class=\"actions\">\n";
1093
		$addView .= "<li><?php echo \$html->link('List {$pluralHumanName}', '{$admin_url}/{$controllerPath}/index')?></li>\n";
1094
		foreach ($modelObj->belongsTo as $associationName => $relation) {
1095
			$otherModelName = $this->__modelName($associationName);
1096
			if($otherModelName != $currentModelName) {
1097
				$otherControllerName = $this->__controllerName($otherModelName);
1098
				$otherControllerPath = $this->__controllerPath($otherControllerName);
1099
				$otherSingularName = $this->__singularName($associationName);
1100
				$otherPluralName = $this->__pluralHumanName($associationName);
1101
				$addView .= "<li><?php echo \$html->link('Detail " . $otherPluralName . "', '{$admin_url}/" .$otherControllerPath."/index/');?></li>\n";
1102
				$addView .= "<li><?php echo \$html->link('Přidej " . $otherPluralName . "', '{$admin_url}/" .$otherControllerPath."/add/');?></li>\n";
1103
			}
1104
		}
1105
		$addView .= "</ul>\n";
1106
		//-------------------------[EDIT]-------------------------//
1107
		$editView = null;
1108
		$editView .= "<h2>Uprav " . $singularHumanName . "</h2>\n";
1109
		$editView .= "<form action=\"<?php echo \$html->url('{$admin_url}/{$controllerPath}/edit/'.\$html->tagValue('{$modelObj->name}/{$modelObj->primaryKey}')); ?>\" method=\"post\">\n";
1110
		$editView .= $this->generateFields($controllerObj->generateFieldNames(null, true));
1111
		$editView .= "<?php echo \$html->hidden('{$modelObj->name}/{$modelObj->primaryKey}')?>\n";
1112
		$editView .= $this->generateSubmitDiv('Ulož změny');
1113
		$editView .= "</form>\n";
1114
		$editView .= "<ul class=\"actions\">\n";
1115
		$editView .= "<li><?php echo \$html->link('Smaž','{$admin_url}/{$controllerPath}/delete/' . \$html->tagValue('{$modelObj->name}/{$modelObj->primaryKey}'), null, 'Opravdu smazat {$pluralHumanName}?');?>\n";
1116
		$editView .= "<li><?php echo \$html->link('Seznam {$pluralHumanName}', '{$admin_url}/{$controllerPath}/index')?></li>\n";
1117
		foreach ($modelObj->belongsTo as $associationName => $relation) {
1118
			$otherModelName = $this->__modelName($associationName);
1119
			if($otherModelName != $currentModelName) {
1120
				$otherControllerName = $this->__controllerName($otherModelName);
1121
				$otherControllerPath = $this->__controllerPath($otherControllerName);
1122
				$otherSingularName = $this->__singularName($associationName);
1123
				$otherPluralName = $this->__pluralHumanName($associationName);
1124
				$editView .= "<li><?php echo \$html->link('Detail " . $otherPluralName . "', '{$admin_url}/" .$otherControllerPath."/index/');?></li>\n";
1125
				$editView .= "<li><?php echo \$html->link('Přidej " . $otherPluralName . "', '{$admin_url}/" .$otherControllerPath."/add/');?></li>\n";
1126
			}
1127
		}
1128
		$editView .= "</ul>\n";
1129

    
1130
		//------------------------------------------------------------------------------------//
1131

    
1132
		if(!file_exists(VIEWS.$controllerPath)) {
1133
			mkdir(VIEWS.$controllerPath);
1134
		}
1135
		$filename = VIEWS . $controllerPath . DS .  $admin . 'index.thtml';
1136
		$this->__createFile($filename, $indexView);
1137
		$filename = VIEWS . $controllerPath . DS . $admin . 'view.thtml';
1138
		$this->__createFile($filename, $viewView);
1139
		$filename = VIEWS . $controllerPath . DS . $admin . 'add.thtml';
1140
		$this->__createFile($filename, $addView);
1141
		$filename = VIEWS . $controllerPath . DS . $admin . 'edit.thtml';
1142
		$this->__createFile($filename, $editView);
1143
	}
1144
/**
1145
 * Action to create a Controller.
1146
 *
1147
 */
1148
	function doController() {
1149
		$this->hr();
1150
		$this->stdout('Controller Bake:');
1151
		$this->hr();
1152
		$uses = array();
1153
		$helpers = array();
1154
		$components = array();
1155
		$wannaUseSession = 'y';
1156
		$wannaDoScaffolding = 'y';
1157

    
1158
		$useDbConfig = 'default';
1159
		$this->__doList($useDbConfig, 'Controllers');
1160

    
1161
		$enteredController = '';
1162

    
1163
		while ($enteredController == '') {
1164
			$enteredController = $this->getInput('Enter a number from the list above, or type in the name of another controller.');
1165

    
1166
			if ($enteredController == '' || intval($enteredController) > count($this->__controllerNames)) {
1167
				$this->stdout('Error:');
1168
				$this->stdout("The Controller name you supplied was empty, or the number \nyou selected was not an option. Please try again.");
1169
				$enteredController = '';
1170
			}
1171
		}
1172

    
1173
		if (intval($enteredController) > 0 && intval($enteredController) <= count($this->__controllerNames) ) {
1174
			$controllerName = $this->__controllerNames[intval($enteredController) - 1];
1175
		} else {
1176
			$controllerName = Inflector::camelize($enteredController);
1177
		}
1178

    
1179
		$controllerPath = low(Inflector::underscore($controllerName));
1180

    
1181
		$doItInteractive = $this->getInput("Would you like bake to build your controller interactively?\nWarning: Choosing no will overwrite {$controllerClassName} controller if it exist.", array('y','n'), 'y');
1182

    
1183
		if (low($doItInteractive) == 'y' || low($doItInteractive) == 'yes') {
1184
			$this->interactive = true;
1185

    
1186
			$wannaUseScaffold = $this->getInput("Would you like to use scaffolding?", array('y','n'), 'y');
1187

    
1188
			if (low($wannaUseScaffold) == 'n' || low($wannaUseScaffold) == 'no') {
1189

    
1190
				$wannaDoScaffolding = $this->getInput("Would you like to include some basic class methods (index(), add(), view(), edit())?", array('y','n'), 'n');
1191

    
1192
				if (low($wannaDoScaffolding) == 'y' || low($wannaDoScaffolding) == 'yes') {
1193
					$wannaDoAdmin = $this->getInput("Would you like to create the methods for admin routing?", array('y','n'), 'n');
1194
				}
1195

    
1196
				$wannaDoUses = $this->getInput("Would you like this controller to use other models besides '" . $this->__modelName($controllerName) .  "'?", array('y','n'), 'n');
1197

    
1198
				if (low($wannaDoUses) == 'y' || low($wannaDoUses) == 'yes') {
1199
					$usesList = $this->getInput("Please provide a comma separated list of the classnames of other models you'd like to use.\nExample: 'Author, Article, Book'");
1200
					$usesListTrimmed = str_replace(' ', '', $usesList);
1201
					$uses = explode(',', $usesListTrimmed);
1202
				}
1203
				$wannaDoHelpers = $this->getInput("Would you like this controller to use other helpers besides HtmlHelper and FormHelper?", array('y','n'), 'n');
1204

    
1205
				if (low($wannaDoHelpers) == 'y' || low($wannaDoHelpers) == 'yes') {
1206
					$helpersList = $this->getInput("Please provide a comma separated list of the other helper names you'd like to use.\nExample: 'Ajax, Javascript, Time'");
1207
					$helpersListTrimmed = str_replace(' ', '', $helpersList);
1208
					$helpers = explode(',', $helpersListTrimmed);
1209
				}
1210
				$wannaDoComponents = $this->getInput("Would you like this controller to use any components?", array('y','n'), 'n');
1211

    
1212
				if (low($wannaDoComponents) == 'y' || low($wannaDoComponents) == 'yes') {
1213
					$componentsList = $this->getInput("Please provide a comma separated list of the component names you'd like to use.\nExample: 'Acl, MyNiftyHelper'");
1214
					$componentsListTrimmed = str_replace(' ', '', $componentsList);
1215
					$components = explode(',', $componentsListTrimmed);
1216
				}
1217

    
1218
				$wannaUseSession = $this->getInput("Would you like to use Sessions?", array('y','n'), 'y');
1219
			} else {
1220
				$wannaDoScaffolding = 'n';
1221
			}
1222
		} else {
1223
			$wannaDoScaffolding = $this->getInput("Would you like to include some basic class methods (index(), add(), view(), edit())?", array('y','n'), 'y');
1224

    
1225
			if (low($wannaDoScaffolding) == 'y' || low($wannaDoScaffolding) == 'yes') {
1226
				$wannaDoAdmin = $this->getInput("Would you like to create the methods for admin routing?", array('y','n'), 'y');
1227
			}
1228
		}
1229

    
1230
		$admin = null;
1231
		$admin_url = null;
1232
		if ((low($wannaDoAdmin) == 'y' || low($wannaDoAdmin) == 'yes')) {
1233
			require(CONFIGS.'core.php');
1234
			if(defined('CAKE_ADMIN')) {
1235
				$admin = CAKE_ADMIN.'_';
1236
				$admin_url = '/'.CAKE_ADMIN;
1237
			} else {
1238
				$adminRoute = '';
1239
				$this->stdout('You need to enable CAKE_ADMIN in /app/config/core.php to use admin routing.');
1240
				$this->stdout('What would you like the admin route to be?');
1241
				$this->stdout('Example: www.example.com/admin/controller');
1242
				while ($adminRoute == '') {
1243
					$adminRoute = $this->getInput("What would you like the admin route to be?", null, 'admin');
1244
				}
1245
				if($this->__addAdminRoute($adminRoute) !== true){
1246
					$this->stdout('Unable to write to /app/config/core.php.');
1247
					$this->stdout('You need to enable CAKE_ADMIN in /app/config/core.php to use admin routing.');
1248
					exit();
1249
				} else {
1250
					$admin = $adminRoute . '_';
1251
					$admin_url = '/'.$adminRoute;
1252
				}
1253
			}
1254
		}
1255

    
1256
		if (low($wannaDoScaffolding) == 'y' || low($wannaDoScaffolding) == 'yes') {
1257
			//loadModels();
1258
			$actions = $this->__bakeActions($controllerName, null, null, $wannaUseSession);
1259
			if($admin) {
1260
				$actions .= $this->__bakeActions($controllerName, $admin, $admin_url, $wannaUseSession);
1261
			}
1262
		}
1263

    
1264
		if($this->interactive === true) {
1265
			$this->stdout('');
1266
			$this->hr();
1267
			$this->stdout('The following controller will be created:');
1268
			$this->hr();
1269
			$this->stdout("Controller Name:	$controllerName");
1270
			if (low($wannaUseScaffold) == 'y' || low($wannaUseScaffold) == 'yes') {
1271
				$this->stdout("			var \$scaffold;");
1272
			}
1273
			if(count($uses)) {
1274
				$this->stdout("Uses:            ", false);
1275

    
1276
				foreach($uses as $use) {
1277
					if ($use != $uses[count($uses) - 1]) {
1278
						$this->stdout(ucfirst($use) . ", ", false);
1279
					} else {
1280
						$this->stdout(ucfirst($use));
1281
					}
1282
				}
1283
			}
1284

    
1285
			if(count($helpers)) {
1286
				$this->stdout("Helpers:			", false);
1287

    
1288
				foreach($helpers as $help) {
1289
					if ($help != $helpers[count($helpers) - 1]) {
1290
						$this->stdout(ucfirst($help) . ", ", false);
1291
					} else {
1292
						$this->stdout(ucfirst($help));
1293
					}
1294
				}
1295
			}
1296

    
1297
			if(count($components)) {
1298
				$this->stdout("Components:            ", false);
1299

    
1300
				foreach($components as $comp) {
1301
					if ($comp != $components[count($components) - 1]) {
1302
						$this->stdout(ucfirst($comp) . ", ", false);
1303
					} else {
1304
						$this->stdout(ucfirst($comp));
1305
					}
1306
				}
1307
			}
1308
			$this->hr();
1309
			$looksGood = $this->getInput('Look okay?', array('y','n'), 'y');
1310

    
1311
			if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
1312
				$this->bakeController($controllerName, $uses, $helpers, $components, $actions, $wannaUseScaffold);
1313

    
1314
				if ($this->doUnitTest()) {
1315
					$this->bakeUnitTest('controller', $controllerName);
1316
				}
1317
			} else {
1318
				$this->stdout('Bake Aborted.');
1319
			}
1320
		} else {
1321
			$this->bakeController($controllerName, $uses, $helpers, $components, $actions, $wannaUseScaffold);
1322
			if ($this->doUnitTest()) {
1323
				$this->bakeUnitTest('controller', $controllerName);
1324
			}
1325
			exit();
1326
		}
1327
	}
1328

    
1329
	function __bakeActions($controllerName, $admin = null, $admin_url = null, $wannaUseSession = 'y') {
1330
		$currentModelName = $this->__modelName($controllerName);
1331
		loadModel($currentModelName);
1332
		$modelObj =& new $currentModelName();
1333
		$controllerPath = $this->__controllerPath($controllerName);
1334
		$pluralName = $this->__pluralName($currentModelName);
1335
		$singularName = $this->__singularName($currentModelName);
1336
		$singularHumanName = $this->__singularHumanName($currentModelName);
1337
		$pluralHumanName = $this->__pluralHumanName($controllerName);
1338
		if(!class_exists($currentModelName)) {
1339
			$this->stdout('You must have a model for this class to build scaffold methods. Please try again.');
1340
			exit;
1341
		}
1342
		$actions .= "\n";
1343
		$actions .= "\tfunction {$admin}index() {\n";
1344
		$actions .= "\t\t\$this->{$currentModelName}->recursive = 0;\n";
1345
		$actions .= "\t\t\$this->set('{$pluralName}', \$this->{$currentModelName}->findAll());\n";
1346
		$actions .= "\t}\n";
1347
		$actions .= "\n";
1348
		$actions .= "\tfunction {$admin}view(\$id = null) {\n";
1349
		$actions .= "\t\tif(!\$id) {\n";
1350
		if (low($wannaUseSession) == 'y' || low($wannaUseSession) == 'yes') {
1351
		$actions .= "\t\t\t\$this->Session->setFlash('Neplatný identifikátor {$singularHumanName}.');\n";
1352
		$actions .= "\t\t\t\$this->redirect('{$admin_url}/{$controllerPath}/index');\n";
1353
		} else {
1354
		$actions .= "\t\t\t\$this->flash('Neplatný identifikátor {$singularHumanName}', '{$admin_url}/{$controllerPath}/index');\n";
1355
		}
1356
		$actions .= "\t\t}\n";
1357
		$actions .= "\t\t\$this->set('".$singularName."', \$this->{$currentModelName}->read(null, \$id));\n";
1358
		$actions .= "\t}\n";
1359
		$actions .= "\n";
1360
		/* ADD ACTION */
1361
		$actions .= "\tfunction {$admin}add() {\n";
1362
		$actions .= "\t\tif(empty(\$this->data)) {\n";
1363

    
1364
		foreach($modelObj->hasAndBelongsToMany as $associationName => $relation) {
1365
			if(!empty($associationName)) {
1366
				$otherModelName = $this->__modelName($associationName);
1367
				$otherSingularName = $this->__singularName($associationName);
1368
				$otherPluralName = $this->__pluralName($associationName);
1369
				$selectedOtherPluralName = 'selected' . ucfirst($otherPluralName);
1370
				$actions .= "\t\t\t\$this->set('{$otherPluralName}', \$this->{$currentModelName}->{$otherModelName}->generateList());\n";
1371
				$actions .= "\t\t\t\$this->set('{$selectedOtherPluralName}', null);\n";
1372
			}
1373
		}
1374
		foreach($modelObj->belongsTo as $associationName => $relation) {
1375
			if(!empty($associationName)) {
1376
				$otherModelName = $this->__modelName($associationName);
1377
				$otherSingularName = $this->__singularName($associationName);
1378
				$otherPluralName = $this->__pluralName($associationName);
1379
				$actions .= "\t\t\t\$this->set('{$otherPluralName}', \$this->{$currentModelName}->{$otherModelName}->generateList());\n";
1380
			}
1381
		}
1382
		$actions .= "\t\t\t\$this->render();\n";
1383
		$actions .= "\t\t} else {\n";
1384
		$actions .= "\t\t\t\$this->cleanUpFields();\n";
1385
		$actions .= "\t\t\tif(\$this->{$currentModelName}->save(\$this->data)) {\n";
1386
		if (low($wannaUseSession) == 'y' || low($wannaUseSession) == 'yes') {
1387
		$actions .= "\t\t\t\t\$this->Session->setFlash(' ".$this->__singularHumanName($currentModelName)." byl(a) přidán(a)');\n";
1388
		$actions .= "\t\t\t\t\$this->redirect('{$admin_url}/{$controllerPath}/index');\n";
1389
		} else {
1390
		$actions .= "\t\t\t\t\$this->flash('{$currentModelName} uložen(a).', '{$admin_url}/{$controllerPath}/index');\n";
1391
		}
1392
		$actions .= "\t\t\t} else {\n";
1393
		if (low($wannaUseSession) == 'y' || low($wannaUseSession) == 'yes') {
1394
		$actions .= "\t\t\t\t\$this->Session->setFlash('Prosím, opravte chyby.');\n";
1395
		}
1396

    
1397
		foreach($modelObj->hasAndBelongsToMany as $associationName => $relation) {
1398
			if(!empty($associationName)) {
1399
				$otherModelName = $this->__modelName($associationName);
1400
				$otherSingularName = $this->__singularName($associationName);
1401
				$otherPluralName = $this->__pluralName($associationName);
1402
				$selectedOtherPluralName = 'selected' . ucfirst($otherPluralName);
1403
				$actions .= "\t\t\t\t\$this->set('{$otherPluralName}', \$this->{$currentModelName}->{$otherModelName}->generateList());\n";
1404
				$actions .= "\t\t\t\tif(empty(\$this->data['{$associationName}']['{$associationName}'])) { \$this->data['{$associationName}']['{$associationName}'] = null; }\n";
1405
				$actions .= "\t\t\t\t\$this->set('{$selectedOtherPluralName}', \$this->data['{$associationName}']['{$associationName}']);\n";
1406
			}
1407
		}
1408
		foreach($modelObj->belongsTo as $associationName => $relation) {
1409
			if(!empty($associationName)) {
1410
				$otherModelName = $this->__modelName($associationName);
1411
				$otherSingularName = $this->__singularName($associationName);
1412
				$otherPluralName = $this->__pluralName($associationName);
1413
				$actions .= "\t\t\t\t\$this->set('{$otherPluralName}', \$this->{$currentModelName}->{$otherModelName}->generateList());\n";
1414
			}
1415
		}
1416
		$actions .= "\t\t\t}\n";
1417
		$actions .= "\t\t}\n";
1418
		$actions .= "\t}\n";
1419
		$actions .= "\n";
1420
		/* EDIT ACTION */
1421
		$actions .= "\tfunction {$admin}edit(\$id = null) {\n";
1422
		$actions .= "\t\tif(empty(\$this->data)) {\n";
1423
		$actions .= "\t\t\tif(!\$id) {\n";
1424
		if (low($wannaUseSession) == 'y' || low($wannaUseSession) == 'yes') {
1425
		$actions .= "\t\t\t\t\$this->Session->setFlash('Invalid id for {$singularHumanName}');\n";
1426
		$actions .= "\t\t\t\t\$this->redirect('{$admin_url}/{$controllerPath}/index');\n";
1427
		} else {
1428
		$actions .= "\t\t\t\t\$this->flash('Neplatný identifikátor pro {$singularHumanName}', '{$admin_url}/{$controllerPath}/index');\n";
1429
		}
1430
		$actions .= "\t\t\t}\n";
1431
		$actions .= "\t\t\t\$this->data = \$this->{$currentModelName}->read(null, \$id);\n";
1432

    
1433
		foreach($modelObj->hasAndBelongsToMany as $associationName => $relation) {
1434
			if(!empty($associationName)) {
1435
				$otherModelName = $this->__modelName($associationName);
1436
				$otherSingularName = $this->__singularName($associationName);
1437
				$otherPluralName = $this->__pluralName($associationName);
1438
				$otherModelKey = Inflector::underscore($otherModelName);
1439
				$otherModelObj =& ClassRegistry::getObject($otherModelKey);
1440
				$selectedOtherPluralName = 'selected' . ucfirst($otherPluralName);
1441
				$actions .= "\t\t\t\$this->set('{$otherPluralName}', \$this->{$currentModelName}->{$otherModelName}->generateList());\n";
1442
				$actions .= "\t\t\tif(empty(\$this->data['{$associationName}'])) { \$this->data['{$associationName}'] = null; }\n";
1443
				$actions .= "\t\t\t\$this->set('{$selectedOtherPluralName}', \$this->_selectedArray(\$this->data['{$associationName}']));\n";
1444
			}
1445
		}
1446
		foreach($modelObj->belongsTo as $associationName => $relation) {
1447
			if(!empty($associationName)) {
1448
				$otherModelName = $this->__modelName($associationName);
1449
				$otherSingularName = $this->__singularName($associationName);
1450
				$otherPluralName = $this->__pluralName($associationName);
1451
				$actions .= "\t\t\t\$this->set('{$otherPluralName}', \$this->{$currentModelName}->{$otherModelName}->generateList());\n";
1452
			}
1453
		}
1454
		$actions .= "\t\t} else {\n";
1455
		$actions .= "\t\t\t\$this->cleanUpFields();\n";
1456
		$actions .= "\t\t\tif(\$this->{$currentModelName}->save(\$this->data)) {\n";
1457
		if (low($wannaUseSession) == 'y' || low($wannaUseSession) == 'yes') {
1458
		$actions .= "\t\t\t\t\$this->Session->setFlash(' ".Inflector::humanize($currentModelName)." uložen(a)');\n";
1459
		$actions .= "\t\t\t\t\$this->redirect('{$admin_url}/{$controllerPath}/index');\n";
1460
		} else {
1461
		$actions .= "\t\t\t\t\$this->flash('{$currentModelName} uložen(a).', '{$admin_url}/{$controllerPath}/index');\n";
1462
		}
1463
		$actions .= "\t\t\t} else {\n";
1464
		if (low($wannaUseSession) == 'y' || low($wannaUseSession) == 'yes') {
1465
		$actions .= "\t\t\t\t\$this->Session->setFlash('Prosím, opravte chyby.');\n";
1466
		}
1467

    
1468
		foreach($modelObj->hasAndBelongsToMany as $associationName => $relation) {
1469
			if(!empty($associationName)) {
1470
				$otherModelName = $this->__modelName($associationName);
1471
				$otherSingularName = $this->__singularName($associationName);
1472
				$otherPluralName = $this->__pluralName($associationName);
1473
				$selectedOtherPluralName = 'selected' . ucfirst($otherPluralName);
1474
				$actions .= "\t\t\t\t\$this->set('{$otherPluralName}', \$this->{$currentModelName}->{$otherModelName}->generateList());\n";
1475
				$actions .= "\t\t\t\tif(empty(\$this->data['{$associationName}']['{$associationName}'])) { \$this->data['{$associationName}']['{$associationName}'] = null; }\n";
1476
				$actions .= "\t\t\t\t\$this->set('{$selectedOtherPluralName}', \$this->data['{$associationName}']['{$associationName}']);\n";
1477
			}
1478
		}
1479
		foreach($modelObj->belongsTo as $associationName => $relation) {
1480
			if(!empty($associationName)) {
1481
				$otherModelName = $this->__modelName($associationName);
1482
				$otherSingularName = $this->__singularName($associationName);
1483
				$otherPluralName = $this->__pluralName($associationName);
1484
				$actions .= "\t\t\t\t\$this->set('{$otherPluralName}', \$this->{$currentModelName}->{$otherModelName}->generateList());\n";
1485
			}
1486
		}
1487
		$actions .= "\t\t\t}\n";
1488
		$actions .= "\t\t}\n";
1489
		$actions .= "\t}\n";
1490
		$actions .= "\n";
1491
		$actions .= "\tfunction {$admin}delete(\$id = null) {\n";
1492
		$actions .= "\t\tif(!\$id) {\n";
1493
		if (low($wannaUseSession) == 'y' || low($wannaUseSession) == 'yes') {
1494
		$actions .= "\t\t\t\$this->Session->setFlash('Neplatný identifikátor pro {$singularHumanName}');\n";
1495
		$actions .= "\t\t\t\$this->redirect('{$admin_url}/{$controllerPath}/index');\n";
1496
		} else {
1497
		$actions .= "\t\t\t\$this->flash('Neplatný identifikátor pro {$singularHumanName}', '{$admin_url}/{$controllerPath}/index');\n";
1498
		}
1499
		$actions .= "\t\t}\n";
1500
		$actions .= "\t\tif(\$this->{$currentModelName}->del(\$id)) {\n";
1501
		if (low($wannaUseSession) == 'y' || low($wannaUseSession) == 'yes') {
1502
			$actions .= "\t\t\t\$this->Session->setFlash(' ".$this->__singularHumanName($currentModelName)." smazan(a) ');\n";
1503
			$actions .= "\t\t\t\$this->redirect('{$admin_url}/{$controllerPath}/index');\n";
1504
		} else {
1505
			$actions .= "\t\t\t\$this->flash('{$currentModelName} smazán: id '.\$id.'.', '{$admin_url}/{$controllerPath}/index');\n";
1506
		}
1507
		$actions .= "\t\t}\n";
1508
		$actions .= "\t}\n";
1509
		$actions .= "\n";
1510
		return $actions;
1511
	}
1512
/**
1513
 * Action to create a Unit Test.
1514
 *
1515
 * @return Success
1516
 */
1517
	function doUnitTest() {
1518
		if (is_dir(VENDORS.'simpletest') || is_dir(ROOT.DS.APP_DIR.DS.'vendors'.DS.'simpletest')) {
1519
			return true;
1520
		}
1521
		$unitTest = $this->getInput('Cake test suite not installed.  Do you want to bake unit test files anyway?', array('y','n'), 'y');
1522
		$result = low($unitTest) == 'y' || low($unitTest) == 'yes';
1523

    
1524
		if ($result) {
1525
			$this->stdout("\nYou can download the Cake test suite from http://cakeforge.org/projects/testsuite/", true);
1526
		}
1527
		return $result;
1528
	}
1529
/**
1530
 * Creates a database configuration file for Bake.
1531
 *
1532
 * @param string $host
1533
 * @param string $login
1534
 * @param string $password
1535
 * @param string $database
1536
 */
1537
	function bakeDbConfig( $driver, $connect, $host, $login, $password, $database, $prefix) {
1538
		$out = "<?php\n";
1539
		$out .= "class DATABASE_CONFIG {\n\n";
1540
		$out .= "\tvar \$default = array(\n";
1541
		$out .= "\t\t'driver' => '{$driver}',\n";
1542
		$out .= "\t\t'connect' => '{$connect}',\n";
1543
		$out .= "\t\t'host' => '{$host}',\n";
1544
		$out .= "\t\t'login' => '{$login}',\n";
1545
		$out .= "\t\t'password' => '{$password}',\n";
1546
		$out .= "\t\t'database' => '{$database}', \n";
1547
		$out .= "\t\t'prefix' => '{$prefix}' \n";
1548
		$out .= "\t);\n";
1549
		$out .= "}\n";
1550
		$out .= "?>";
1551
		$filename = CONFIGS.'database.php';
1552
		$this->__createFile($filename, $out);
1553
	}
1554
/**
1555
 * Assembles and writes a Model file.
1556
 *
1557
 * @param string $name
1558
 * @param object $useDbConfig
1559
 * @param string $useTable
1560
 * @param string $primaryKey
1561
 * @param array $validate
1562
 * @param array $associations
1563
 */
1564
	function bakeModel($name, $useDbConfig = 'default', $useTable = null, $primaryKey = 'id', $validate=array(), $associations=array()) {
1565
		$out = "<?php\n";
1566
		$out .= "class {$name} extends AppModel {\n\n";
1567
		$out .= "\tvar \$name = '{$name}';\n";
1568

    
1569
		if ($useDbConfig != 'default') {
1570
			$out .= "\tvar \$useDbConfig = '$useDbConfig';\n";
1571
		}
1572

    
1573
		if ($useTable != null) {
1574
			$out .= "\tvar \$useTable = '$useTable';\n";
1575
		}
1576

    
1577
		if ($primaryKey != 'id') {
1578
			$out .= "\tvar \$primaryKey = '$primaryKey';\n";
1579
		}
1580

    
1581

    
1582
		if (count($validate)) {
1583
			$out .= "\tvar \$validate = array(\n";
1584
			$keys = array_keys($validate);
1585
			for($i = 0; $i < count($validate); $i++) {
1586
				$out .= "\t\t'" . $keys[$i] . "' => " . $validate[$keys[$i]] . ",\n";
1587
			}
1588
			$out .= "\t);\n";
1589
		}
1590
		$out .= "\n";
1591

    
1592
		if(!empty($associations)) {
1593
			$out.= "\t//The Associations below have been created with all possible keys, those that are not needed can be removed\n";
1594
			if(!empty($associations['belongsTo'])) {
1595
				$out .= "\tvar \$belongsTo = array(\n";
1596

    
1597
				for($i = 0; $i < count($associations['belongsTo']); $i++) {
1598
					$out .= "\t\t\t'{$associations['belongsTo'][$i]['alias']}' =>\n";
1599
					$out .= "\t\t\t\tarray('className' => '{$associations['belongsTo'][$i]['className']}',\n";
1600
					$out .= "\t\t\t\t\t\t'foreignKey' => '{$associations['belongsTo'][$i]['foreignKey']}',\n";
1601
					$out .= "\t\t\t\t\t\t'conditions' => '',\n";
1602
					$out .= "\t\t\t\t\t\t'fields' => '',\n";
1603
					$out .= "\t\t\t\t\t\t'order' => '',\n";
1604
					$out .= "\t\t\t\t\t\t'counterCache' => ''\n";
1605
					$out .= "\t\t\t\t),\n\n";
1606
				}
1607
				$out .= "\t);\n\n";
1608
			}
1609

    
1610
			if(!empty($associations['hasOne'])) {
1611
				$out .= "\tvar \$hasOne = array(\n";
1612

    
1613
				for($i = 0; $i < count($associations['hasOne']); $i++) {
1614
					$out .= "\t\t\t'{$associations['hasOne'][$i]['alias']}' =>\n";
1615
					$out .= "\t\t\t\tarray('className' => '{$associations['hasOne'][$i]['className']}',\n";
1616
					$out .= "\t\t\t\t\t\t'foreignKey' => '{$associations['hasOne'][$i]['foreignKey']}',\n";
1617
					$out .= "\t\t\t\t\t\t'conditions' => '',\n";
1618
					$out .= "\t\t\t\t\t\t'fields' => '',\n";
1619
					$out .= "\t\t\t\t\t\t'order' => '',\n";
1620
					$out .= "\t\t\t\t\t\t'dependent' => ''\n";
1621
					$out .= "\t\t\t\t),\n\n";
1622
				}
1623
				$out .= "\t);\n\n";
1624
			}
1625

    
1626
			if(!empty($associations['hasMany'])) {
1627
				$out .= "\tvar \$hasMany = array(\n";
1628

    
1629
				for($i = 0; $i < count($associations['hasMany']); $i++) {
1630
					$out .= "\t\t\t'{$associations['hasMany'][$i]['alias']}' =>\n";
1631
					$out .= "\t\t\t\tarray('className' => '{$associations['hasMany'][$i]['className']}',\n";
1632
					$out .= "\t\t\t\t\t\t'foreignKey' => '{$associations['hasMany'][$i]['foreignKey']}',\n";
1633
					$out .= "\t\t\t\t\t\t'conditions' => '',\n";
1634
					$out .= "\t\t\t\t\t\t'fields' => '',\n";
1635
					$out .= "\t\t\t\t\t\t'order' => '',\n";
1636
					$out .= "\t\t\t\t\t\t'limit' => '',\n";
1637
					$out .= "\t\t\t\t\t\t'offset' => '',\n";
1638
					$out .= "\t\t\t\t\t\t'dependent' => '',\n";
1639
					$out .= "\t\t\t\t\t\t'exclusive' => '',\n";
1640
					$out .= "\t\t\t\t\t\t'finderQuery' => '',\n";
1641
					$out .= "\t\t\t\t\t\t'counterQuery' => ''\n";
1642
					$out .= "\t\t\t\t),\n\n";
1643
				}
1644
				$out .= "\t);\n\n";
1645
			}
1646

    
1647
			if(!empty($associations['hasAndBelongsToMany'])) {
1648
				$out .= "\tvar \$hasAndBelongsToMany = array(\n";
1649

    
1650
				for($i = 0; $i < count($associations['hasAndBelongsToMany']); $i++) {
1651
					$out .= "\t\t\t'{$associations['hasAndBelongsToMany'][$i]['alias']}' =>\n";
1652
					$out .= "\t\t\t\tarray('className' => '{$associations['hasAndBelongsToMany'][$i]['className']}',\n";
1653
					$out .= "\t\t\t\t\t\t'joinTable' => '{$associations['hasAndBelongsToMany'][$i]['joinTable']}',\n";
1654
					$out .= "\t\t\t\t\t\t'foreignKey' => '{$associations['hasAndBelongsToMany'][$i]['foreignKey']}',\n";
1655
					$out .= "\t\t\t\t\t\t'associationForeignKey' => '{$associations['hasAndBelongsToMany'][$i]['associationForeignKey']}',\n";
1656
					$out .= "\t\t\t\t\t\t'conditions' => '',\n";
1657
					$out .= "\t\t\t\t\t\t'fields' => '',\n";
1658
					$out .= "\t\t\t\t\t\t'order' => '',\n";
1659
					$out .= "\t\t\t\t\t\t'limit' => '',\n";
1660
					$out .= "\t\t\t\t\t\t'offset' => '',\n";
1661
					$out .= "\t\t\t\t\t\t'unique' => '',\n";
1662
					$out .= "\t\t\t\t\t\t'finderQuery' => '',\n";
1663
					$out .= "\t\t\t\t\t\t'deleteQuery' => '',\n";
1664
					$out .= "\t\t\t\t\t\t'insertQuery' => ''\n";
1665
					$out .= "\t\t\t\t),\n\n";
1666
				}
1667
				$out .= "\t);\n\n";
1668
			}
1669
		}
1670
		$out .= "}\n";
1671
		$out .= "?>";
1672
		$filename = MODELS.Inflector::underscore($name) . '.php';
1673
		$this->__createFile($filename, $out);
1674
	}
1675
/**
1676
 * Assembles and writes a View file.
1677
 *
1678
 * @param string $controllerName
1679
 * @param string $actionName
1680
 * @param string $content
1681
 */
1682
	function bakeView($controllerName, $actionName, $content = '') {
1683
		$out = "<h2>{$actionName}</h2>\n";
1684
		$out .= $content;
1685
		if(!file_exists(VIEWS.$this->__controllerPath($controllerName))) {
1686
			mkdir(VIEWS.$this->__controllerPath($controllerName));
1687
		}
1688
		$filename = VIEWS . $this->__controllerPath($controllerName) . DS . Inflector::underscore($actionName) . '.thtml';
1689
		$this->__createFile($filename, $out);
1690
	}
1691
/**
1692
 * Assembles and writes a Controller file.
1693
 *
1694
 * @param string $controllerName
1695
 * @param array $uses
1696
 * @param array $helpers
1697
 * @param array $components
1698
 * @param string $actions
1699
 */
1700
	function bakeController($controllerName, $uses, $helpers, $components, $actions = '', $wannaUseScaffold = 'y') {
1701
		$out = "<?php\n";
1702
		$out .= "class $controllerName" . "Controller extends AppController {\n\n";
1703
		$out .= "\tvar \$name = '$controllerName';\n";
1704
		if(low($wannaUseScaffold) == 'y' || low($wannaUseScaffold) == 'yes') {
1705
		$out .= "\tvar \$scaffold;\n";
1706
		} else {
1707

    
1708
			if (count($uses)) {
1709
				$out .= "\tvar \$uses = array('" . $this->__modelName($controllerName) . "', ";
1710

    
1711
				foreach($uses as $use) {
1712
					if ($use != $uses[count($uses) - 1]) {
1713
						$out .= "'" . $this->__modelName($use) . "', ";
1714
					} else {
1715
						$out .= "'" . $this->__modelName($use) . "'";
1716
					}
1717
				}
1718
				$out .= ");\n";
1719
			}
1720

    
1721
				$out .= "\tvar \$helpers = array('Html', 'Form' ";
1722
				if (count($helpers)) {
1723
					foreach($helpers as $help) {
1724
						if ($help != $helpers[count($helpers) - 1]) {
1725
							$out .= ", '" . Inflector::camelize($help) . "'";
1726
						} else {
1727
							$out .= ", '" . Inflector::camelize($help) . "'";
1728
						}
1729
					}
1730
				}
1731
				$out .= ");\n";
1732

    
1733
			if (count($components)) {
1734
				$out .= "\tvar \$components = array(";
1735

    
1736
				foreach($components as $comp) {
1737
					if ($comp != $components[count($components) - 1]) {
1738
						$out .= "'" . Inflector::camelize($comp) . "', ";
1739
					} else {
1740
						$out .= "'" . Inflector::camelize($comp) . "'";
1741
					}
1742
				}
1743
				$out .= ");\n";
1744
			}
1745
		}
1746
		$out .= $actions;
1747
		$out .= "}\n";
1748
		$out .= "?>";
1749
		$filename = CONTROLLERS . $this->__controllerPath($controllerName) . '_controller.php';
1750
		$this->__createFile($filename, $out);
1751
	}
1752
/**
1753
 * Assembles and writes a unit test file.
1754
 *
1755
 * @param string $type One of "model", and "controller".
1756
 * @param string $className
1757
 */
1758
	function bakeUnitTest($type, $className) {
1759
		$out = '<?php '."\n\n";
1760
		$error = false;
1761
		switch ($type) {
1762
			case 'model':
1763
				$out .= "loadModel('$className');\n\n";
1764
				$out .= "class {$className}TestCase extends UnitTestCase {\n";
1765
				$out .= "\tvar \$object = null;\n\n";
1766
				$out .= "\tfunction setUp() {\n\t\t\$this->object = new {$className}();\n";
1767
				$out .= "\t}\n\n\tfunction tearDown() {\n\t\tunset(\$this->object);\n\t}\n";
1768
				$out .= "\n\t/*\n\tfunction testMe() {\n";
1769
				$out .= "\t\t\$result = \$this->object->doSomething();\n";
1770
				$out .= "\t\t\$expected = 1;\n";
1771
				$out .= "\t\t\$this->assertEqual(\$result, \$expected);\n\t}\n\t*/\n}";
1772
				$path = MODEL_TESTS;
1773
				$filename = $this->__singularName($className).'.test.php';
1774
			break;
1775
			case 'controller':
1776
				$out .= "loadController('$className');\n\n";
1777
				$out .= "class {$className}ControllerTestCase extends UnitTestCase {\n";
1778
				$out .= "\tvar \$object = null;\n\n";
1779
				$out .= "\tfunction setUp() {\n\t\t\$this->object = new {$className}Controller();\n";
1780
				$out .= "\t}\n\n\tfunction tearDown() {\n\t\tunset(\$this->object);\n\t}\n";
1781
				$out .= "\n\t/*\n\tfunction testMe() {\n";
1782
				$out .= "\t\t\$result = \$this->object->doSomething();\n";
1783
				$out .= "\t\t\$expected = 1;\n";
1784
				$out .= "\t\t\$this->assertEqual(\$result, \$expected);\n\t}\n\t*/\n}";
1785
				$path = CONTROLLER_TESTS;
1786
				$filename = $this->__pluralName($className).'_controller.test.php';
1787
			break;
1788
			default:
1789
				$error = true;
1790
			break;
1791
		}
1792
		$out .= "\n?>";
1793

    
1794
		if (!$error) {
1795
			$this->stdout("Baking unit test for $className...");
1796
			$path = explode(DS, $path);
1797
			foreach($path as $i => $val) {
1798
				if ($val == '' || $val == '../') {
1799
					unset($path[$i]);
1800
				}
1801
			}
1802
			$path = implode(DS, $path);
1803
			$unixPath = DS;
1804
			if (strpos(PHP_OS, 'WIN') === 0){
1805
				$unixPath = null;
1806
			}
1807
			if (!is_dir($unixPath.$path)) {
1808
				$create = $this->getInput("Unit test directory does not exist.  Create it?", array('y','n'), 'y');
1809
				if (low($create) == 'y' || low($create) == 'yes') {
1810
					$build = array();
1811

    
1812
					foreach(explode(DS, $path) as $i => $dir) {
1813
						$build[] = $dir;
1814
						if (!is_dir($unixPath.implode(DS, $build))) {
1815
							mkdir($unixPath.implode(DS, $build));
1816
						}
1817
					}
1818
				} else {
1819
					return false;
1820
				}
1821
			}
1822
			$this->__createFile($unixPath.$path.DS.$filename, $out);
1823
		}
1824
	}
1825
/**
1826
 * Prompts the user for input, and returns it.
1827
 *
1828
 * @param string $prompt Prompt text.
1829
 * @param mixed $options Array or string of options.
1830
 * @param string $default Default input value.
1831
 * @return Either the default value, or the user-provided input.
1832
 */
1833
	function getInput($prompt, $options = null, $default = null) {
1834
		if (!is_array($options)) {
1835
			$print_options = '';
1836
		} else {
1837
			$print_options = '(' . implode('/', $options) . ')';
1838
		}
1839

    
1840
		if($default == null) {
1841
			$this->stdout('');
1842
			$this->stdout($prompt . " $print_options \n" . '> ', false);
1843
		} else {
1844
			$this->stdout('');
1845
			$this->stdout($prompt . " $print_options \n" . "[$default] > ", false);
1846
		}
1847
		$result = trim(fgets($this->stdin));
1848

    
1849
		if($default != null && empty($result)) {
1850
			return $default;
1851
		} else {
1852
			return $result;
1853
		}
1854
	}
1855
/**
1856
 * Outputs to the stdout filehandle.
1857
 *
1858
 * @param string $string String to output.
1859
 * @param boolean $newline If true, the outputs gets an added newline.
1860
 */
1861
	function stdout($string, $newline = true) {
1862
		if ($newline) {
1863
			fwrite($this->stdout, $string . "\n");
1864
		} else {
1865
			fwrite($this->stdout, $string);
1866
		}
1867
	}
1868
/**
1869
 * Outputs to the stderr filehandle.
1870
 *
1871
 * @param string $string Error text to output.
1872
 */
1873
	function stderr($string) {
1874
		fwrite($this->stderr, $string, true);
1875
	}
1876
/**
1877
 * Outputs a series of minus characters to the standard output, acts as a visual separator.
1878
 *
1879
 */
1880
	function hr() {
1881
		$this->stdout('---------------------------------------------------------------');
1882
	}
1883
/**
1884
 * Creates a file at given path.
1885
 *
1886
 * @param string $path		Where to put the file.
1887
 * @param string $contents Content to put in the file.
1888
 * @return Success
1889
 */
1890
	function __createFile ($path, $contents) {
1891
		$path = str_replace('//', '/', $path);
1892
		echo "\nCreating file $path\n";
1893
		if (is_file($path) && $this->interactive === true) {
1894
			fwrite($this->stdout, __("File exists, overwrite?", true). " {$path} (y/n/q):");
1895
			$key = trim(fgets($this->stdin));
1896

    
1897
			if ($key=='q') {
1898
				fwrite($this->stdout, __("Quitting.", true) ."\n");
1899
				exit;
1900
			} elseif ($key == 'a') {
1901
				$this->dont_ask = true;
1902
			} elseif ($key == 'y') {
1903
			} else {
1904
				fwrite($this->stdout, __("Skip", true) ." {$path}\n");
1905
				return false;
1906
			}
1907
		}
1908

    
1909
		if ($f = fopen($path, 'w')) {
1910
			fwrite($f, $contents);
1911
			fclose($f);
1912
			fwrite($this->stdout, __("Wrote", true) ."{$path}\n");
1913
			return true;
1914
		} else {
1915
			fwrite($this->stderr, __("Error! Could not write to", true)." {$path}.\n");
1916
			return false;
1917
		}
1918
	}
1919
/**
1920
 * Takes an array of database fields, and generates an HTML form for a View.
1921
 * This is an extraction from the Scaffold functionality.
1922
 *
1923
 * @param array $fields
1924
 * @param boolean $readOnly
1925
 * @return Generated HTML and PHP.
1926
 */
1927
	function generateFields( $fields, $readOnly = false ) {
1928
		$strFormFields = '';
1929
		foreach( $fields as $field ) {
1930
			if(isset( $field['type'])) {
1931
				if(!isset($field['required'])) {
1932
					$field['required'] = false;
1933
				}
1934

    
1935
				if(!isset( $field['errorMsg'])) {
1936
					$field['errorMsg'] = null;
1937
				}
1938

    
1939
				if(!isset( $field['htmlOptions'])) {
1940
					$field['htmlOptions'] = array();
1941
				}
1942

    
1943
				if( $readOnly ) {
1944
					$field['htmlOptions']['READONLY'] = "readonly";
1945
				}
1946

    
1947
				switch( $field['type'] ) {
1948
					case "input" :
1949
						if(!isset( $field['size'])) {
1950
							$field['size'] = 60;
1951
						}
1952
						$strFormFields = $strFormFields.$this->generateInputDiv( $field['tagName'], $field['prompt'], $field['required'], $field['errorMsg'], $field['size'], $field['htmlOptions'] );
1953
					break;
1954
					case "checkbox" :
1955
						$strFormFields = $strFormFields.$this->generateCheckboxDiv( $field['tagName'], $field['prompt'], $field['required'], $field['errorMsg'], $field['htmlOptions'] );
1956
					break;
1957
					case "select";
1958
					case "selectMultiple";
1959
						if( "selectMultiple" == $field['type'] ) {
1960
							$field['selectAttr']['multiple'] = 'multiple';
1961
							$field['selectAttr']['class'] = 'selectMultiple';
1962
						}
1963
						if(!isset( $field['selected'])) {
1964
							$field['selected'] = null;
1965
						}
1966
						if(!isset( $field['selectAttr'])) {
1967
							$field['selectAttr'] = null;
1968
						}
1969
						if(!isset( $field['optionsAttr'])) {
1970
							$field['optionsAttr'] = null;
1971
						}
1972
						if($readOnly) {
1973
							$field['selectAttr']['DISABLED'] = true;
1974
						}
1975
						if(!isset( $field['options'])) {
1976
							$field['options'] = null;
1977
						}
1978
						$this->__modelAlias = null;
1979
						if(isset($field['foreignKey'])) {
1980
							$modelKey = Inflector::underscore($this->__modelClass);
1981
							$modelObj =& ClassRegistry::getObject($modelKey);
1982
							foreach($modelObj->belongsTo as $associationName => $value) {
1983
								if($field['model'] == $value['className']) {
1984
									$this->__modelAlias = $this->__modelName($associationName);
1985
									break;
1986
								}
1987
							}
1988
						}
1989
						$strFormFields = $strFormFields.$this->generateSelectDiv( $field['tagName'], $field['prompt'], $field['options'], $field['selected'], $field['selectAttr'], $field['optionsAttr'], $field['required'], $field['errorMsg'] );
1990
					break;
1991
					case "area";
1992
						if(!isset( $field['rows'])) {
1993
							$field['rows'] = 10;
1994
						}
1995
						if(!isset( $field['cols'])) {
1996
							$field['cols'] = 60;
1997
						}
1998
						$strFormFields = $strFormFields.$this->generateAreaDiv( $field['tagName'], $field['prompt'], $field['required'], $field['errorMsg'], $field['cols'], $field['rows'], $field['htmlOptions'] );
1999
					break;
2000
					case "fieldset";
2001
						$strFieldsetFields = $this->generateFields( $field['fields'] );
2002
						$strFieldSet = sprintf( '
2003
						<fieldset><legend>%s</legend><div class="notes"><h4>%s</h4><p class="last">%s</p></div>%s</fieldset>',
2004
						$field['legend'], $field['noteHeading'], $field['note'], $strFieldsetFields );
2005
						$strFormFields = $strFormFields.$strFieldSet;
2006
					break;
2007
					case "hidden";
2008
						//$strFormFields = $strFormFields . $this->Html->hiddenTag( $field['tagName']);
2009
					break;
2010
					case "date":
2011
						if (!isset($field['selected'])) {
2012
							$field['selected'] = null;
2013
						}
2014
						$strFormFields = $strFormFields . $this->generateDate($field['tagName'], $field['prompt'], $field['required'], $field['errorMsg'], null, $field['htmlOptions'], $field['selected']);
2015
					break;
2016
					case "datetime":
2017
						if (!isset($field['selected'])) {
2018
							$field['selected'] = null;
2019
						}
2020
						$strFormFields = $strFormFields . $this->generateDateTime($field['tagName'], $field['prompt'], $field['required'], $field['errorMsg'], null, $field['htmlOptions'], $field['selected']);
2021
					break;
2022
					case "time":
2023
						if (!isset($field['selected'])) {
2024
							$field['selected'] = null;
2025
						}
2026
						$strFormFields = $strFormFields . $this->generateTime($field['tagName'], $field['prompt'], $field['required'], $field['errorMsg'], null, $field['htmlOptions'], $field['selected']);
2027
					break;
2028
					default:
2029
					break;
2030
				}
2031
			}
2032
		}
2033
		return $strFormFields;
2034
	}
2035
/**
2036
 * Generates PHP code for a View file that makes a textarea.
2037
 *
2038
 * @param string $tagName
2039
 * @param string $prompt
2040
 * @param boolean $required
2041
 * @param string $errorMsg
2042
 * @param integer $cols
2043
 * @param integer $rows
2044
 * @param array $htmlOptions
2045
 * @return Generated HTML and PHP.
2046
 */
2047
	function generateAreaDiv($tagName, $prompt, $required=false, $errorMsg=null, $cols=60, $rows=10,  $htmlOptions=null ) {
2048
		$htmlAttributes = $htmlOptions;
2049
		$htmlAttributes['cols'] = $cols;
2050
		$htmlAttributes['rows'] = $rows;
2051
		$str = "\t<?php echo \$html->textarea('{$tagName}', " . $this->__attributesToArray($htmlAttributes) . ");?>\n";
2052
		$str .= "\t<?php echo \$error->showMessage('{$tagName}');?>\n";
2053
		$strLabel = "\n\t<?php echo \$form->labelTag( '{$tagName}', '{$prompt}' );?>\n";
2054
		$divClass = "optional";
2055

    
2056
		if( $required ) {
2057
			$divClass = "required";
2058
		}
2059
		$strError = "";// initialize the error to empty.
2060
		$divTagInside = sprintf( "%s %s %s", $strError, $strLabel, $str );
2061
		return $this->divTag( $divClass, $divTagInside );
2062
	}
2063
/**
2064
 * Generates PHP code for a View file that makes a checkbox, wrapped in a DIV.
2065
 *
2066
 * @param string $tagName
2067
 * @param string $prompt
2068
 * @param boolean $required
2069
 * @param string $errorMsg
2070
 * @param array $htmlOptions
2071
 * @return Generated HTML and PHP.
2072
 */
2073
	function generateCheckboxDiv($tagName, $prompt, $required=false, $errorMsg=null, $htmlOptions=null ) {
2074
		$htmlAttributes = $htmlOptions;
2075
		$strLabel = "\n\t<?php echo \$html->checkbox('{$tagName}', null, " . $this->__attributesToArray($htmlAttributes) . ");?>\n";
2076
		$strLabel .= "\t<?php echo \$form->labelTag('{$tagName}', '{$prompt}');?>\n";
2077
		$str = "\t<?php echo \$error->showMessage('{$tagName}');?>\n";
2078
		$divClass = "optional";
2079

    
2080
		if($required) {
2081
			$divClass = "required";
2082
		}
2083
		$strError = "";// initialize the error to empty.
2084
		$divTagInside = sprintf( "%s %s %s", $strError, $strLabel, $str);
2085
		return $this->divTag( $divClass, $divTagInside );
2086
	}
2087
/**
2088
 * Generates PHP code for a View file that makes a date-picker, wrapped in a DIV.
2089
 *
2090
 * @param string $tagName
2091
 * @param string $prompt
2092
 * @param boolean $required
2093
 * @param string $errorMsg
2094
 * @param integer $size
2095
 * @param array $htmlOptions
2096
 * @param string $selected
2097
 * @return Generated HTML and PHP.
2098
 */
2099
	function generateDate($tagName, $prompt, $required=false, $errorMsg=null, $size=20, $htmlOptions=null, $selected=null ) {
2100
		$str = "\t<?php echo \$html->dateTimeOptionTag('{$tagName}', 'MDY' , 'NONE', \$html->tagValue('{$tagName}'), " . $this->__attributesToArray($htmlOptions) . ");?>\n";
2101
		$str .= "\t<?php echo \$error->showMessage('{$tagName}');?>\n";
2102
		$strLabel = "\n\t<?php echo \$form->labelTag('{$tagName}', '{$prompt}');?>\n";
2103
		$divClass = "optional";
2104

    
2105
		if($required) {
2106
			$divClass = "required";
2107
		}
2108
		$strError = "";// initialize the error to empty.
2109
		$divTagInside = sprintf( "%s %s %s", $strError, $strLabel, $str );
2110
		return $this->divTag( $divClass, $divTagInside );
2111
	}
2112
/**
2113
 * Generates PHP code for a View file that makes a time-picker, wrapped in a DIV.
2114
 *
2115
 * @param string $tagName
2116
 * @param string $prompt
2117
 * @param boolean $required
2118
 * @param string $errorMsg
2119
 * @param integer $size
2120
 * @param array $htmlOptions
2121
 * @param string $selected
2122
 * @return Generated HTML and PHP.
2123
 */
2124
	function generateTime($tagName, $prompt, $required = false, $errorMsg = null, $size = 20, $htmlOptions = null, $selected = null) {
2125
		$str = "\n\t\<?php echo \$html->dateTimeOptionTag('{$tagName}', 'NONE', '24', \$html->tagValue('{$tagName}'), " . $this->__attributesToArray($htmlOptions) . ");?>\n";
2126
		$strLabel = "\n\t<?php echo \$form->labelTag('{$tagName}', '{$prompt}');?>\n";
2127
		$divClass = "optional";
2128
		if ($required) {
2129
			$divClass = "required";
2130
		}
2131
		$strError = "";
2132
		$divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str);
2133
		return $this->divTag($divClass, $divTagInside);
2134
	}
2135
/**
2136
 * EGenerates PHP code for a View file that makes a datetime-picker, wrapped in a DIV.
2137
 *
2138
 * @param string $tagName
2139
 * @param string $prompt
2140
 * @param boolean $required
2141
 * @param string $errorMsg
2142
 * @param integer $size
2143
 * @param array $htmlOptions
2144
 * @param string $selected
2145
 * @return Generated HTML and PHP.
2146
 */
2147
	function generateDateTime($tagName, $prompt, $required=false, $errorMsg=null, $size=20, $htmlOptions=null, $selected = null ) {
2148
		$str = "\t<?php echo \$html->dateTimeOptionTag('{$tagName}', 'MDY' , '12', \$html->tagValue('{$tagName}'), " . $this->__attributesToArray($htmlOptions) . ");?>\n";
2149
		$str .= "\t<?php echo \$error->showMessage('{$tagName}');?>\n";
2150
		$strLabel = "\n\t<?php echo \$form->labelTag('{$tagName}', '{$prompt}');?>\n";
2151
		$divClass = "optional";
2152

    
2153
		if($required) {
2154
			$divClass = "required";
2155
		}
2156
		$strError = "";// initialize the error to empty.
2157
		$divTagInside = sprintf( "%s %s %s", $strError, $strLabel, $str );
2158
		return $this->divTag( $divClass, $divTagInside );
2159
	}
2160
/**
2161
 * Generates PHP code for a View file that makes an INPUT field, wrapped in a DIV.
2162
 *
2163
 * @param string $tagName
2164
 * @param string $prompt
2165
 * @param boolean $required
2166
 * @param string $errorMsg
2167
 * @param integer $size
2168
 * @param array $htmlOptions
2169
 * @return Generated HTML and PHP.
2170
 */
2171
	function generateInputDiv($tagName, $prompt, $required=false, $errorMsg=null, $size=20, $htmlOptions=null ) {
2172
		$htmlAttributes = $htmlOptions;
2173
		$htmlAttributes['size'] = $size;
2174
		$str = "\t<?php echo \$html->input('{$tagName}', " . $this->__attributesToArray($htmlAttributes) . ");?>\n";
2175
		$str .= "\t<?php echo \$error->showMessage('{$tagName}');?>\n";
2176
		 $strLabel = "\n\t<?php echo \$form->labelTag('{$tagName}', '{$prompt}');?>\n";
2177
		$divClass = "optional";
2178

    
2179
		if($required) {
2180
			$divClass = "required";
2181
		}
2182
		$strError = "";// initialize the error to empty.
2183
		$divTagInside = sprintf( "%s %s %s", $strError, $strLabel, $str );
2184
		return $this->divTag( $divClass, $divTagInside );
2185
	}
2186

    
2187
/**
2188
 * Generates PHP code for a View file that makes a SELECT box, wrapped in a DIV.
2189
 *
2190
 * @param string $tagName
2191
 * @param string $prompt
2192
 * @param array $options
2193
 * @param string $selected
2194
 * @param array $selectAttr
2195
 * @param array $optionAttr
2196
 * @param boolean $required
2197
 * @param string $errorMsg
2198
 * @return Generated HTML and PHP.
2199
 */
2200
	function generateSelectDiv($tagName, $prompt, $options, $selected=null, $selectAttr=null, $optionAttr=null, $required=false,  $errorMsg=null) {
2201

    
2202
		if($this->__modelAlias) {
2203
			$pluralName = $this->__pluralName($this->__modelAlias);
2204
		} else {
2205
			$tagArray = explode('/', $tagName);
2206
			$pluralName = $this->__pluralName($this->__modelNameFromKey($tagArray[1]));
2207
		}
2208
		$showEmpty = 'true';
2209
		if($required) {
2210
			$showEmpty = 'false';
2211
		}
2212
		if($selectAttr['multiple'] != 'multiple') {
2213
			$str = "\t<?php echo \$html->selectTag('{$tagName}', " . "\${$pluralName}, \$html->tagValue('{$tagName}'), " . $this->__attributesToArray($selectAttr) . ", " . $this->__attributesToArray($optionAttr) . ", " . $showEmpty . ");?>\n";
2214
			$str .= "\t<?php echo \$error->showMessage('{$tagName}') ?>\n";
2215
		} else {
2216
			$selectedPluralName = 'selected' . ucfirst($pluralName);
2217
			$selectAttr = am(array('multiple' => 'multiple', 'class' => 'selectMultiple'), $selectAttr);
2218
			$str = "\t<?php echo \$html->selectTag('{$tagName}', \${$pluralName}, \${$selectedPluralName}, " . $this->__attributesToArray($selectAttr) . ", " . $this->__attributesToArray($optionAttr) . ", " . $showEmpty . ");?>\n";
2219
			$str .= "\t<?php echo \$error->showMessage('{$tagName}');?>\n";
2220
		}
2221
		$strLabel = "\n\t<?php echo \$form->labelTag('{$tagName}', '{$prompt}');?>\n";
2222
		$divClass = "optional";
2223

    
2224
		if($required) {
2225
			$divClass = "required";
2226
		}
2227
		$strError = "";// initialize the error to empty.
2228
		$divTagInside = sprintf( "%s %s %s", $strError, $strLabel, $str );
2229
		return $this->divTag( $divClass, $divTagInside );
2230
	}
2231
/**
2232
 * Generates PHP code for a View file that makes a submit button, wrapped in a DIV.
2233
 *
2234
 * @param string $displayText
2235
 * @param array $htmlOptions
2236
 * @return Generated HTML.
2237
 */
2238
	function generateSubmitDiv($displayText, $htmlOptions = null) {
2239
		$str = "\n\t<?php echo \$html->submit('{$displayText}');?>\n";
2240
		$divTagInside = sprintf( "%s", $str );
2241
		return $this->divTag( 'submit', $divTagInside);
2242
	}
2243
/**
2244
 * Returns the text wrapped in an HTML DIV, followed by a newline.
2245
 *
2246
 * @param string $class
2247
 * @param string $text
2248
 * @return Generated HTML.
2249
 */
2250
	function divTag($class, $text) {
2251
		return sprintf('<div class="%s">%s</div>', $class, $text ) . "\n";
2252
	}
2253
/**
2254
 * Parses the HTML attributes array, which is a common data structure in View files.
2255
 * Returns PHP code for initializing this array in a View file.
2256
 *
2257
 * @param array $htmlAttributes
2258
 * @return Generated PHP code.
2259
 */
2260
	function __attributesToArray($htmlAttributes) {
2261
		if (is_array($htmlAttributes)) {
2262
			$keys = array_keys($htmlAttributes);
2263
			$vals = array_values($htmlAttributes);
2264
			$out = "array(";
2265

    
2266
			for($i = 0; $i < count($htmlAttributes); $i++) {
2267
				//don't put vars in quotes
2268
				if(substr($vals[$i], 0, 1) != '$') {
2269
					$out .= "'{$keys[$i]}' => '{$vals[$i]}', ";
2270
				} else {
2271
					$out .= "'{$keys[$i]}' => {$vals[$i]}, ";
2272
				}
2273
			}
2274
			//Chop off last comma
2275
			if(substr($out, -2, 1) == ',') {
2276
				$out = substr($out, 0, strlen($out) - 2);
2277
			}
2278
			$out .= ")";
2279
			return $out;
2280
		} else {
2281
			return 'array()';
2282
		}
2283
	}
2284
/**
2285
 * Outputs usage text on the standard output.
2286
 *
2287
 */
2288
	function help() {
2289
		$this->stdout('CakePHP Bake:');
2290
		$this->hr();
2291
		$this->stdout('The Bake script generates controllers, views and models for your application.');
2292
		$this->stdout('If run with no command line arguments, Bake guides the user through the class');
2293
		$this->stdout('creation process. You can customize the generation process by telling Bake');
2294
		$this->stdout('where different parts of your application are using command line arguments.');
2295
		$this->stdout('');
2296
		$this->hr('');
2297
		$this->stdout('usage: php bake.php [command] [path...]');
2298
		$this->stdout('');
2299
		$this->stdout('commands:');
2300
		$this->stdout('   -app [path...] Absolute path to Cake\'s app Folder.');
2301
		$this->stdout('   -core [path...] Absolute path to Cake\'s cake Folder.');
2302
		$this->stdout('   -help Shows this help message.');
2303
		$this->stdout('   -project [path...]  Generates a new app folder in the path supplied.');
2304
		$this->stdout('   -root [path...] Absolute path to Cake\'s \app\webroot Folder.');
2305
		$this->stdout('');
2306
	}
2307
/**
2308
 * Checks that given project path does not already exist, and
2309
 * finds the app directory in it. Then it calls __buildDirLayout() with that information.
2310
 *
2311
 * @param string $projectPath
2312
 */
2313
	function project($projectPath = null) {
2314
		if($projectPath != '') {
2315
			while ($this->__checkPath($projectPath) === true && $this->__checkPath(CONFIGS) === true) {
2316
				$response = $this->getInput('Bake -app in '.$projectPath, array('y','n'), 'y');
2317
				if(low($response) == 'y') {
2318
					$this->main();
2319
					exit();
2320
				} else {
2321
					$projectPath = $this->getInput("What is the full path for this app including the app directory name?\nExample: ".ROOT.DS."myapp", null, ROOT.DS.'myapp');
2322
				}
2323
			}
2324
		} else {
2325
			while ($projectPath == '') {
2326
				$projectPath = $this->getInput("What is the full path for this app including the app directory name?\nExample: ".ROOT.DS."myapp", null, ROOT.DS.'myapp');
2327

    
2328
				if ($projectPath == '') {
2329
					$this->stdout('The directory path you supplied was empty. Please try again.');
2330
				}
2331
			}
2332
		}
2333
		while ($newPath != 'y' && ($this->__checkPath($projectPath) === true || $projectPath == '')) {
2334
				$newPath = $this->getInput('Directory '.$projectPath.'  exists. Overwrite (y) or insert a new path', null, 'y');
2335
				if($newPath != 'y') {
2336
					$projectPath = $newPath;
2337
				}
2338
			while ($projectPath == '') {
2339
				$projectPath = $this->getInput('The directory path you supplied was empty. Please try again.');
2340
			}
2341
		}
2342
		$parentPath = explode(DS, $projectPath);
2343
		$count = count($parentPath);
2344
		$appName = $parentPath[$count - 1];
2345
		if($appName == '') {
2346
			$appName = $parentPath[$count - 2];
2347
		}
2348
		$this->__buildDirLayout($projectPath, $appName);
2349
		exit();
2350
	}
2351
/**
2352
 * Returns true if given path is a directory.
2353
 *
2354
 * @param string $projectPath
2355
 * @return True if given path is a directory.
2356
 */
2357
	function __checkPath($projectPath) {
2358
		if(is_dir($projectPath)) {
2359
			return true;
2360
		} else {
2361
			return false;
2362
		}
2363
	}
2364
/**
2365
 * Looks for a skeleton template of a Cake application,
2366
 * and if not found asks the user for a path. When there is a path
2367
 * this method will make a deep copy of the skeleton to the project directory.
2368
 * A default home page will be added, and the tmp file storage will be chmod'ed to 0777.
2369
 *
2370
 * @param string $projectPath
2371
 * @param string $appName
2372
 */
2373
	function __buildDirLayout($projectPath, $appName) {
2374
		$skel = '';
2375
		if($this->__checkPath(CAKE_CORE_INCLUDE_PATH.DS.'cake'.DS.'scripts'.DS.'templates'.DS.'skel') === true) {
2376
			$skel = CAKE_CORE_INCLUDE_PATH.DS.'cake'.DS.'scripts'.DS.'templates'.DS.'skel';
2377
		} else {
2378

    
2379
			while ($skel == '') {
2380
				$skel = $this->getInput("What is the full path for the cake install app directory?\nExample: ", null, ROOT.'myapp'.DS);
2381

    
2382
				if ($skel == '') {
2383
					$this->stdout('The directory path you supplied was empty. Please try again.');
2384
				} else {
2385
					while ($this->__checkPath($skel) === false) {
2386
						$skel = $this->getInput('Directory path does not exist please choose another:');
2387
					}
2388
				}
2389
			}
2390
		}
2391
		$this->stdout('');
2392
		$this->hr();
2393
		$this->stdout("Skel Directory: $skel");
2394
		$this->stdout("Will be copied to:");
2395
		$this->stdout("New App Directory: $projectPath");
2396
		$this->hr();
2397
		$looksGood = $this->getInput('Look okay?', array('y', 'n', 'q'), 'y');
2398

    
2399
		if (low($looksGood) == 'y' || low($looksGood) == 'yes') {
2400
			$verboseOuptut = $this->getInput('Do you want verbose output?', array('y', 'n'), 'n');
2401
			$verbose = false;
2402

    
2403
			if (low($verboseOuptut) == 'y' || low($verboseOuptut) == 'yes') {
2404
				$verbose = true;
2405
			}
2406
			$this->__copydirr($skel, $projectPath, 0755, $verbose);
2407
			$this->hr();
2408
			$this->stdout('Created: '.$projectPath);
2409
			$this->hr();
2410
			$this->stdout('Creating welcome page');
2411
			$this->hr();
2412
			$this->__defaultHome($projectPath, $appName);
2413
			$this->stdout('Welcome page created');
2414
			if(chmodr($projectPath.DS.'tmp', 0777) === false) {
2415
				$this->stdout('Could not set permissions on '. $projectPath.DS.'tmp'.DS.'*');
2416
				$this->stdout('You must manually check that these directories can be wrote to by the server');
2417
			}
2418
			return;
2419
		} elseif (low($looksGood) == 'q' || low($looksGood) == 'quit') {
2420
			$this->stdout('Bake Aborted.');
2421
		} else {
2422
			$this->project();
2423
		}
2424
	}
2425
/**
2426
 * Recursive directory copy.
2427
 *
2428
 * @param string $fromDir
2429
 * @param string $toDir
2430
 * @param octal $chmod
2431
 * @param boolean	 $verbose
2432
 * @return Success.
2433
 */
2434
	function __copydirr($fromDir, $toDir, $chmod = 0755, $verbose = false) {
2435
		$errors=array();
2436
		$messages=array();
2437

    
2438
		uses('folder');
2439
		$folder = new Folder($toDir, true, 0755);
2440

    
2441
		if (!is_writable($toDir)) {
2442
			$errors[]='target '.$toDir.' is not writable';
2443
		}
2444

    
2445
		if (!is_dir($fromDir)) {
2446
			$errors[]='source '.$fromDir.' is not a directory';
2447
		}
2448

    
2449
		if (!empty($errors)) {
2450
			if ($verbose) {
2451
				foreach($errors as $err) {
2452
					$this->stdout('Error: '.$err);
2453
				}
2454
			}
2455
			return false;
2456
		}
2457
		$exceptions=array('.','..','.svn');
2458
		$handle = opendir($fromDir);
2459

    
2460
		while (false!==($item = readdir($handle))) {
2461
			if (!in_array($item,$exceptions)) {
2462
				$from = $folder->addPathElement($fromDir, $item);
2463
				$to = $folder->addPathElement($toDir, $item);
2464
				if (is_file($from)) {
2465
					if (@copy($from, $to)) {
2466
						chmod($to, $chmod);
2467
						touch($to, filemtime($from));
2468
						$messages[]='File copied from '.$from.' to '.$to;
2469
					} else {
2470
						$errors[]='cannot copy file from '.$from.' to '.$to;
2471
					}
2472
				}
2473

    
2474
				if (is_dir($from)) {
2475
					if (@mkdir($to)) {
2476
						chmod($to,$chmod);
2477
						$messages[]='Directory created: '.$to;
2478
					} else {
2479
						$errors[]='cannot create directory '.$to;
2480
					}
2481
					$this->__copydirr($from,$to,$chmod,$verbose);
2482
				}
2483
			}
2484
		}
2485
		closedir($handle);
2486

    
2487
		if ($verbose) {
2488
			foreach($errors as $err) {
2489
				$this->stdout('Error: '.$err);
2490
			}
2491
			foreach($messages as $msg) {
2492
				$this->stdout($msg);
2493
			}
2494
		}
2495
		return true;
2496
	}
2497

    
2498
	function __addAdminRoute($name){
2499
		$file = file_get_contents(CONFIGS.'core.php');
2500
		if (preg_match('%([/\\t\\x20]*define\\(\'CAKE_ADMIN\',[\\t\\x20\'a-z]*\\);)%', $file, $match)) {
2501
			$result = str_replace($match[0], 'define(\'CAKE_ADMIN\', \''.$name.'\');', $file);
2502

    
2503
			if(file_put_contents(CONFIGS.'core.php', $result)){
2504
				return true;
2505
			} else {
2506
				return false;
2507
			}
2508
		} else {
2509
			return false;
2510
		}
2511
	}
2512
/**
2513
 * Outputs an ASCII art banner to standard output.
2514
 *
2515
 */
2516
	function welcome()
2517
	{
2518
		$this->stdout('');
2519
		$this->stdout(' ___  __  _  _  ___  __  _  _  __      __   __  _  _  ___ ');
2520
		$this->stdout('|    |__| |_/  |__  |__] |__| |__]    |__] |__| |_/  |__ ');
2521
		$this->stdout('|___ |  | | \_ |___ |    |  | |       |__] |  | | \_ |___ ');
2522
		$this->hr();
2523
		$this->stdout('');
2524
	}
2525
/**
2526
 * Writes a file with a default home page to the project.
2527
 *
2528
 * @param string $dir
2529
 * @param string $app
2530
 */
2531
	function __defaultHome($dir, $app) {
2532
		$path = $dir.DS.'views'.DS.'pages'.DS;
2533
		include(CAKE_CORE_INCLUDE_PATH.DS.'cake'.DS.'scripts'.DS.'templates'.DS.'views'.DS.'home.thtml');
2534
		$this->__createFile($path.'home.thtml', $output);
2535
	}
2536
/**
2537
 * creates the proper pluralize controller for the url
2538
 *
2539
 * @param string $name must be a controller name in pluralized form
2540
 * @return string $name
2541
 */
2542
	function __controllerPath($name) {
2543
		return low(Inflector::underscore($name));
2544
	}
2545
/**
2546
 * creates the proper pluralize controller class name.
2547
 *
2548
 * @param string $name
2549
 * @return string $name
2550
 */
2551
	function __controllerName($name) {
2552
		return Inflector::pluralize(Inflector::camelize($name));
2553
	}
2554
/**
2555
 * creates the proper singular model name.
2556
 *
2557
 * @param string $name
2558
 * @return string $name
2559
 */
2560
	function __modelName($name) {
2561
		return Inflector::camelize(Inflector::singularize($name));
2562
	}
2563
/**
2564
 * creates the proper singular model key for associations.
2565
 *
2566
 * @param string $name
2567
 * @return string $name
2568
 */
2569
	function __modelKey($name) {
2570
		return Inflector::underscore(Inflector::singularize($name)).'_id';
2571
	}
2572
/**
2573
 * creates the proper model name from a foreign key.
2574
 *
2575
 * @param string $key
2576
 * @return string $name
2577
 */
2578
	function __modelNameFromKey($key) {
2579
		$name = str_replace('_id', '',$key);
2580
		return $this->__modelName($name);
2581
	}
2582
/**
2583
 * creates the singular name for use in views.
2584
 *
2585
 * @param string $name
2586
 * @return string $name
2587
 */
2588
	function __singularName($name) {
2589
		return Inflector::variable(Inflector::singularize($name));
2590
	}
2591
/**
2592
 * creates the plural name for views.
2593
 *
2594
 * @param string $name
2595
 * @return string $name
2596
 */
2597
	function __pluralName($name) {
2598
		return Inflector::variable(Inflector::pluralize($name));
2599
	}
2600
/**
2601
 * creates the singular human name used in views
2602
 *
2603
 * @param string $name
2604
 * @return string $name
2605
 */
2606
	function __singularHumanName($name) {
2607
		return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
2608
	}
2609
/**
2610
 * creates the plural humna name used in views
2611
 *
2612
 * @param string $name
2613
 * @return string $name
2614
 */
2615
	function __pluralHumanName($name) {
2616
		return Inflector::humanize(Inflector::underscore(Inflector::pluralize($name)));
2617
	}
2618
/**
2619
 * outputs the a list of possible models or controllers from database
2620
 *
2621
 * @param string $useDbConfig
2622
 * @param string $type = Models or Controllers
2623
 * @return output
2624
 */
2625
	function __doList($useDbConfig = 'default', $type = 'Models') {
2626
		$db =& ConnectionManager::getDataSource($useDbConfig);
2627
		$usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
2628
		if ($usePrefix) {
2629
			$tables = array();
2630
			foreach ($db->listSources() as $table) {
2631
				if (!strncmp($table, $usePrefix, strlen($usePrefix))) {
2632
					$tables[] = substr($table, strlen($usePrefix));
2633
				}
2634
			}
2635
		} else {
2636
			$tables = $db->listSources();
2637
		}
2638
		$this->__tables = $tables;
2639
		$this->stdout('Possible '.$type.' based on your current database:');
2640
		$this->__controllerNames = array();
2641
		$this->__modelNames = array();
2642
		$count = count($tables);
2643
		for ($i = 0; $i < $count; $i++) {
2644
			if(low($type) == 'controllers') {
2645
				$this->__controllerNames[] = $this->__controllerName($this->__modelName($tables[$i]));
2646
				$this->stdout($i + 1 . ". " . $this->__controllerNames[$i]);
2647
			} else {
2648
				$this->__modelNames[] = $this->__modelName($tables[$i]);
2649
				$this->stdout($i + 1 . ". " . $this->__modelNames[$i]);
2650
			}
2651
		}
2652
	}
2653

    
2654
}
2655
?>
(2-2/2)