File: model.php

package info (click to toggle)
cakephp 1.2.0.7296-rc2-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 6,032 kB
  • ctags: 23,481
  • sloc: php: 77,476; sql: 92; makefile: 34; sh: 5
file content (2666 lines) | stat: -rw-r--r-- 79,487 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
<?php
/* SVN FILE: $Id: model.php 7296 2008-06-27 09:09:03Z gwoo $ */
/**
 * Object-relational mapper.
 *
 * DBO-backed object data model, for mapping database tables to Cake objects.
 *
 * PHP versions 5
 *
 * CakePHP(tm) :  Rapid Development Framework <http://www.cakephp.org/>
 * Copyright 2005-2008, Cake Software Foundation, Inc.
 *								1785 E. Sahara Avenue, Suite 490-204
 *								Las Vegas, Nevada 89104
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright		Copyright 2005-2008, Cake Software Foundation, Inc.
 * @link				http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
 * @package			cake
 * @subpackage		cake.cake.libs.model
 * @since			CakePHP(tm) v 0.10.0.0
 * @version			$Revision: 7296 $
 * @modifiedby		$LastChangedBy: gwoo $
 * @lastmodified	$Date: 2008-06-27 02:09:03 -0700 (Fri, 27 Jun 2008) $
 * @license			http://www.opensource.org/licenses/mit-license.php The MIT License
 */
/**
 * Included libs
 */
App::import('Core', array('ClassRegistry', 'Overloadable', 'Validation', 'Behavior', 'ConnectionManager', 'Set'));
/**
 * Object-relational mapper.
 *
 * DBO-backed object data model.
 * Automatically selects a database table name based on a pluralized lowercase object class name
 * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
 * The table is required to have at least 'id auto_increment', 'created datetime',
 * and 'modified datetime' fields.
 *
 * @package		cake
 * @subpackage	cake.cake.libs.model
 */
class Model extends Overloadable {
/**
 * The name of the DataSource connection that this Model uses
 *
 * @var string
 * @access public
 */
	var $useDbConfig = 'default';
/**
 * Custom database table name.
 *
 * @var string
 * @access public
 */
	var $useTable = null;
/**
 * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
 *
 * @var string
 * @access public
 */
	var $displayField = null;
/**
 * Value of the primary key ID of the record that this model is currently pointing to
 *
 * @var mixed
 * @access public
 */
	var $id = false;
/**
 * Container for the data that this model gets from persistent storage (the database).
 *
 * @var array
 * @access public
 */
	var $data = array();
/**
 * Table name for this Model.
 *
 * @var string
 * @access public
 */
	var $table = false;
/**
 * The name of the ID field for this Model.
 *
 * @var string
 * @access public
 */
	var $primaryKey = null;
/**
 * Table metadata
 *
 * @var array
 * @access protected
 */
	var $_schema = null;
/**
 * List of validation rules. Append entries for validation as ('field_name' => '/^perl_compat_regexp$/')
 * that have to match with preg_match(). Use these rules with Model::validate()
 *
 * @var array
 * @access public
 */
	var $validate = array();
/**
 * Errors in validation
 *
 * @var array
 * @access public
 */
	var $validationErrors = array();
/**
 * Database table prefix for tables in model.
 *
 * @var string
 * @access public
 */
	var $tablePrefix = null;
/**
 * Name of the model.
 *
 * @var string
 * @access public
 */
	var $name = null;
/**
 * Alias name for model.
 *
 * @var string
 * @access public
 */
	var $alias = null;
/**
 * List of table names included in the Model description. Used for associations.
 *
 * @var array
 * @access public
 */
	var $tableToModel = array();
/**
 * Whether or not transactions for this model should be logged
 *
 * @var boolean
 * @access public
 */
	var $logTransactions = false;
/**
 * Whether or not to enable transactions for this model (i.e. BEGIN/COMMIT/ROLLBACK)
 *
 * @var boolean
 * @access public
 */
	var $transactional = false;
/**
 * Whether or not to cache queries for this model.  This enables in-memory
 * caching only, the results are not stored beyond this execution.
 *
 * @var boolean
 * @access public
 */
	var $cacheQueries = false;
/**
 * belongsTo association
 *
 * @var array
 * @access public
 */
	var $belongsTo = array();
/**
 * hasOne association
 *
 * @var array
 * @access public
 */
	var $hasOne = array();
/**
 * hasMany association
 *
 * @var array
 * @access public
 */
	var $hasMany = array();
/**
 * hasAndBelongsToMany association
 *
 * @var array
 * @access public
 */
	var $hasAndBelongsToMany = array();
/**
 * List of behaviors to load when the model object is initialized. Settings can be
 * passed to behaviors by using the behavior name as index. Eg:
 *
 * array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
 *
 * @var array
 * @access public
 */
	var $actsAs = null;
/**
 * Holds the Behavior objects currently bound to this model
 *
 * @var object
 * @access public
 */
	var $Behaviors = null;
/**
 * Whitelist of fields allowed to be saved
 *
 * @var array
 * @access public
 */
	var $whitelist = array();
/**
 * Should sources for this model be cached.
 *
 * @var boolean
 * @access public
 */
	var $cacheSources = true;
/**
 * Type of find query currently executing
 *
 * @var string
 * @access public
 */
	var $findQueryType = null;
/**
 * Depth of recursive association
 *
 * @var integer
 * @access public
 */
	var $recursive = 1;
/**
 * Default ordering of model records
 *
 * @var string
 * @access public
 */
	var $order = null;
/**
 * Whether or not the model record exists, set by Model::exists()
 *
 * @var bool
 * @access private
 */
	var $__exists = null;
/**
 * Default association keys
 *
 * @var array
 * @access private
 */
	var $__associationKeys = array(
			'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
			'hasOne' => array('className', 'foreignKey','conditions', 'fields','order', 'dependent'),
			'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
			'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery'));
/**
 * Holds provided/generated association key names and other data for all associations
 *
 * @var array
 * @access private
 */
	var $__associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
/**
 * Holds model associations temporarily to allow for dynamic (un)binding
 *
 * @var array
 * @access private
 */
	var $__backAssociation = array();
/**
 * The last inserted ID of the data that this model created
 *
 * @var integer
 * @access private
 */
	var $__insertID = null;
/**
 * The number of records returned by the last query
 *
 * @var integer
 * @access private
 */
	var $__numRows = null;
/**
 * The number of records affected by the last query
 *
 * @var integer
 * @access private
 */
	var $__affectedRows = null;
/**
 * List of valid finder method options
 *
 * @var array
 * @access private
 */
	var $__findMethods = array('all' => true, 'first' => true, 'count' => true, 'neighbors' => true, 'list' => true, 'threaded' => true);
/**
 * Constructor. Binds the Model's database table to the object.
 *
 * @param integer $id Set this ID for this model on startup
 * @param string $table Name of database table to use.
 * @param object $ds DataSource connection object.
 */
	function __construct($id = false, $table = null, $ds = null) {
		parent::__construct();

		if (is_array($id)) {
			extract(array_merge(array('id' => false, 'table' => null, 'ds' => null, 'name' => null, 'alias' => null), $id));
			$this->name = $name;
			$this->alias = $alias;
		}

		if ($this->name === null) {
			$this->name = get_class($this);
		}

		if ($this->alias === null) {
			$this->alias = $this->name;
		}

		if ($this->primaryKey === null) {
			$this->primaryKey = 'id';
		}
		ClassRegistry::addObject($this->alias, $this);

		$this->id = $id;
		unset($id);

		if ($table === false) {
			$this->useTable = false;
		} elseif ($table) {
			$this->useTable = $table;
		}

		if ($this->useTable !== false) {
			$this->setDataSource($ds);

			if ($this->useTable === null) {
				$this->useTable = Inflector::tableize($this->name);
			}

			if (in_array('settableprefix', get_class_methods($this))) {
				$this->setTablePrefix();
			}

			$this->setSource($this->useTable);
			$this->__createLinks();

			if ($this->displayField == null) {
				$this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
			}
		}

		if (is_subclass_of($this, 'AppModel')) {
			$appVars = get_class_vars('AppModel');
			$merge = array();

			if ($this->actsAs !== null || $this->actsAs !== false) {
				$merge[] = 'actsAs';
			}

			foreach ($merge as $var) {
				if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
					$this->{$var} = Set::merge($appVars[$var], $this->{$var});
				}
			}
		}
		$this->Behaviors = new BehaviorCollection();
		$this->Behaviors->init($this->alias, $this->actsAs);
	}
/**
 * Handles custom method calls, like findBy<field> for DB models,
 * and custom RPC calls for remote data sources.
 *
 * @param string $method Name of method to call.
 * @param array $params Parameters for the method.
 * @return mixed Whatever is returned by called method
 * @access protected
 */
	function call__($method, $params) {
		$result = $this->Behaviors->dispatchMethod($this, $method, $params);

		if ($result !== array('unhandled')) {
			return $result;
		}
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		$return = $db->query($method, $params, $this);

		if (!PHP5) {
			$this->resetAssociations();
		}
		return $return;
	}
/**
 * Bind model associations on the fly.
 *
 * If $permanent is true, association will not be reset
 * to the originals defined in the model.
 *
 * @param mixed $model A model or association name (string) or set of binding options (indexed by model name type)
 * @param array $options If $model is a string, this is the list of association properties with which $model will
 * 						 be bound
 * @param boolean $permanent Set to true to make the binding permanent
 * @access public
 * @todo
 */
	function bind($model, $options = array(), $permanent = true) {
		if (!is_array($model)) {
			$model = array($model => $options);
		}

		foreach ($model as $name => $options) {
			if (isset($options['type'])) {
				$assoc = $options['type'];
			} elseif (isset($options[0])) {
				$assoc = $options[0];
			} else {
				$assoc = 'belongsTo';
			}

			if (!$permanent) {
				$this->__backAssociation[$assoc] = $this->{$assoc};
			}
			foreach ($model as $key => $value) {
				$assocName = $modelName = $key;

				if (isset($this->{$assoc}[$assocName])) {
					$this->{$assoc}[$assocName] = array_merge($this->{$assoc}[$assocName], $options);
				} else {
					if (isset($value['className'])) {
						$modelName = $value['className'];
					}

					$this->__constructLinkedModel($assocName, $modelName);
					$this->{$assoc}[$assocName] = $model[$assocName];
					$this->__generateAssociation($assoc);
				}
				unset($this->{$assoc}[$assocName]['type'], $this->{$assoc}[$assocName][0]);
			}
		}
	}
/**
 * Bind model associations on the fly.
 *
 * If $reset is false, association will not be reset
 * to the originals defined in the model
 *
 * Example: Add a new hasOne binding to the Profile model not
 * defined in the model source code:
 * <code>
 * $this->User->bindModel( array('hasOne' => array('Profile')) );
 * </code>
 *
 * @param array $params Set of bindings (indexed by binding type)
 * @param boolean $reset Set to false to make the binding permanent
 * @return boolean Success
 * @access public
 */
	function bindModel($params, $reset = true) {
		foreach ($params as $assoc => $model) {
			if ($reset === true) {
				$this->__backAssociation[$assoc] = $this->{$assoc};
			}

			foreach ($model as $key => $value) {
				$assocName = $key;

				if (is_numeric($key)) {
					$assocName = $value;
					$value = array();
				}
				$modelName = $assocName;
				$this->{$assoc}[$assocName] = $value;
			}
		}
		$this->__createLinks();
		return true;
	}
/**
 * Turn off associations on the fly.
 *
 * If $reset is false, association will not be reset
 * to the originals defined in the model
 *
 * Example: Turn off the associated Model Support request,
 * to temporarily lighten the User model:
 * <code>
 * $this->User->unbindModel( array('hasMany' => array('Supportrequest')) );
 * </code>
 *
 * @param array $params Set of bindings to unbind (indexed by binding type)
 * @param boolean $reset  Set to false to make the unbinding permanent
 * @return boolean Success
 * @access public
 */
	function unbindModel($params, $reset = true) {
		foreach ($params as $assoc => $models) {
			if ($reset === true) {
				$this->__backAssociation[$assoc] = $this->{$assoc};
			}

			foreach ($models as $model) {
				$this->__backAssociation = array_merge($this->__backAssociation, $this->{$assoc});
				unset ($this->__backAssociation[$model]);
				unset ($this->{$assoc}[$model]);
			}
		}
		return true;
	}
/**
 * Create a set of associations
 *
 * @access private
 */
	function __createLinks() {
		foreach ($this->__associations as $type) {
			if (!is_array($this->{$type})) {
				$this->{$type} = explode(',', $this->{$type});

				foreach ($this->{$type} as $i => $className) {
					$className = trim($className);
					unset ($this->{$type}[$i]);
					$this->{$type}[$className] = array();
				}
			}

			if (!empty($this->{$type})) {
				foreach ($this->{$type} as $assoc => $value) {
					$plugin = null;

					if (is_numeric($assoc)) {
						unset ($this->{$type}[$assoc]);
						$assoc = $value;
						$value = array();
						$this->{$type}[$assoc] = $value;

						if (strpos($assoc, '.') !== false) {
							$value = $this->{$type}[$assoc];
							unset($this->{$type}[$assoc]);
							list($plugin, $assoc) = explode('.', $assoc);
							$this->{$type}[$assoc] = $value;
							$plugin = $plugin . '.';
						}
					}
					$className =  $assoc;

					if (isset($value['className']) && !empty($value['className'])) {
						$className = $value['className'];
						if (strpos($className, '.') !== false) {
							list($plugin, $className) = explode('.', $className);
							$plugin = $plugin . '.';
							$this->{$type}[$assoc]['className'] = $className;
						}
					}
					$this->__constructLinkedModel($assoc, $plugin . $className);
				}
				$this->__generateAssociation($type);
			}
		}
	}
/**
 * Private helper method to create associated models of given class.
 *
 * @param string $assoc Association name
 * @param string $className Class name
 * @deprecated $this->$className use $this->$assoc instead. $assoc is the 'key' in the associations array;
 * 	examples: var $hasMany = array('Assoc' => array('className' => 'ModelName'));
 * 					usage: $this->Assoc->modelMethods();
 *
 * 				var $hasMany = array('ModelName');
 * 					usage: $this->ModelName->modelMethods();
 * @access private
 */
	function __constructLinkedModel($assoc, $className = null) {
		if(empty($className)) {
			$className = $assoc;
		}

		if (!isset($this->{$assoc})) {
			$model = array('class' => $className, 'alias' => $assoc);
			if (PHP5) {
				$this->{$assoc} = ClassRegistry::init($model);
			} else {
				$this->{$assoc} =& ClassRegistry::init($model);
			}
			if ($assoc) {
				$this->tableToModel[$this->{$assoc}->table] = $assoc;
			}
		}
	}
/**
 * Build array-based association from string.
 *
 * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
 * @access private
 */
	function __generateAssociation($type) {
		foreach ($this->{$type} as $assocKey => $assocData) {
			$class = $assocKey;

			foreach ($this->__associationKeys[$type] as $key) {
				if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
					$data = '';

					switch($key) {
						case 'fields':
							$data = '';
						break;

						case 'foreignKey':
							$data = ife($type == 'belongsTo', Inflector::underscore($assocKey) . '_id', Inflector::singularize($this->table) . '_id');
						break;

						case 'associationForeignKey':
							$data = Inflector::singularize($this->{$class}->table) . '_id';
						break;

						case 'with':
							$data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
						break;

						case 'joinTable':
							$tables = array($this->table, $this->{$class}->table);
							sort ($tables);
							$data = $tables[0] . '_' . $tables[1];
						break;

						case 'className':
							$data = $class;
						break;

						case 'unique':
							$data = true;
						break;
					}
					$this->{$type}[$assocKey][$key] = $data;
				}
			}

			if (isset($this->{$type}[$assocKey]['with']) && !empty($this->{$type}[$assocKey]['with'])) {
				$joinClass = $this->{$type}[$assocKey]['with'];
				if (is_array($joinClass)) {
					$joinClass = key($joinClass);
				}
				$plugin = null;

				if (strpos($joinClass, '.') !== false) {
					list($plugin, $joinClass) = explode('.', $joinClass);
					$plugin = $plugin . '.';
					$this->{$type}[$assocKey]['with'] = $joinClass;
				}

				if (!App::import('Model', $plugin . $joinClass)) {
					$this->{$joinClass} = new AppModel(array(
						'name' => $joinClass,
						'table' => $this->{$type}[$assocKey]['joinTable'],
						'ds' => $this->useDbConfig
					));
					$this->{$joinClass}->primaryKey = $this->{$type}[$assocKey]['foreignKey'];

				} else {
					$this->__constructLinkedModel($joinClass, $plugin . $joinClass);
					$this->{$joinClass}->primaryKey = $this->{$type}[$assocKey]['foreignKey'];
					$this->{$type}[$assocKey]['joinTable'] = $this->{$joinClass}->table;
				}

				if (count($this->{$joinClass}->_schema) > 2) {
					if (isset($this->{$joinClass}->_schema['id'])) {
						$this->{$joinClass}->primaryKey = 'id';
					}
				}
			}
		}
	}
/**
 * Sets a custom table for your controller class. Used by your controller to select a database table.
 *
 * @param string $tableName Name of the custom table
 * @access public
 */
	function setSource($tableName) {
		$this->setDataSource($this->useDbConfig);
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		$db->cacheSources = $this->cacheSources;

		if ($db->isInterfaceSupported('listSources')) {
			$sources = $db->listSources();
			if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
				return $this->cakeError('missingTable', array(array(
					'className' => $this->alias,
					'table' => $this->tablePrefix . $tableName
				)));
			}
			$this->_schema = null;
		}
		$this->table = $this->useTable = $tableName;
		$this->tableToModel[$this->table] = $this->alias;
		$this->schema();
	}
/**
 * This function does two things: 1) it scans the array $one for the primary key,
 * and if that's found, it sets the current id to the value of $one[id].
 * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
 * 2) Returns an array with all of $one's keys and values.
 * (Alternative indata: two strings, which are mangled to
 * a one-item, two-dimensional array using $one for a key and $two as its value.)
 *
 * @param mixed $one Array or string of data
 * @param string $two Value string for the alternative indata method
 * @return array Data with all of $one's keys and values
 * @access public
 */
	function set($one, $two = null) {
		if (!$one) {
			return;
		}
		if (is_object($one)) {
			$one = Set::reverse($one);
		}

		if (is_array($one)) {
			$data = $one;
			if (empty($one[$this->alias])) {
				$keys = array_keys($one);
				if (in_array($keys[0], array_keys($this->_schema))) {
					$data = array($this->alias => $one);
				}
			}
		} else {
			$data = array($this->alias => array($one => $two));
		}

		foreach ($data as $n => $v) {
			if (is_array($v)) {

				foreach ($v as $x => $y) {
					if (isset($this->validationErrors[$x])) {
						unset ($this->validationErrors[$x]);
					}

					if ($n === $this->alias) {
						if ($x === $this->primaryKey) {
							$this->id = $y;
						}
					}
					if (is_array($y) || is_object($y)) {
						$y = $this->deconstruct($x, $y);
					}
					$this->data[$n][$x] = $y;
				}
			}
		}
		return $data;
	}
/**
 * Deconstructs a complex data type (array or object) into a single field value
 *
 * @param string $field The name of the field to be deconstructed
 * @param mixed $data An array or object to be deconstructed into a field
 * @return mixed The resulting data that should be assigned to a field
 * @access public
 */
	function deconstruct($field, $data) {
		$copy = $data;
		$type = $this->getColumnType($field);
		$db =& ConnectionManager::getDataSource($this->useDbConfig);

		if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
			$useNewDate = (isset($data['year']) || isset($data['month']) || isset($data['day']) || isset($data['hour']) || isset($data['minute']));
			$dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
			$format = $db->columns[$type]['format'];
			$date = array();

			if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) {
				$data['hour'] = $data['hour'] + 12;
			}
			if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
				$data['hour'] = '00';
			}

			foreach ($dateFields as $key => $val) {
				if (in_array($val, array('hour', 'min', 'sec'))) {
					if (!isset($data[$val]) || $data[$val] === '0' || empty($data[$val])) {
						$data[$val] = '00';
					} else {
						$data[$val] = sprintf('%02d', $data[$val]);
					}
				}
				if (in_array($type, array('datetime', 'timestamp', 'date')) && !isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
					return null;
				} elseif (isset($data[$val]) && !empty($data[$val])) {
					$date[$key] = $data[$val];
				}
			}
			$date = str_replace(array_keys($date), array_values($date), $format);

			if ($useNewDate && (!empty($date))) {
				return $date;
			}
		}
		return $data;
	}
/**
 * Returns an array of table metadata (column names and types) from the database.
 * $field => keys(type, null, default, key, length, extra)
 *
 * @param mixed $field Set to true to reload schema, or a string to return a specific field
 * @return array Array of table metadata
 * @access public
 */
	function schema($field = false) {
		if (!is_array($this->_schema) || $field === true) {
			$db =& ConnectionManager::getDataSource($this->useDbConfig);
			$db->cacheSources = $this->cacheSources;
			if ($db->isInterfaceSupported('describe') && $this->useTable !== false) {
				$this->_schema = $db->describe($this, $field);
			} elseif ($this->useTable === false) {
				$this->_schema = array();
			}
		}
		if (is_string($field)) {
			if (isset($this->_schema[$field])) {
				return $this->_schema[$field];
			} else {
				return null;
			}
		}
		return $this->_schema;
	}
/**
 * Returns an associative array of field names and column types.
 *
 * @return array Field types indexed by field name
 * @access public
 */
	function getColumnTypes() {
		$columns = $this->schema();
		if (empty($columns)) {
			trigger_error(__('(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()', true), E_USER_WARNING);
		}
		$cols = array();
		foreach ($columns as $field => $values) {
			$cols[$field] = $values['type'];
		}
		return $cols;
	}
/**
 * Returns the column type of a column in the model
 *
 * @param string $column The name of the model column
 * @return string Column type
 * @access public
 */
	function getColumnType($column) {
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		$cols = $this->schema();
		$model = null;

		$column = str_replace(array($db->startQuote, $db->endQuote), '', $column);

		if (strpos($column, '.')) {
			list($model, $column) = explode('.', $column);
		}
		if ($model != $this->alias && isset($this->{$model})) {
			return $this->{$model}->getColumnType($column);
		}
		if (isset($cols[$column]) && isset($cols[$column]['type'])) {
			return $cols[$column]['type'];
		}
		return null;
	}
/**
 * Returns true if this Model has given field in its database table.
 *
 * @param mixed $name Name of field to look for, or an array of names
 * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
 *               If $name is an array of field names, returns the first field that exists,
 *               or false if none exist.
 * @access public
 */
	function hasField($name) {
		if (is_array($name)) {
			foreach ($name as $n) {
				if ($this->hasField($n)) {
					return $n;
				}
			}
			return false;
		}

		if (empty($this->_schema)) {
			$this->schema();
		}

		if ($this->_schema != null) {
			return isset($this->_schema[$name]);
		}
		return false;
	}
/**
 * Initializes the model for writing a new record, loading the default values
 * for those fields that are not defined in $data.
 *
 * @param mixed $data Optional data array to assign to the model after it is created.  If null or false,
 *                    schema data defaults are not merged.
 * @param boolean $filterKey If true, overwrites any primary key input with an empty value
 * @return array The current Model::data; after merging $data and/or defaults from database
 * @access public
 */
	function create($data = array(), $filterKey = false) {
		$defaults = array();
		$this->id = false;
		$this->data = array();
		$this->validationErrors = array();

		if ($data !== null && $data !== false) {
			foreach ($this->schema() as $field => $properties) {
				if ($this->primaryKey !== $field && isset($properties['default'])) {
					$defaults[$field] = $properties['default'];
				}
			}
			$this->set(Set::filter($defaults));
			$this->set($data);
		}
		if ($filterKey) {
			$this->set($this->primaryKey, false);
		}
		return $this->data;
	}
/**
 * Returns a list of fields from the database, and sets the current model
 * data (Model::$data) with the record found.
 *
 * @param mixed $fields String of single fieldname, or an array of fieldnames.
 * @param mixed $id The ID of the record to read
 * @return array Array of database fields, or false if not found
 * @access public
 */
	function read($fields = null, $id = null) {
		$this->validationErrors = array();

		if ($id != null) {
			$this->id = $id;
		}

		$id = $this->id;

		if (is_array($this->id)) {
			$id = $this->id[0];
		}

		if ($id !== null && $id !== false) {
			$this->data = $this->find(array($this->alias . '.' . $this->primaryKey => $id), $fields);
			return $this->data;
		} else {
			return false;
		}
	}
/**
 * Returns contents of a field in a query matching given conditions.
 *
 * @param string $name Name of field to get
 * @param array $conditions SQL conditions (defaults to NULL)
 * @param string $order SQL ORDER BY fragment
 * @return string field contents, or false if not found
 * @access public
 */
	function field($name, $conditions = null, $order = null) {
		if ($conditions === null && $this->id !== false) {
			$conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
		}
		if ($this->recursive >= 1) {
			$recursive = -1;
		} else {
			$recursive = $this->recursive;
		}
		if ($data = $this->find($conditions, $name, $order, $recursive)) {
			if (strpos($name, '.') === false) {
				if (isset($data[$this->alias][$name])) {
					return $data[$this->alias][$name];
				}
			} else {
				$name = explode('.', $name);
				if (isset($data[$name[0]][$name[1]])) {
					return $data[$name[0]][$name[1]];
				}
			}
			if (isset($data[0]) && count($data[0]) > 0) {
				$name = key($data[0]);
				return $data[0][$name];
			}
		} else {
			return false;
		}
	}
/**
 * Saves a single field to the database.
 *
 * @param string $name Name of the table field
 * @param mixed $value Value of the field
 * @param array $options See $options param in Model::save(). Does not respect 'fieldList' key if passed
 * @return boolean See Model::save()
 * @access public
 * @see Model::save()
 */
	function saveField($name, $value, $validate = false) {
		$id = $this->id;
		$this->create(false);

		if (is_array($validate)) {
			$options = array_merge(array('validate' => false, 'fieldList' => array($name)), $options);
		} else {
			$options = array('validate' => $validate, 'fieldList' => array($name));
		}

		return $this->save(
			array($this->alias => array($this->primaryKey => $id, $name => $value)), $options
		);
	}
/**
 * Saves model data to the database. By default, validation occurs before save.
 *
 * @param array $data Data to save.
 * @param boolean $validate If set, validation will be done before the save
 * @param array $fieldList List of fields to allow to be written
 * @return mixed On success Model::$data if its not empty or true, false on failure
 * @access public
 */
	function save($data = null, $validate = true, $fieldList = array()) {
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		$_whitelist = $this->whitelist;
		$defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
		$fields = array();

		if (!is_array($validate)) {
			$options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
		} else {
			$options = array_merge($defaults, $validate);
		}

		if (!empty($options['fieldList'])) {
			$this->whitelist = $options['fieldList'];
		} elseif ($options['fieldList'] === null) {
			$this->whitelist = array();
		}
		$this->set($data);

		if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
			return false;
		}

		foreach (array('created', 'updated', 'modified') as $field) {
			if (isset($this->data[$this->alias]) && array_key_exists($field, $this->data[$this->alias]) && $this->data[$this->alias][$field] === null) {
				unset($this->data[$this->alias][$field]);
			}
		}

		$this->exists();
		$dateFields = array('modified', 'updated');

		if (!$this->__exists) {
			$dateFields[] = 'created';
		}
		if (isset($this->data[$this->alias])) {
			$fields = array_keys($this->data[$this->alias]);
		}
		if ($options['validate'] && !$this->validates($options)) {
			$this->whitelist = $_whitelist;
			return false;
		}

		foreach ($dateFields as $updateCol) {
			if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
				$colType = array_merge(array('formatter' => 'date'), $db->columns[$this->getColumnType($updateCol)]);
				if (!array_key_exists('formatter', $colType) || !array_key_exists('format', $colType)) {
					$time = strtotime('now');
				} else {
					$time = $colType['formatter']($colType['format']);
				}
				if (!empty($this->whitelist)) {
					$this->whitelist[] = $updateCol;
				}
				$this->set($updateCol, $time);
			}
		}

		if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
			if (!$this->Behaviors->trigger($this, 'beforeSave', array($options), array('break' => true, 'breakOn' => false)) || !$this->beforeSave($options)) {
				$this->whitelist = $_whitelist;
				return false;
			}
		}
		$fields = $values = array();

		if (isset($this->data[$this->alias][$this->primaryKey]) && empty($this->data[$this->alias][$this->primaryKey])) {
			unset($this->data[$this->alias][$this->primaryKey]);
		}

		foreach ($this->data as $n => $v) {
			if (isset($this->hasAndBelongsToMany[$n])) {
				if (isset($v[$n])) {
					$v = $v[$n];
				}
				$joined[$n] = $v;
			} else {
				if ($n === $this->alias) {
					foreach (array('created', 'updated', 'modified') as $field) {
						if (array_key_exists($field, $v) && empty($v[$field])) {
							unset($v[$field]);
						}
					}

					foreach ($v as $x => $y) {
						if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
							list($fields[], $values[]) = array($x, $y);
						}
					}
				}
			}
		}
		$count = count($fields);

		if (!$this->__exists && $count > 0) {
			$this->id = false;
		}
		$success = true;
		$created = false;

		if ($count > 0) {
			if (!empty($this->id)) {
				if (!$db->update($this, $fields, $values)) {
					$success = false;
				}
			} else {
				foreach ($this->_schema as $field => $properties) {
					if ($this->primaryKey === $field) {
						$isUUID = ($this->_schema[$field]['type'] === 'string' && $this->_schema[$field]['length'] === 36)
								|| ($this->_schema[$field]['type'] === 'binary' && $this->_schema[$field]['length'] === 16);
						if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
							list($fields[], $values[]) = array($this->primaryKey, String::uuid());
						}
						break;
					}
				}

				if (!$db->create($this, $fields, $values)) {
					$success = $created = false;
				} else {
					$created = true;
				}
			}
		}

		if (!empty($this->belongsTo)) {
			$this->updateCounterCache(array(), $created);
		}

		if (!empty($joined) && $success === true) {
			$this->__saveMulti($joined, $this->id);
		}

		if ($success && $count > 0) {
			if (!empty($this->data)) {
				$success = $this->data;
			}
			if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
				$this->Behaviors->trigger($this, 'afterSave', array($created, $options));
				$this->afterSave($created);
			}
			if (!empty($this->data)) {
				$success = Set::merge($success, $this->data);
			}
			$this->data = false;
			$this->__exists = null;
			$this->_clearCache();
			$this->validationErrors = array();
		}
		$this->whitelist = $_whitelist;
		return $success;
	}
/**
 * Saves model hasAndBelongsToMany data to the database.
 *
 * @param array $joined Data to save
 * @param mixed $id ID of record in this model
 * @access private
 */
	function __saveMulti($joined, $id) {
		$db =& ConnectionManager::getDataSource($this->useDbConfig);

		foreach ($joined as $assoc => $value) {
			$newValues = array();
			if (empty($value)) {
				$value = array();
			}
			if (isset($this->hasAndBelongsToMany[$assoc])) {
				list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
				$conditions = array($join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id);
				$links = array();

				if ($this->hasAndBelongsToMany[$assoc]['unique']) {
					$this->{$join}->deleteAll($conditions);
				} else {
					list($recursive, $fields) = array(-1, $this->hasAndBelongsToMany[$assoc]['associationForeignKey']);
					$links = Set::extract(
						$this->{$join}->find('all', compact('conditions', 'recursive', 'fields')),
						"{n}.{$join}." . $this->hasAndBelongsToMany[$assoc]['associationForeignKey']
					);
				}

				foreach ($value as $update) {
					if (!empty($update)) {
						if (is_array($update)) {
							$update[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
							$this->{$join}->create($update);
							$this->{$join}->save();
						} elseif (!in_array($update, $links)) {
							$values  = join(',', array(
								$db->value($id, $this->getColumnType($this->primaryKey)),
								$db->value($update)
							));
							$newValues[] = "({$values})";
							unset($values);
						}
					}
				}

				if (!empty($newValues)) {
					$fields = join(',', array(
						$db->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
						$db->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
					));
					$db->insertMulti($this->{$join}, $fields, $newValues);
				}
			}
		}
	}
/**
 * Updates the counter cache of belongsTo associations after a save or delete operation
 *
 * @param array $keys Optional foreign key data, defaults to the information $this->data
 * @param boolean $created True if a new record was created, otherwise only associations with
 *				  'counterScope' defined get updated
 * @return void
 * @access public
 */
	function updateCounterCache($keys = array(), $created = false) {
		if (empty($keys)) {
			$keys = $this->data[$this->alias];
		}
		foreach ($this->belongsTo as $parent => $assoc) {
			if (!empty($assoc['counterCache'])) {
				if ($assoc['counterCache'] === true) {
					$assoc['counterCache'] = Inflector::underscore($this->alias) . '_count';
				}
				if (!isset($keys[$assoc['foreignKey']]) || empty($keys[$assoc['foreignKey']])) {
					$keys[$assoc['foreignKey']] = $this->field($assoc['foreignKey']);
				}
				if ($this->{$parent}->hasField($assoc['counterCache'])) {
					$conditions = array($this->escapeField($assoc['foreignKey']) => $keys[$assoc['foreignKey']]);
					if (isset($assoc['counterScope'])) {
						$conditions = array_merge($conditions, (array)$assoc['counterScope']);
					}
					$this->{$parent}->updateAll(
						array($assoc['counterCache'] => intval($this->find('count', compact('conditions')))),
						array($this->{$parent}->escapeField() => $keys[$assoc['foreignKey']])
					);
				}
			}
		}
	}
/**
 * Saves (a) multiple individual records for a single model or (b) this record, as well as
 * all associated records
 *
 * @param array $data Record data to save.  This can be either a numerically-indexed array (for saving multiple
 * 						records of the same type), or an array indexed by association name.
 * @param array $options Options to use when saving record data, which are as follows:
 * 							- validate: Set to false to disable validation, true to validate each record before
 * 							  saving, 'first' to validate *all* records before any are saved, or 'only' to only
 * 							  validate the records, but not save them.
 * 							- atomic: If true (default), will attempt to save all records in a single transaction.
 *							  Should be set to false if database/table does not support transactions.
 *								If false, we return an array similar to the $data array passed, but values are set to true/false
 *								depending on whether each record saved successfully.
 *							- fieldList: Equivalent to the $fieldList parameter in Model::save()
 * @return mixed True on success, or false on failure
 * @access public
 */
	function saveAll($data = null, $options = array()) {
		if (empty($data)) {
			$data = $this->data;
		}
		$db =& ConnectionManager::getDataSource($this->useDbConfig);

		$options = array_merge(array('validate' => true, 'atomic' => true), $options);
		$this->validationErrors = $validationErrors = array();
		$validates = true;
		$return = array();

		if ($options['atomic'] && $options['validate'] !== 'only') {
			$db->begin($this);
		}

		if (Set::numeric(array_keys($data))) {
			while ($validates) {
				foreach ($data as $key => $record) {
					if (!$validates = $this->__save($this, $record, $options)) {
						if (empty($this->id)) {
							$validationErrors[$key] = $this->validationErrors;
						} else {
							$validationErrors[$this->id] = $this->validationErrors;
						}
					}
					$validating = ($options['validate'] === 'only' || $options['validate'] === 'first');

					if (!$options['atomic']) {
						$return[] = $validates;
					} elseif (!$validates && !$validating) {
						break;
					}
				}
				$this->validationErrors = $validationErrors;

				switch (true) {
					case ($options['validate'] === 'only'):
						return ($options['atomic'] ? $validates : $return);
					break;
					case ($options['validate'] === 'first'):
						$options['validate'] = true;
						continue;
					break;
					default:
						if ($options['atomic']) {
							if ($validates && ($db->commit($this) !== false)) {
								return true;
							}
							$db->rollback($this);
							return false;
						}
						return $return;
					break;
				}
			}
			return $return;
		}
		$associations = $this->getAssociated();

		while ($validates) {
			foreach ($data as $association => $values) {
				if (isset($associations[$association])) {
					switch ($associations[$association]) {
						case 'belongsTo':
							if ($this->__save($this->{$association}, $values, $options)) {
								$data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
							} else {
								$validationErrors[$association] = $this->{$association}->validationErrors;
								$validates = false;
							}
							if (!$options['atomic']) {
								$return[$association][] = $validates;
							}
						break;
					}
				}
			}
			if (!$this->__save($this, $data[$this->alias], $options)) {
				$validationErrors[$this->alias] = $this->validationErrors;
				$validates = false;
			}
			if (!$options['atomic']) {
				$return[$this->alias] = $validates;
			}
			$validating = ($options['validate'] === 'only' || $options['validate'] === 'first');

			foreach ($data as $association => $values) {
				if (!$validates && !$validating) {
					break;
				}
				if (isset($associations[$association])) {
					$type = $associations[$association];
					switch ($type) {
						case 'hasOne':
							$values[$this->{$type}[$association]['foreignKey']] = $this->id;
							if (!$this->__save($this->{$association}, $values, $options)) {
								$validationErrors[$association] = $this->{$association}->validationErrors;
								$validates = false;
							}
							if (!$options['atomic']) {
								$return[$association][] = $validates;
							}
						break;
						case 'hasMany':
							foreach ($values as $i => $value) {
								$values[$i][$this->{$type}[$association]['foreignKey']] =  $this->id;
							}
							$_options = array_merge($options, array('atomic' => false));

							if ($_options['validate'] === 'first') {
								$_options['validate'] = 'only';
							}
							$_return = $this->{$association}->saveAll($values, $_options);

							if ($_return === false || (is_array($_return) && in_array(false, $_return, true))) {
								$validationErrors[$association] = $this->{$association}->validationErrors;
								$validates = false;
							}
							if (is_array($_return)) {
								foreach ($_return as $val) {
									if (!isset($return[$association])) {
										$return[$association] = array();
									} elseif (!is_array($return[$association])) {
										$return[$association] = array($return[$association]);
									}
									$return[$association][] = $val;
								}
							} else {
								$return[$association] = $_return;
							}
						break;
					}
				}
			}
			$this->validationErrors = $validationErrors;

			if (isset($validationErrors[$this->alias])) {
				$this->validationErrors = $validationErrors[$this->alias];
			}

			switch (true) {
				case ($options['validate'] === 'only'):
					return ($options['atomic'] ? $validates : $return);
				break;
				case ($options['validate'] === 'first'):
					$options['validate'] = true;
					continue;
				break;
				default:
					if ($options['atomic']) {
						if ($validates) {
							return ($db->commit($this) !== false);
						} else {
							$db->rollback($this);
						}
					}
					return $return;
				break;
			}
		}
	}
/**
 * Private helper method used by saveAll
 *
 * @access private
 * @see Model::saveAll()
 */
	function __save(&$model, $data, $options) {
		if ($options['validate'] === 'first' || $options['validate'] === 'only') {
			if (!($model->create($data) && $model->validates($options))) {
				return false;
			}
		} elseif (!($model->create(null) !== null && $model->save($data, $options))) {
			return false;
		}
		return true;
	}
/**
 * Allows model records to be updated based on a set of conditions
 *
 * @param array $fields Set of fields and values, indexed by fields
 * @param mixed $conditions Conditions to match, true for all records
 * @return boolean True on success, false on failure
 * @access public
 */
	function updateAll($fields, $conditions = true) {
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		return $db->update($this, $fields, null, $conditions);
	}
/**
 * Synonym for del().
 *
 * @param mixed $id ID of record to delete
 * @param boolean $cascade Set to true to delete records that depend on this record
 * @return boolean True on success
 * @access public
 * @see Model::del()
 */
	function remove($id = null, $cascade = true) {
		return $this->del($id, $cascade);
	}
/**
 * Removes record for given id. If no id is given, the current id is used. Returns true on success.
 *
 * @param mixed $id ID of record to delete
 * @param boolean $cascade Set to true to delete records that depend on this record
 * @return boolean True on success
 * @access public
 */
	function del($id = null, $cascade = true) {
		if (!empty($id)) {
			$this->id = $id;
		}
		$id = $this->id;

		if ($this->exists() && $this->beforeDelete($cascade)) {
			$db =& ConnectionManager::getDataSource($this->useDbConfig);
			if (!$this->Behaviors->trigger($this, 'beforeDelete', array($cascade), array('break' => true, 'breakOn' => false))) {
				return false;
			}
			$this->_deleteDependent($id, $cascade);
			$this->_deleteLinks($id);
			$this->id = $id;

			if (!empty($this->belongsTo)) {
				$keys = $this->find('first', array('fields', $this->__collectForeignKeys()));
			}

			if ($db->delete($this)) {
				if (!empty($this->belongsTo)) {
					$this->updateCounterCache($keys[$this->alias]);
				}
				$this->Behaviors->trigger($this, 'afterDelete');
				$this->afterDelete();
				$this->_clearCache();
				$this->id = false;
				$this->__exists = null;
				return true;
			}
		}
		return false;
	}
/**
 * Synonym for del().
 *
 * @param mixed $id ID of record to delete
 * @param boolean $cascade Set to true to delete records that depend on this record
 * @return boolean True on success
 * @access public
 * @see Model::del()
 */
	function delete($id = null, $cascade = true) {
		return $this->del($id, $cascade);
	}
/**
 * Cascades model deletes to hasMany and hasOne relationships.
 *
 * @param string $id ID of record that was deleted
 * @param boolean $cascade Set to true to delete records that depend on this record
 * @access protected
 */
	function _deleteDependent($id, $cascade) {
		if (!empty($this->__backAssociation)) {
			$savedAssociatons = $this->__backAssociation;
			$this->__backAssociation = array();
		}
		foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
			if ($data['dependent'] === true && $cascade === true) {

				$model =& $this->{$assoc};
				$conditions = array($model->escapeField($data['foreignKey']) => $id);
				if ($data['conditions']) {
					$conditions = am($data['conditions'], $conditions);
				}
				$model->recursive = -1;

				if (isset($data['exclusive']) && $data['exclusive']) {
					$model->deleteAll($conditions);
				} else {
					$records = $model->find('all', array('conditions' => $conditions, 'fields' => $model->primaryKey));

					if (!empty($records)) {
						foreach ($records as $record) {
							$model->delete($record[$model->alias][$model->primaryKey]);
						}
					}
				}
			}
		}
		if (isset($savedAssociatons)) {
			$this->__backAssociation = $savedAssociatons;
		}
	}
/**
 * Cascades model deletes to HABTM join keys.
 *
 * @param string $id ID of record that was deleted
 * @access protected
 */
	function _deleteLinks($id) {
		$db =& ConnectionManager::getDataSource($this->useDbConfig);

		foreach ($this->hasAndBelongsToMany as $assoc => $data) {
			$records = $this->{$data['with']}->find('all', array(
				'conditions' => array($data['foreignKey'] => $id),
				'fields' => $this->{$data['with']}->primaryKey,
				'recursive' => -1
			));
			if (!empty($records)) {
				foreach ($records as $record) {
					$this->{$data['with']}->delete($record[$this->{$data['with']}->alias][$this->{$data['with']}->primaryKey]);
				}
			}
		}
	}
/**
 * Allows model records to be deleted based on a set of conditions
 *
 * @param mixed $conditions Conditions to match
 * @param boolean $cascade Set to true to delete records that depend on this record
 * @param boolean $callbacks Run callbacks (not being used)
 * @return boolean True on success, false on failure
 * @access public
 */
	function deleteAll($conditions, $cascade = true, $callbacks = false) {
		if (empty($conditions)) {
			return false;
		}
		$db =& ConnectionManager::getDataSource($this->useDbConfig);

		if (!$cascade && !$callbacks) {
			return $db->delete($this, $conditions);
		} else {
			$ids = Set::extract(
				$this->find('all', array_merge(array('fields' => "{$this->alias}.{$this->primaryKey}", 'recursive' => 0), compact('conditions'))),
				"{n}.{$this->alias}.{$this->primaryKey}"
			);

			if (empty($ids)) {
				return false;
			}

			if ($callbacks) {
				$_id = $this->id;

				foreach ($ids as $id) {
					$this->delete($id, $cascade);
				}
				$this->id = $_id;
			} else {
				foreach ($ids as $id) {
					$this->_deleteLinks($id);
					if ($cascade) {
						$this->_deleteDependent($id, $cascade);
					}
				}
				return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
			}
		}
	}
/**
 * Collects foreign keys from associations
 *
 * @access private
 */
	function __collectForeignKeys($type = 'belongsTo') {
		$result = array();

		foreach ($this->{$type} as $assoc => $data) {
			if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
				$result[$assoc] = $data['foreignKey'];
			}
		}
		return $result;
	}
/**
 * Returns true if a record with set id exists.
 *
 * @param boolean $reset if true will force database query
 * @return boolean True if such a record exists
 * @access public
 */
	function exists($reset = false) {
		if (is_array($reset)) {
			extract($reset, EXTR_OVERWRITE);
		}

		if ($this->getID() === false || $this->useTable === false) {
			return false;
		}
		if ($this->__exists !== null && $reset !== true) {
			return $this->__exists;
		}
		$conditions = array($this->alias . '.' . $this->primaryKey => $this->getID());
		$query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false);

		if (is_array($reset)) {
			$query = array_merge($query, $reset);
		}
		return $this->__exists = ($this->find('count', $query) > 0);
	}
/**
 * Returns true if a record that meets given conditions exists
 *
 * @param array $conditions SQL conditions array
 * @return boolean True if such a record exists
 * @access public
 */
	function hasAny($conditions = null) {
		return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
	}
/**
 * Return a single row as a resultset array.
 * By using the $recursive parameter, the call can access further "levels of association" than
 * the ones this model is directly associated to.
 *
 * Eg: find(array('name' => 'Thomas Anderson'), array('name', 'email'), 'field3 DESC', 2);
 *
 * Also used to perform new-notation finds, where the first argument is type of find operation to perform
 * (all / first / count), second parameter options for finding (indexed array, including: 'conditions', 'limit',
 * 'recursive', 'page', 'fields', 'offset', 'order')
 *
 * Eg: find('all', array(
 * 					'conditions' => array('name' => 'Thomas Anderson'),
 * 					'fields' => array('name', 'email'),
 * 					'order' => 'field3 DESC',
 * 					'recursive' => 2,
 * 					'group' => 'type'));
 *
 * Specifying 'fields' for new-notation 'list':
 *  - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
 *  - If a single field is specified, 'id' is used for key and specified field is used for value.
 *  - If three fields are specified, they are used (in order) for key, value and group.
 *  - Otherwise, first and second fields are used for key and value.
 *
 * @param array $conditions SQL conditions array, or type of find operation (all / first / count)
 * @param mixed $fields Either a single string of a field name, or an array of field names, or options for matching
 * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC")
 * @param integer $recursive The number of levels deep to fetch associated records
 * @return array Array of records
 * @access public
 */
	function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
		if (!is_string($conditions) || (is_string($conditions) && !array_key_exists($conditions, $this->__findMethods))) {
			$type = 'first';
			$query = array_merge(compact('conditions', 'fields', 'order', 'recursive'), array('limit' => 1));
		} else {
			list($type, $query) = array($conditions, $fields);
		}

		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		$this->findQueryType = $type;
		$this->id = $this->getID();

		$query = array_merge(
			array(
				'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
				'offset' => null, 'order' => null, 'page' => null, 'group' => null, 'callbacks' => true
			),
			(array)$query
		);

		if ($type != 'all') {
			if ($this->__findMethods[$type] === true) {
				$query = $this->{'_find' . ucfirst($type)}('before', $query);
			}
		}

		if (!is_numeric($query['page']) || intval($query['page']) < 1) {
			$query['page'] = 1;
		}
		if ($query['page'] > 1 && !empty($query['limit'])) {
			$query['offset'] = ($query['page'] - 1) * $query['limit'];
		}
		if ($query['order'] === null && $this->order !== null) {
			$query['order'] = $this->order;
		}
		$query['order'] = array($query['order']);

		if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
			$return = $this->Behaviors->trigger($this, 'beforeFind', array($query), array('break' => true, 'breakOn' => false, 'modParams' => true));
			$query = ife(is_array($return), $return, $query);

			if ($return === false) {
				return null;
			}

			$return = $this->beforeFind($query);
			$query = ife(is_array($return), $return, $query);

			if ($return === false) {
				return null;
			}
		}

		$results = $db->read($this, $query);
		$this->resetAssociations();
		$this->findQueryType = null;

		if ($type === 'all') {
			if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
				return $this->__filterResults($results);
			}
			return $results;
		} else {
			if ($this->__findMethods[$type] === true) {
				return $this->{'_find' . ucfirst($type)}('after', $query, $results);
			}
		}
	}
/**
 * Handles the before/after filter logic for find('first') operations.  Only called by Model::find().
 *
 * @param string $state Either "before" or "after"
 * @param array $query
 * @param array $data
 * @return array
 * @access protected
 */
	function _findFirst($state, $query, $results = array()) {
		if ($state == 'before') {
			$query['limit'] = 1;
			if (empty($query['conditions']) && !empty($this->id)) {
				$query['conditions'] = array($this->escapeField() => $this->id);
			}
			return $query;
		} elseif ($state == 'after') {
			$results = $this->__filterResults($results);
			if (empty($results[0])) {
				return false;
			}
			return $results[0];
		}
	}
/**
 * Handles the before/after filter logic for find('count') operations.  Only called by Model::find().
 *
 * @param string $state Either "before" or "after"
 * @param array $query
 * @param array $data
 * @return int The number of records found, or false
 * @access protected
 */
	function _findCount($state, $query, $results = array()) {
		if ($state == 'before') {
			if (empty($query['fields'])) {
				$db =& ConnectionManager::getDataSource($this->useDbConfig);
				$query['fields'] = $db->calculate($this, 'count');
			}
			$query['order'] = false;
			return $query;
		} elseif ($state == 'after') {
			if (isset($results[0][0]['count'])) {
				return intval($results[0][0]['count']);
			} elseif (isset($results[0][$this->alias]['count'])) {
				return intval($results[0][$this->alias]['count']);
			}
			return false;
		}
	}
/**
 * Handles the before/after filter logic for find('list') operations.  Only called by Model::find().
 *
 * @param string $state Either "before" or "after"
 * @param array $query
 * @param array $data
 * @return array Key/value pairs of primary keys/display field values of all records found
 * @access protected
 */
	function _findList($state, $query, $results = array()) {
		if ($state == 'before') {
			if (empty($query['fields'])) {
				$query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
				$list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
			} else {
				if (!is_array($query['fields'])) {
					$query['fields'] = String::tokenize($query['fields']);
				}

				if (count($query['fields']) == 1) {
					if (strpos($query['fields'][0], '.') === false) {
						$query['fields'][0] = $this->alias . '.' . $query['fields'][0];
					}

					$list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
					$query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
				} elseif (count($query['fields']) == 3) {
					for ($i = 0; $i < 3; $i++) {
						if (strpos($query['fields'][$i], '.') === false) {
							$query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
						}
					}

					$list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
				} else {
					for ($i = 0; $i < 2; $i++) {
						if (strpos($query['fields'][$i], '.') === false) {
							$query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
						}
					}

					$list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
				}
			}
			if (!isset($query['recursive']) || $query['recursive'] === null) {
				$query['recursive'] = -1;
			}
			list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
			return $query;
		} elseif ($state == 'after') {
			if (empty($results)) {
				return array();
			}
			return Set::combine(
				$this->__filterResults($results),
				$query['list']['keyPath'],
				$query['list']['valuePath'],
				$query['list']['groupPath']
			);
		}
	}
/**
 * findNeighbors method
 *
 * The before logic will find the previous field value, the after logic will then find the 'wrapping'
 * rows and return them
 *
 * @param string $state Either "before" or "after"
 * @param mixed $query
 * @param array $results
 * @return void
 * @access protected
 */
	function _findNeighbors($state, $query, $results = array()) {
		if ($state == 'before') {
			$query = array_merge(array('recursive' => 0), $query);
			extract($query);
			$conditions = (array)$conditions;
			if (isset($field) && isset($value)) {
				if (strpos($field, '.') === false) {
					$field = $this->alias . '.' . $field;
				}
			} else {
				$field = $this->alias . '.' . $this->primaryKey;
				$value = $this->id;
			}
			$query['conditions'] = 	array_merge($conditions, array($field . ' <' => $value));
			$query['order'] = $field . ' DESC';
			$query['limit'] = 1;
			$query['field'] = $field;
			$query['value'] = $value;
			return $query;
		} elseif ($state == 'after') {
			extract($query);
			unset($query['conditions'][$field . ' <']);
			$return = array();
			if (isset($results[0])) {
				$prevVal = Set::extract('/' . str_replace('.', '/', $field), $results[0]);
				$query['conditions'][$field . ' >='] = $prevVal[0];
				$query['conditions'][$field . ' !='] = $value;
				$query['limit'] = 2;
			} else {
				$return['prev'] = null;
				$query['conditions'][$field . ' >'] = $value;
				$query['limit'] = 1;
			}
			$query['order'] = $field . ' ASC';
			$return2 = $this->find('all', $query);
			if (!array_key_exists('prev', $return)) {
				$return['prev'] = $return2[0];
			}
			if (count($return2) == 2) {
				$return['next'] = $return2[1];
			} elseif (count($return2) == 1 && !$return['prev']) {
				$return['next'] = $return2[0];
			} else {
				$return['next'] = null;
			}
			return $return;
		}
	}
/**
 * findThreaded method
 *
 * @param mixed $state
 * @param mixed $query
 * @param array $results
 * @return array Threaded results
 * @access protected
 */
	function _findThreaded($state, $query, $results = array()) {
		if ($state == 'before') {
			return $query;
		} elseif ($state == 'after') {
			$return = $idMap = array();
			foreach ($results as $result) {
				$result['children'] = array();
				$id = $result[$this->alias]['id'];
				$parentId = $result[$this->alias]['parent_id'];
				if (isset($idMap[$id]['children'])) {
					$idMap[$id] = am($result, $idMap[$id]);
				} else {
					$idMap[$id] = am($result, array('children' => array()));
				}
				if ($parentId) {
					$idMap[$parentId]['children'][] =& $idMap[$id];
				} else {
					$return[] =& $idMap[$id];
				}
			}
			return $return;
		}
	}
/**
 * Passes query results through model and behavior afterFilter() methods
 *
 * @param array Results to filter
 * @param boolean $primary If this is the primary model results (results from model where the find operation was performed)
 * @return array Set of filtered results
 * @access private
 */
	function __filterResults($results, $primary = true) {
		$return = $this->Behaviors->trigger($this, 'afterFind', array($results, $primary), array('modParams' => true));
		if ($return !== true) {
			$results = $return;
		}
		return $this->afterFind($results, $primary);
	}
/**
 * Method is called only when bindTo<ModelName>() is used.
 * This resets the association arrays for the model back
 * to the original as set in the model.
 *
 * @return boolean Success
 * @access public
 */
	function resetAssociations() {
		if (!empty($this->__backAssociation)) {
			foreach ($this->__associations as $type) {
				if (isset($this->__backAssociation[$type])) {
					$this->{$type} = $this->__backAssociation[$type];
				}
			}
			$this->__backAssociation = array();
		}

		foreach ($this->__associations as $type) {
			foreach ($this->{$type} as $key => $name) {
				if (!empty($this->{$key}->__backAssociation)) {
					$this->{$key}->resetAssociations();
				}
			}
		}
		$this->__backAssociation = array();
		return true;
	}
/**
 * False if any fields passed match any (by default, all if $or = false) of their matching values.
 *
 * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
 * @param boolean $or If false, all fields specified must match in order for a false return value
 * @return boolean False if any records matching any fields are found
 * @access public
 */
	function isUnique($fields, $or = true) {
		if (!is_array($fields)) {
			$fields = func_get_args();
			if (is_bool($fields[count($fields) - 1])) {
				$or = $fields[count($fields) - 1];
				unset($fields[count($fields) - 1]);
			}
		}

		foreach ($fields as $field => $value) {
			if (is_numeric($field)) {
				unset($fields[$field]);

				$field = $value;
				if (isset($this->data[$this->alias][$field])) {
					$value = $this->data[$this->alias][$field];
				} else {
					$value = null;
				}
			}

			if (strpos($field, '.') === false) {
				unset($fields[$field]);
				$fields[$this->alias . '.' . $field] = $value;
			}
		}
		if ($or) {
			$fields = array('or' => $fields);
		}
		if (!empty($this->id)) {
			$fields[$this->alias . '.' . $this->primaryKey . ' !='] =  $this->id;
		}
		return ($this->find('count', array('conditions' => $fields)) == 0);
	}
/**
 * Returns a resultset for given SQL statement. Generic SQL queries should be made with this method.
 *
 * @param string $sql SQL statement
 * @return array Resultset
 * @access public
 */
	function query() {
		$params = func_get_args();
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		return call_user_func_array(array(&$db, 'query'), $params);
	}
/**
 * Returns true if all fields pass validation, otherwise false.
 *
 * @param string $options An optional array of custom options to be made available in the beforeValidate callback
 * @return boolean True if there are no errors
 * @access public
 */
	function validates($options = array()) {
		$errors = $this->invalidFields($options);
		if (is_array($errors)) {
			return count($errors) === 0;
		}
		return $errors;
	}
/**
 * Returns an array of fields that do not meet validation.
 *
 * @param string $options An optional array of custom options to be made available in the beforeValidate callback
 * @return array Array of invalid fields
 * @access public
 */
	function invalidFields($options = array()) {
		if (!$this->Behaviors->trigger($this, 'beforeValidate', array($options), array('break' => true, 'breakOn' => false)) || $this->beforeValidate($options) === false) {
			return $this->validationErrors;
		}

		if (!isset($this->validate) || empty($this->validate)) {
			return $this->validationErrors;
		}
		$data = $this->data;
		$methods = array_map('strtolower', get_class_methods($this));
		$behaviorMethods = array_keys($this->Behaviors->methods());

		if (isset($data[$this->alias])) {
			$data = $data[$this->alias];
		} elseif (!is_array($data)) {
			$data = array();
		}

		$Validation =& Validation::getInstance();
		$this->exists();

		foreach ($this->validate as $fieldName => $ruleSet) {
			if (!is_array($ruleSet) || (is_array($ruleSet) && isset($ruleSet['rule']))) {
				$ruleSet = array($ruleSet);
			}
			$default = array('allowEmpty' => null, 'required' => null, 'rule' => 'blank', 'last' => false, 'on' => null);

			foreach ($ruleSet as $index => $validator) {
				if (!is_array($validator)) {
					$validator = array('rule' => $validator);
				}
				$validator = array_merge($default, $validator);

				if (isset($validator['message'])) {
					$message = $validator['message'];
				} else {
					$message = __('This field cannot be left blank', true);
				}

				if (empty($validator['on']) || ($validator['on'] == 'create' && !$this->__exists) || ($validator['on'] == 'update' && $this->__exists)) {
					if ((!isset($data[$fieldName]) && $validator['required'] === true) || (isset($data[$fieldName]) && (empty($data[$fieldName]) && !is_numeric($data[$fieldName])) && $validator['allowEmpty'] === false)) {
						$this->invalidate($fieldName, $message);
						if ($validator['last']) {
							break;
						}
					} elseif (array_key_exists($fieldName, $data)) {
						if (empty($data[$fieldName]) && $data[$fieldName] != '0' && $validator['allowEmpty'] === true) {
							break;
						}
						if (is_array($validator['rule'])) {
							$rule = $validator['rule'][0];
							unset($validator['rule'][0]);
							$ruleParams = array_merge(array($data[$fieldName]), array_values($validator['rule']));
						} else {
							$rule = $validator['rule'];
							$ruleParams = array($data[$fieldName]);
						}

						$valid = true;

						if (in_array(strtolower($rule), $methods)) {
							$ruleParams[] = array_diff_key($validator, $default);
							$ruleParams[0] = array($fieldName => $ruleParams[0]);
							$valid = $this->dispatchMethod($rule, $ruleParams);
						} elseif (in_array($rule, $behaviorMethods) || in_array(strtolower($rule), $behaviorMethods)) {
							$ruleParams[] = array_diff_key($validator, $default);
							$ruleParams[0] = array($fieldName => $ruleParams[0]);
							$valid = $this->Behaviors->dispatchMethod($this, $rule, $ruleParams);
						} elseif (method_exists($Validation, $rule)) {
							$valid = $Validation->dispatchMethod($rule, $ruleParams);
						} elseif (!is_array($validator['rule'])) {
							$valid = preg_match($rule, $data[$fieldName]);
						}
						if (!$valid) {
							if (!isset($validator['message'])) {
								if (is_string($index)) {
									$validator['message'] = $index;
								} else {
									$validator['message'] = ife(is_numeric($index) && count($ruleSet) > 1, ($index + 1), $message);
								}
							}
							$this->invalidate($fieldName, $validator['message']);

							if ($validator['last']) {
								break;
							}
						}
					}
				}
			}
		}
		return $this->validationErrors;
	}
/**
 * Sets a field as invalid, optionally setting the name of validation
 * rule (in case of multiple validation for field) that was broken
 *
 * @param string $field The name of the field to invalidate
 * @param string $value Name of validation rule that was not met
 * @access public
 */
	function invalidate($field, $value = true) {
		if (!is_array($this->validationErrors)) {
			$this->validationErrors = array();
		}
		$this->validationErrors[$field] = $value;
	}
/**
 * Returns true if given field name is a foreign key in this Model.
 *
 * @param string $field Returns true if the input string ends in "_id"
 * @return boolean True if the field is a foreign key listed in the belongsTo array.
 * @access public
 */
	function isForeignKey($field) {
		$foreignKeys = array();
		if (!empty($this->belongsTo)) {
			foreach ($this->belongsTo as $assoc => $data) {
				$foreignKeys[] = $data['foreignKey'];
			}
		}
		return in_array($field, $foreignKeys);
	}
/**
 * Gets the display field for this model
 *
 * @return string The name of the display field for this Model (i.e. 'name', 'title').
 * @access public
 */
	function getDisplayField() {
		return $this->displayField;
	}
/**
 * Escapes the field name and prepends the model name. Escaping will be done according to the current database driver's rules.
 *
 * @param string $field Field to escape (e.g: id)
 * @param string $alias Alias for the model (e.g: Post)
 * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
 * @access public
 */
	function escapeField($field = null, $alias = null) {
		if (empty($alias)) {
			$alias = $this->alias;
		}
		if (empty($field)) {
			$field = $this->primaryKey;
		}
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		if (strpos($field, $db->name($alias)) === 0) {
			return $field;
		}
		return $db->name($alias . '.' . $field);
	}
/**
 * Returns the current record's ID
 *
 * @param integer $list Index on which the composed ID is located
 * @return mixed The ID of the current record, false if no ID
 * @access public
 */
	function getID($list = 0) {
		if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
			return false;
		}

		if (!is_array($this->id)) {
			return $this->id;
		}

		if (empty($this->id)) {
			return false;
		}

		if (isset($this->id[$list]) && !empty($this->id[$list])) {
			return $this->id[$list];
		} elseif (isset($this->id[$list])) {
			return false;
		}

		foreach ($this->id as $id) {
			return $id;
		}

		return false;
	}
/**
 * Top secret
 *
 * @access public
 */
	function normalizeFindParams($type, $data, $altType = null, $r = array(), $_this = null) {
		if ($_this == null) {
			$_this = $this;
			$root = true;
		}

		foreach ((array)$data as $name => $children) {
			if (is_numeric($name)) {
				$name = $children;
				$children = array();
			}

			if (strpos($name, '.') !== false) {
				$chain = explode('.', $name);
				$name = array_shift($chain);
				$children = array(join('.', $chain) => $children);
			}

			if (!empty($children)) {
				if ($_this->name == $name) {
					$r = array_merge($r, $this->normalizeFindParams($type, $children, $altType, $r, $_this));
				} else {
					if (!$_this->getAssociated($name)) {
						$r[$altType][$name] = $children;
					} else {
						$r[$name] = $this->normalizeFindParams($type, $children, $altType, @$r[$name], $_this->{$name});;
					}
				}
			} else {
				if ($_this->getAssociated($name)) {
					$r[$name] = array($type => null);
				} else {
					if ($altType != null) {
						$r[$type][] = $name;
					} else {
						$r[$type] = $name;
					}
				}
			}
		}

		if (isset($root)) {
			return array($this->name => $r);
		}
		return $r;
	}
/**
 * Returns the ID of the last record this Model inserted
 *
 * @return mixed Last inserted ID
 * @access public
 */
	function getLastInsertID() {
		return $this->getInsertID();
	}
/**
 * Returns the ID of the last record this Model inserted
 *
 * @return mixed Last inserted ID
 * @access public
 */
	function getInsertID() {
		return $this->__insertID;
	}
/**
 * Sets the ID of the last record this Model inserted
 *
 * @param mixed Last inserted ID
 * @access public
 */
	function setInsertID($id) {
		$this->__insertID = $id;
	}
/**
 * Returns the number of rows returned from the last query
 *
 * @return int Number of rows
 * @access public
 */
	function getNumRows() {
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		return $db->lastNumRows();
	}
/**
 * Returns the number of rows affected by the last query
 *
 * @return int Number of rows
 * @access public
 */
	function getAffectedRows() {
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		return $db->lastAffected();
	}
/**
 * Sets the DataSource to which this model is bound
 *
 * @param string $dataSource The name of the DataSource, as defined in app/config/database.php
 * @return boolean True on success
 * @access public
 */
	function setDataSource($dataSource = null) {
		$oldConfig = $this->useDbConfig;

		if ($dataSource != null) {
			$this->useDbConfig = $dataSource;
		}
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		if (!empty($oldConfig) && isset($db->config['prefix'])) {
			$oldDb =& ConnectionManager::getDataSource($oldConfig);

			if (empty($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) {
				$this->tablePrefix = $db->config['prefix'];
			}
		} elseif (isset($db->config['prefix'])) {
			$this->tablePrefix = $db->config['prefix'];
		}

		if (empty($db) || $db == null || !is_object($db)) {
			return $this->cakeError('missingConnection', array(array('className' => $this->alias)));
		}
	}
/**
 * Gets the DataSource to which this model is bound.
 * Not safe for use with some versions of PHP4, because this class is overloaded.
 *
 * @return object A DataSource object
 * @access public
 */
	function &getDataSource() {
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		return $db;
	}
/**
 * Gets all the models with which this model is associated
 *
 * @param string $type Only result associations of this type
 * @return array Associations
 * @access public
 */
	function getAssociated($type = null) {
		if ($type == null) {
			$associated = array();
			foreach ($this->__associations as $assoc) {
				if (!empty($this->{$assoc})) {
					$models = array_keys($this->{$assoc});
					foreach ($models as $m) {
						$associated[$m] = $assoc;
					}
				}
			}
			return $associated;
		} elseif (in_array($type, $this->__associations)) {
			if (empty($this->{$type})) {
				return array();
			}
			return array_keys($this->{$type});
		} else {
			$assoc = array_merge($this->hasOne, $this->hasMany, $this->belongsTo, $this->hasAndBelongsToMany);
			if (array_key_exists($type, $assoc)) {
				foreach ($this->__associations as $a) {
					if (isset($this->{$a}[$type])) {
						$assoc[$type]['association'] = $a;
						break;
					}
				}
				return $assoc[$type];
			}
			return null;
		}
	}
/**
 * Gets the name and fields to be used by a join model.  This allows specifying join fields in the association definition.
 *
 * @param object $model The model to be joined
 * @param mixed $with The 'with' key of the model association
 * @param array $keys Any join keys which must be merged with the keys queried
 * @return array
 */
	function joinModel($assoc, $keys = array()) {
		if (is_string($assoc)) {
			return array($assoc, array_keys($this->{$assoc}->schema()));
		} elseif (is_array($assoc)) {
			$with = key($assoc);
			return array($with, array_unique(array_merge($assoc[$with], $keys)));
		} else {
			trigger_error(sprintf(__('Invalid join model settings in %s', true), $model->alias), E_USER_WARNING);
		}
	}
/**
 * Before find callback
 *
 * @param array $queryData Data used to execute this query, i.e. conditions, order, etc.
 * @return mixed true if the operation should continue, false if it should abort; or, modified $queryData to continue with new $queryData
 * @access public
 */
	function beforeFind($queryData) {
		return true;
	}
/**
 * After find callback. Can be used to modify any results returned by find().
 *
 * @param mixed $results The results of the find operation
 * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association)
 * @return mixed Result of the find operation
 * @access public
 */
	function afterFind($results, $primary = false) {
		return $results;
	}
/**
 * Before save callback
 *
 * @return boolean True if the operation should continue, false if it should abort
 * @access public
 */
	function beforeSave() {
		return true;
	}
/**
 * After save callback
 *
 * @param boolean $created True if this save created a new record
 * @access public
 */
	function afterSave($created) {
	}
/**
 * Before delete callback
 *
 * @param boolean $cascade If true records that depend on this record will also be deleted
 * @return boolean True if the operation should continue, false if it should abort
 * @access public
 */
	function beforeDelete($cascade = true) {
		return true;
	}
/**
 * After delete callback
 *
 * @access public
 */
	function afterDelete() {
	}
/**
 * Before validate callback
 *
 * @return boolean True if validate operation should continue, false to abort
 * @access public
 */
	function beforeValidate() {
		return true;
	}
/**
 * DataSource error callback
 *
 * @access public
 */
	function onError() {
	}
/**
 * Private method. Clears cache for this model
 *
 * @param string $type If null this deletes cached views if Cache.check is true
 *                     Will be used to allow deleting query cache also
 * @return boolean true on delete
 * @access protected
 * @todo
 */
	function _clearCache($type = null) {
		if ($type === null) {
			if (Configure::read('Cache.check') === true) {
				$assoc[] = strtolower(Inflector::pluralize($this->alias));
				foreach ($this->__associations as $key => $association) {
					foreach ($this->$association as $key => $className) {
						$check = strtolower(Inflector::pluralize($className['className']));
						if (!in_array($check, $assoc)) {
							$assoc[] = strtolower(Inflector::pluralize($className['className']));
						}
					}
				}
				clearCache($assoc);
				return true;
			}
		} else {
			//Will use for query cache deleting
		}
	}
/**
 * Called when serializing a model
 *
 * @return array Set of object variable names this model has
 * @access private
 */
	function __sleep() {
		$return = array_keys(get_object_vars($this));
		return $return;
	}
/**
 * Called when unserializing a model
 *
 * @access private
 */
	function __wakeup() {
	}
/**
 * @deprecated
 * @see Model::find('all')
 */
	function findAll($conditions = null, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
		//trigger_error(__('(Model::findAll) Deprecated, use Model::find("all")', true), E_USER_WARNING);
		return $this->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
	}
/**
 * @deprecated
 * @see Model::find('count')
 */
	function findCount($conditions = null, $recursive = 0) {
		//trigger_error(__('(Model::findCount) Deprecated, use Model::find("count")', true), E_USER_WARNING);
		return $this->find('count', compact('conditions', 'recursive'));
	}
/**
 * @deprecated
 * @see Model::find('threaded')
 */
	function findAllThreaded($conditions = null, $fields = null, $order = null) {
		//trigger_error(__('(Model::findAllThreaded) Deprecated, use Model::find("threaded")', true), E_USER_WARNING);
		return $this->find('threaded', compact('conditions', 'fields', 'order'));
	}
/**
 * @deprecated
 * @see Model::find('neighbors')
 */
	function findNeighbours($conditions = null, $field, $value) {
		//trigger_error(__('(Model::findNeighbours) Deprecated, use Model::find("neighbors")', true), E_USER_WARNING);
		$query = compact('conditions', 'field', 'value');
		$query['fields'] = $field;
		if (is_array($field)) {
			$query['field'] = $field[0];
		}
		return $this->find('neighbors', $query);
	}
}
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
	Overloadable::overload('Model');
}
?>