zurmouser /app/protected/core/models/RedBeanModel.php

Language PHP Lines 3139
MD5 Hash f7b8c1ab84e9183523b9dc2a7ec1b5e3 Estimated Cost $62,684 (why?)
Repository https://bitbucket.org/ddonthula/zurmouser View Raw File View Project SPDX
   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
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
<?php
    /*********************************************************************************
     * Zurmo is a customer relationship management program developed by
     * Zurmo, Inc. Copyright (C) 2012 Zurmo Inc.
     *
     * Zurmo is free software; you can redistribute it and/or modify it under
     * the terms of the GNU General Public License version 3 as published by the
     * Free Software Foundation with the addition of the following permission added
     * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
     * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
     * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
     *
     * Zurmo is distributed in the hope that it will be useful, but WITHOUT
     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
     * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
     * details.
     *
     * You should have received a copy of the GNU General Public License along with
     * this program; if not, see http://www.gnu.org/licenses or write to the Free
     * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
     * 02110-1301 USA.
     *
     * You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207,
     * Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com.
     ********************************************************************************/

    /**
     * Abstraction over the top of an application database accessed via
     * <a href="http://www.redbeanphp.com/">RedBean</a>. The base class for
     * an MVC model. Replaces the M part of MVC in Yii. Yii maps from the
     * database scheme to the objects, (good for database guys, not so good
     * for OO guys), this maps from objects to the database schema.
     *
     * A domain model is created by extending RedBeanModel and supplying
     * a getDefaultMetadata() method.
     *
     * Static getXxxx() methods can be supplied to query for the given domain
     * models, and instance methods should supply additional behaviour.
     *
     * getDefaultMetadata() returns an array of the class name mapped to
     * an array containing 'members' mapped to an array of member names,
     * (to be accessed as $model->memberName).
     *
     * It can then optionally have, 'relations' mapped
     * to an array of relation names, (to be accessed as $model->relationName),
     * mapped to its type, (the extending model class to which it relates).
     *
     * And it can then optionally have as well, 'rules' mapped to an array of
     * attribute names, (attributes are members and relations), a validator name,
     * and the parameters to the validator, if any, as per the Yii::CModel::rules()
     * method.See http://www.yiiframework.com/wiki/56/reference-model-rules-validation.
     *
     * These are used to automatically and dynamically create the database
     * schema on the fly as opposed to Yii's getting attributes from an
     * already existing schema.
     */
    abstract class RedBeanModel extends ObservableComponent implements Serializable
    {
        /**
         * Models that have not been saved yet have no id as far
         * as the database is concerned. Until they are saved they are
         * assigned a negative id, so that they have identity.
         * @var integer
         */
        private static $nextPseudoId = -1;

        /**
         * Array of static models. Used by Observers @see ObservableComponent to add events to a class.
         * @var array
         */
        private static $_models = array();

        /*
         * The id of an unsaved model.
         * @var integer
         */
        private $pseudoId;

        /**
         * When creating the class heirarchy for bean creation and maintenence, which class is the last class in the
         * lineage to create a bean for?  Normally the RedBeanModel is the lastClass in the line, and therefore there
         * will not be a table redbeanmodel.  Some classes that extend RedBeanModel might want the line to stop before
         * RedBeanModel since creating a table with just an 'id' would be pointless.  @see OwnedModel
         * @var string
         */
        protected static $lastClassInBeanHeirarchy = 'RedBeanModel';

        // A model maps to one or more beans. If Person extends RedBeanModel
        // there is one bean, but if User then extends Person a User model
        // has two beans, the one holding the person data and the one holding
        // the extended User data. In this way in inheritance hierarchy from
        // model is normalized over several tables, one for each extending
        // class.
        private $modelClassNameToBean                            = array();
        private $attributeNameToBeanAndClassName                 = array();
        private $attributeNamesNotBelongsToOrManyMany            = array();
        private $relationNameToRelationTypeModelClassNameAndOwns = array();
        private $relationNameToRelatedModel                      = array();
        private $unlinkedRelationNames                           = array();
        private $validators                                      = array();
        private $attributeNameToErrors                           = array();
        private $scenarioName                                    = '';
        // An object is automatcally savable if it is new or contains
        // modified members or related objects.
        // If it is newly created and has never had any data put into it
        // it can be saved explicitly but it wont be saved automatically
        // when it is a related model and will be redispensed next
        // time it is referenced.
        protected $modified               = false;
        protected $deleted                = false;
        protected $isInIsModified         = false;
        protected $isInHasErrors          = false;
        protected $isInGetErrors          = false;
        protected $isValidating           = false;
        protected $isSaving               = false;
        protected $isNewModel             = false;

        /**
         * Can this model be saved when save is called from a related model?  True if it can, false if it cannot.
         * Setting this value to false can reduce unnecessary queries to the database. If the models of a class do
         * not change often then it can make sense to set this to false.  An example is @see Currency.
         * @var boolean
         */
        protected $isSavableFromRelation = true;

        // Mapping of Yii validators to validators doing things that
        // are either required for RedBean, or that simply implement
        // The semantics that we want.
        private static $yiiValidatorsToRedBeanValidators = array(
            'CDefaultValueValidator' => 'RedBeanModelDefaultValueValidator',
            'CNumberValidator'       => 'RedBeanModelNumberValidator',
            'CTypeValidator'         => 'RedBeanModelTypeValidator',
            'CRequiredValidator'     => 'RedBeanModelRequiredValidator',
            'CUniqueValidator'       => 'RedBeanModelUniqueValidator',
            'defaultCalculatedDate'  => 'RedBeanModelDefaultCalculatedDateValidator',
            'readOnly'               => 'RedBeanModelReadOnlyValidator',
            'dateTimeDefault'        => 'RedBeanModelDateTimeDefaultValueValidator',
        );

        /**
         * Can the class have a bean.  Some classes do not have beans as they are just used for modeling purposes
         * and do not need to store persistant data.
         * @var boolean
         */
        private static $canHaveBean = true;

        /**
         * Used in an extending class's getDefaultMetadata() method to specify
         * that a relation is 1:1 and that the class on the side of the relationship where this is not a column in that
         * model's table.  Example: model X HAS_ONE Y.  There will be a y_id on the x table.  But in Y you would have
         * HAS_ONE_BELONGS_TO X and there would be no column in the y table.
         */
        const HAS_ONE_BELONGS_TO = 0;

        /**
         * Used in an extending class's getDefaultMetadata() method to specify
         * that a relation is 1:M and that the class on the M side of the
         * relation.
         * Note: Currently if you have a relation that is set to HAS_MANY_BELONGS_TO, then that relation name
         * must be the strtolower() same as the related model class name.  This is the current support for this
         * relation type.  If something different is set, an exception will be thrown.
         */
        const HAS_MANY_BELONGS_TO = 1;

        /**
         * Used in an extending class's getDefaultMetadata() method to specify
         * that a relation is 1:1.
         */
        const HAS_ONE    = 2;

        /**
         * Used in an extending class's getDefaultMetadata() method to specify
         * that a relation is 1:M and that the class is on the 1 side of the
         * relation.
         */
        const HAS_MANY   = 3;

        /**
         * Used in an extending class's getDefaultMetadata() method to specify
         * that a relation is M:N and that the class on the either side of the
         * relation.
         */
        const MANY_MANY  = 4;

        /**
         * Used in an extending class's getDefaultMetadata() method to specify
         * that a 1:1 or 1:M relation is one in which the left side of the relation
         * owns the model or models on the right side, meaning that if the model
         * is deleted it owns the related models and they are deleted along with it.
         * If not specified the related model is independent and is not deleted.
         */
        const OWNED     = true;

        /**
         * @see const OWNED for more information.
         * @var boolean
         */
        const NOT_OWNED = false;

        /**
         * Returns the static model of the specified AR class.
         * The model returned is a static instance of the AR class.
         * It is provided for invoking class-level methods (something similar to static class methods.)
         *
         * EVERY derived AR class must override this method as follows,
         * <pre>
         * public static function model($className=__CLASS__)
         * {
         *     return parent::model($className);
         * }
         * </pre>
         *
         * @param string $className active record class name.
         * @return CActiveRecord active record model instance.
         */
        public static function model($className = null)
        {
            if ($className == null)
            {
                $className = get_called_class();
            }
            if (isset(self::$_models[$className]))
            {
                return self::$_models[$className];
            }
            else
            {
                $model = self::$_models[$className] = new $className(false);
                return $model;
            }
        }

        /**
         * Gets all the models from the database of the named model type.
         * @param $orderBy TODO
         * @param $modelClassName Pass only when getting it at runtime
         *                        gets the wrong name.
         * @return An array of models of the type of the extending model.
         */
        public static function getAll($orderBy = null, $sortDescending = false, $modelClassName = null)
        {
            assert('$orderBy        === null || is_string($orderBy)        && $orderBy        != ""');
            assert('is_bool($sortDescending)');
            assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
            $quote = DatabaseCompatibilityUtil::getQuote();
            $orderBySql = null;
            if ($orderBy !== null)
            {
                $orderBySql = "$quote$orderBy$quote";
                if ($sortDescending)
                {
                    $orderBySql .= ' desc';
                }
            }
            return static::getSubset(null, null, null, null, $orderBySql, $modelClassName);
        }

        /**
         * Gets a range of models from the database of the named model type.
         * @param $modelClassName
         * @param $joinTablesAdapter null or instance of joinTablesAdapter.
         * @param $offset The zero based index of the first model to be returned.
         * @param $count The number of models to be returned.
         * @param $where
         * @param $orderBy - sql string. Example 'a desc' or 'a.b desc'.  Currently only supports non-related attributes
         * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
         * @return An array of models of the type of the extending model.
         */
        public static function getSubset(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
                                         $offset = null, $count = null,
                                         $where = null, $orderBy = null,
                                         $modelClassName = null,
                                         $selectDistinct = false)
        {
            assert('$offset  === null || is_integer($offset)  && $offset  >= 0');
            assert('$count   === null || is_integer($count)   && $count   >= 1');
            assert('$where   === null || is_string ($where)   && $where   != ""');
            assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
            assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
            if ($modelClassName === null)
            {
                $modelClassName = get_called_class();
            }
            if ($joinTablesAdapter == null)
            {
                $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
            }
            $tableName = self::getTableName($modelClassName);
            $sql       = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, $offset, $count, $where,
                                                           $orderBy, false, $selectDistinct);
            $ids       = R::getCol($sql);
            $tableName = self::getTableName($modelClassName);
            $beans = R::batch ($tableName, $ids);
            return self::makeModels($beans, $modelClassName);
        }

        /**
         * @param boolean $selectCount If true then make this a count query. If false, select ids from rows.
         * @param array $quotedExtraSelectColumnNameAndAliases - extra columns to select.
         * @return string - sql statement.
         */
        public static function makeSubsetOrCountSqlQuery($tableName,
                                                         RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter,
                                                         $offset = null, $count = null,
                                                         $where = null, $orderBy = null,
                                                         $selectCount = false,
                                                         $selectDistinct = false,
                                                         array $quotedExtraSelectColumnNameAndAliases = array())
        {
            assert('is_string($tableName) && $tableName != ""');
            assert('$offset  === null || is_integer($offset)  && $offset  >= 0');
            assert('$count   === null || is_integer($count)   && $count   >= 1');
            assert('$where   === null || is_string ($where)   && $where   != ""');
            assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
            assert('is_bool($selectCount)');
            assert('is_bool($selectDistinct)');
            $selectQueryAdapter = new RedBeanModelSelectQueryAdapter($selectDistinct);
            if ($selectCount)
            {
                $selectQueryAdapter->addCountClause($tableName);
            }
            else
            {
                $selectQueryAdapter->addClause($tableName, 'id', 'id');
            }
            foreach ($quotedExtraSelectColumnNameAndAliases as $columnName => $columnAlias)
            {
                $selectQueryAdapter->addClauseWithColumnNameOnlyAndNoEnclosure($columnName, $columnAlias);
            }
            return SQLQueryUtil::
                   makeQuery($tableName, $selectQueryAdapter, $joinTablesAdapter, $offset, $count, $where, $orderBy);
        }

        /**
         * @param $modelClassName
         * @param $joinTablesAdapter null or instance of joinTablesAdapter.
         * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
         */
        public static function getCount(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
                                        $where = null, $modelClassName = null, $selectDistinct = false)
        {
            assert('$where          === null || is_string($where)');
            assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
            if ($modelClassName === null)
            {
                $modelClassName = get_called_class();
            }
            if ($joinTablesAdapter == null)
            {
                $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
            }
            $tableName      = self::getTableName($modelClassName);
            $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, null, null, $where, null, true,
                                                     $selectDistinct);
            $count = R::getCell($sql);
            if ($count === null || empty($count))
            {
                $count = 0;
            }
            return $count;
        }

        /**
         * Gets a model from the database by Id.
         * @param $id Integer Id.
         * @param $modelClassName Pass only when getting it at runtime
         *                        gets the wrong name.
         * @return A model of the type of the extending model.
         */
        public static function getById($id, $modelClassName = null)
        {
            assert('is_integer($id) && $id > 0');
            assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
            // I would have thought it was correct to user R::load() and get
            // a null, or error or something if the bean doesn't exist, but
            // it still returns a bean. So until I've investigated further
            // I'm using Finder.
            if ($modelClassName === null)
            {
                $modelClassName = get_called_class();
            }
            $tableName = self::getTableName($modelClassName);
            $beans = R::find($tableName, "id = '$id'");
            assert('count($beans) <= 1');
            if (count($beans) == 0)
            {
                throw new NotFoundException();
            }
            return RedBeanModel::makeModel(end($beans), $modelClassName);
        }

        public function getIsNewModel()
        {
            return $this->isNewModel;
        }

        /**
         * Constructs a new model.
         * Important:
         * Models are only constructed with beans by the RedBeanModel. Beans are
         * never used by the application directly.
         * The application can construct a new model object by constructing a
         * model without specifying a bean. In other words, if Php had
         * overloading a constructor with $setDefaults would be public, and
         * a constructor taking a $bean and $forceTreatAsCreation would be private.
         * @param $setDefaults. If false the default validators will not be run
         *                      on construction. The Yii way is that defaults are
         *                      filled in after the fact, which is counter the usual
         *                      for objects.
         * @param $bean A bean. Never specified by an application.
         * @param $forceTreatAsCreation. Never specified by an application.
         * @see getById()
         * @see makeModel()
         * @see makeModels()
         */
        public function __construct($setDefaults = true, RedBean_OODBBean $bean = null, $forceTreatAsCreation = false)
        {
            $this->pseudoId = self::$nextPseudoId--;
            $this->init();
            if ($bean === null)
            {
                foreach (array_reverse(RuntimeUtil::getClassHierarchy(get_class($this), static::$lastClassInBeanHeirarchy)) as $modelClassName)
                {
                    if ($modelClassName::getCanHaveBean())
                    {
                        $tableName = self::getTableName($modelClassName);
                        $newBean = R::dispense($tableName);
                        $this->modelClassNameToBean[$modelClassName] = $newBean;
                        $this->mapAndCacheMetadataAndSetHints($modelClassName, $newBean);
                    }
                }
                // The yii way of doing defaults is the the default validator
                // fills in the defaults on attributes that don't have values
                // when you validator, or save. This weird, since when you get
                // a model the things with defaults have not been defaulted!
                // We want that semantic.
                if ($setDefaults)
                {
                    $this->runDefaultValidators();
                }
                $forceTreatAsCreation = true;
            }
            else
            {
                assert('$bean->id > 0');
                $first = true;
                foreach (RuntimeUtil::getClassHierarchy(get_class($this), static::$lastClassInBeanHeirarchy) as $modelClassName)
                {
                    if ($modelClassName::getCanHaveBean())
                    {
                        if ($first)
                        {
                            $lastBean = $bean;
                            $first = false;
                        }
                        else
                        {
                            $tableName = self::getTableName($modelClassName);
                            $lastBean = ZurmoRedBeanLinkManager::getBean($lastBean, $tableName);
                            if ($lastBean === null)
                            {
                                throw new MissingBeanException();
                            }
                            assert('$lastBean->id > 0');
                        }
                        $this->modelClassNameToBean[$modelClassName] = $lastBean;
                        $this->mapAndCacheMetadataAndSetHints($modelClassName, $lastBean);
                    }
                }
                $this->modelClassNameToBean = array_reverse($this->modelClassNameToBean);
            }

            $this->constructDerived($bean, $setDefaults);
            if ($forceTreatAsCreation)
            {
                $this->onCreated();
            }
            else
            {
                $this->onLoaded();
                RedBeanModelsCache::cacheModel($this);
            }
            $this->modified = false;
        }

        // Derived classes can insert additional steps into the construction.
        protected function constructDerived($bean, $setDefaults)
        {
            assert('$bean === null || $bean instanceof RedBean_OODBBean');
            assert('is_bool($setDefaults)');
        }

        /**
         * Utilized when pieces of information need to be constructed on an existing model, that can potentially be
         * missing. For example, if a model is created, then a custom field is added, it is possible the cached model
         * is missing the custom field customFieldData.
         * @param unknown_type $bean
         */
        protected function constructIncomplete($bean)
        {
            assert('$bean === null || $bean instanceof RedBean_OODBBean');
            $this->init();
        }

        public function serialize()
        {
            return serialize(array(
                $this->pseudoId,
                $this->modelClassNameToBean,
                $this->attributeNameToBeanAndClassName,
                $this->attributeNamesNotBelongsToOrManyMany,
                $this->relationNameToRelationTypeModelClassNameAndOwns,
                $this->validators,
            ));
        }

        public function unserialize($data)
        {
            try
            {
                $data = unserialize($data);
                assert('is_array($data)');
                if (count($data) != 6)
                {
                    return null;
                }

                $this->pseudoId                                        = $data[0];
                $this->modelClassNameToBean                            = $data[1];
                $this->attributeNameToBeanAndClassName                 = $data[2];
                $this->attributeNamesNotBelongsToOrManyMany            = $data[3];
                $this->relationNameToRelationTypeModelClassNameAndOwns = $data[4];
                $this->validators                                      = $data[5];

                $this->relationNameToRelatedModel = array();
                $this->unlinkedRelationNames      = array();
                $this->attributeNameToErrors      = array();
                $this->scenarioName               = '';
                $this->modified                   = false;
                $this->deleted                    = false;
                $this->isInIsModified             = false;
                $this->isInHasErrors              = false;
                $this->isInGetErrors              = false;
                $this->isValidating               = false;
                $this->isSaving                   = false;
            }
            catch (Exception $e)
            {
                return null;
            }
        }

        /**
         * Overriding constructors must call this function to ensure that
         * they leave the newly constructed instance not modified since
         * anything modifying the class during constructionm will set it
         * modified automatically.
         */
        protected function setNotModified()
        {
            $this->modified = false;        // This sets this class to the right state.
            assert('!$this->isModified()'); // This tests that related classes are in the right state.
        }

        /**
         * By default the table name is the lowercased class name. If this
         * conflicts with a database keyword override to return true.
         * RedBean does not quote table names in most cases.
         */
        // Public for unit testing.
        public static function mangleTableName()
        {
            return false;
        }

        /**
         * Returns the table name for a class.
         * For use by RedBeanModelDataProvider. It will not
         * be of any use to an application. Applications
         * should not be doing anything table related.
         * Derived classes can refer directly to the
         * table name.
         */
        public static function getTableName($modelClassName)
        {
            assert('is_string($modelClassName) && $modelClassName != ""');
            $tableName = strtolower($modelClassName);
            if ($modelClassName::mangleTableName())
            {
                $tableName = '_' . $tableName;
            }
            return $tableName;
        }

        /**
         * Returns the table names for an array of classes.
         * For use by RedBeanModelDataProvider. It will not
         * be of any use to an application.
         */
        public static function getTableNames($classNames)
        {
            $tableNames = array();
            foreach ($classNames as $className)
            {
                $tableNames[] = self::getTableName($className);
            }
            return $tableNames;
        }

        /**
         * Used by classes such as containers which use sql to
         * optimize getting models from the database.
         */
        public static function getForeignKeyName($modelClassName, $relationName)
        {
            assert('is_string($modelClassName)');
            assert('$modelClassName != ""');
            $metadata = $modelClassName::getMetadata();
            foreach ($metadata as $modelClassName => $modelClassMetadata)
            {
                if (isset($metadata[$modelClassName]["relations"]) &&
                    array_key_exists($relationName, $metadata[$modelClassName]["relations"]))
                {
                    $relatedModelClassName = $metadata[$modelClassName]['relations'][$relationName][1];
                    self::resolveModelClassNameForClassesWithoutBeans($relatedModelClassName);
                    $relatedModelTableName = self::getTableName($relatedModelClassName);
                    $columnName = '';
                    if (strtolower($relationName) != strtolower($relatedModelClassName))
                    {
                        $columnName = strtolower($relationName) . '_';
                    }
                    $columnName .= $relatedModelTableName . '_id';
                    return $columnName;
                }
            }
            throw new NotSupportedException;
        }

        /**
         * Called on construction when a new model is created.
         */
        protected function onCreated()
        {
        }

        /**
         * Called on construction when a model is loaded.
         */
        protected function onLoaded()
        {
        }

        /**
         * Called when a model is modified.
         */
        protected function onModified()
        {
        }

        /**
         * Used for mixins.
         */
        protected function mapAndCacheMetadataAndSetHints($modelClassName, RedBean_OODBBean $bean)
        {
            assert('is_string($modelClassName)');
            assert('$modelClassName != ""');
            $metadata = $this->getMetadata();
            if (isset($metadata[$modelClassName]))
            {
                $hints = array();
                if (isset($metadata[$modelClassName]['members']))
                {
                    foreach ($metadata[$modelClassName]['members'] as $memberName)
                    {
                        $this->attributeNameToBeanAndClassName[$memberName] = array($bean, $modelClassName);
                        $this->attributeNamesNotBelongsToOrManyMany[] = $memberName;
                        if (substr($memberName, -2) == 'Id')
                        {
                            $columnName = strtolower($memberName);
                            $hints[$columnName] = 'id';
                        }
                    }
                }
                if (isset($metadata[$modelClassName]['relations']))
                {
                    foreach ($metadata[$modelClassName]['relations'] as $relationName => $relationTypeModelClassNameAndOwns)
                    {
                        assert('in_array(count($relationTypeModelClassNameAndOwns), array(2, 3, 4))');

                        $relationType           = $relationTypeModelClassNameAndOwns[0];
                        $relationModelClassName = $relationTypeModelClassNameAndOwns[1];
                        if ($relationType == self::HAS_MANY_BELONGS_TO &&
                           strtolower($relationName) != strtolower($relationModelClassName))
                        {
                            $label = 'Relations of type HAS_MANY_BELONGS_TO must have the relation name ' .
                                     'the same as the related model class name. Relation: {relationName} ' .
                                     'Relation model class name: {relationModelClassName}';
                            throw new NotSupportedException(Yii::t('Default', $label,
                                      array('{relationName}' => $relationName,
                                            '{relationModelClassName}' => $relationModelClassName)));
                        }
                        if (count($relationTypeModelClassNameAndOwns) >= 3 &&
                            $relationTypeModelClassNameAndOwns[2] == self::OWNED)
                        {
                            $owns = true;
                        }
                        else
                        {
                            $owns = false;
                        }
                        if (count($relationTypeModelClassNameAndOwns) == 4 && $relationType != self::HAS_MANY)
                        {
                            throw new NotSupportedException();
                        }
                        if (count($relationTypeModelClassNameAndOwns) == 4)
                        {
                            $relationPolyOneToManyName = $relationTypeModelClassNameAndOwns[3];
                        }
                        else
                        {
                            $relationPolyOneToManyName = null;
                        }
                        assert('in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, ' .
                                                             'self::HAS_ONE, self::HAS_MANY, self::MANY_MANY))');
                        $this->attributeNameToBeanAndClassName[$relationName] = array($bean, $modelClassName);
                        $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName] = array($relationType,
                                                                                                $relationModelClassName,
                                                                                                $owns,
                                                                                                $relationPolyOneToManyName);
                        if (!in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, self::MANY_MANY)))
                        {
                            $this->attributeNamesNotBelongsToOrManyMany[] = $relationName;
                        }
                    }
                }
                // Add model validators. Parent validators are already applied.
                if (isset($metadata[$modelClassName]['rules']))
                {
                    foreach ($metadata[$modelClassName]['rules'] as $validatorMetadata)
                    {
                        assert('isset($validatorMetadata[0])');
                        assert('isset($validatorMetadata[1])');
                        $attributeName       = $validatorMetadata[0];
                        // Each rule in RedBeanModel must specify one attribute name.
                        // This was just better style, now it is mandatory.
                        assert('strpos($attributeName, " ") === false');
                        $validatorName       = $validatorMetadata[1];
                        $validatorParameters = array_slice($validatorMetadata, 2);
                        if (isset(CValidator::$builtInValidators[$validatorName]))
                        {
                            $validatorName = CValidator::$builtInValidators[$validatorName];
                        }
                        if (isset(self::$yiiValidatorsToRedBeanValidators[$validatorName]))
                        {
                            $validatorName = self::$yiiValidatorsToRedBeanValidators[$validatorName];
                        }
                        $validator = CValidator::createValidator($validatorName, $this, $attributeName, $validatorParameters);

                        switch ($validatorName)
                        {
                            case 'RedBeanModelTypeValidator':
                            case 'TypeValidator':
                                $columnName = strtolower($attributeName);
                                if (array_key_exists($columnName, $hints))
                                {
                                    unset($hints[$columnName]);
                                }
                                if (in_array($validator->type, array('date', 'datetime', 'blob', 'longblob', 'string', 'text', 'longtext')))
                                {
                                    $hints[$columnName] = $validator->type;
                                }
                                break;
                            case 'CBooleanValidator':
                                $columnName = strtolower($attributeName);
                                $hints[$columnName] = 'boolean';
                                break;
                            case 'RedBeanModelUniqueValidator':
                                if (!$this->isRelation($attributeName))
                                {
                                    $bean->setMeta("buildcommand.unique", array(array($attributeName)));
                                }
                                else
                                {
                                    $relatedModelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][1];
                                    $relatedModelTableName = self::getTableName($relatedModelClassName);
                                    $columnName = strtolower($attributeName);
                                    if ($columnName != $relatedModelTableName)
                                    {
                                        $columnName .= '_' . $relatedModelTableName;
                                    }
                                    $columnName .= '_id';
                                    $bean->setMeta("buildcommand.unique", array(array($columnName)));
                                }
                                break;
                        }
                        $this->validators[] = $validator;
                    }

                    // Check if we need to update string type to long string type, based on validators.
                        if (isset($metadata[$modelClassName]['members']))
                        {
                            foreach ($metadata[$modelClassName]['members'] as $memberName)
                            {
                                $allValidators = $this->getValidators($memberName);
                                if (!empty($allValidators))
                                {
                                    foreach ($allValidators as $validator)
                                    {
                                        if ((get_class($validator) == 'RedBeanModelTypeValidator' ||
                                            get_class($validator) == 'TypeValidator') &&
                                            $validator->type == 'string')
                                        {
                                            $columnName = strtolower($validator->attributes[0]);
                                            if (count($allValidators) > 1)
                                            {
                                                $haveCStringValidator = false;
                                                foreach ($allValidators as $innerValidator)
                                                {
                                                    if (get_class($innerValidator) == 'CStringValidator' &&
                                                        isset($innerValidator->max) &&
                                                        $innerValidator->max > 0)
                                                    {
                                                        if ($innerValidator->max > 65535)
                                                        {
                                                            $hints[$columnName] = 'longtext';
                                                        }
                                                        elseif ($innerValidator->max < 255)
                                                        {
                                                            $hints[$columnName] = "string({$innerValidator->max})";
                                                        }
                                                        else
                                                        {
                                                            $hints[$columnName] = 'text';
                                                        }
                                                    }
                                                    if (get_class($innerValidator) == 'CStringValidator')
                                                    {
                                                        $haveCStringValidator = true;
                                                    }
                                                }
                                                if (!$haveCStringValidator)
                                                {
                                                    $hints[$columnName] = 'text';
                                                }
                                            }
                                            else
                                            {
                                                $hints[$columnName] = 'text';
                                            }
                                        }
                                    }
                                }
                            }
                        }
                }
                $bean->setMeta('hint', $hints);
            }
        }

        /**
         * Used for mixins.
         */
        protected function runDefaultValidators()
        {
            foreach ($this->validators as $validator)
            {
                if ($validator instanceof CDefaultValueValidator)
                {
                    $validator->validate($this);
                }
            }
        }

        /**
         * For use only by RedBeanModel and RedBeanModels. Beans are
         * never used by the application directly.
         */
        public function getPrimaryBean()
        {
            return end($this->modelClassNameToBean);
        }

        /**
         * Used for optimization.
         */
        public function getClassId($modelClassName)
        {
            assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
            return intval($this->getClassBean($modelClassName)->id); // Trying to combat the slop.
        }

        public function getClassBean($modelClassName)
        {
            assert('is_string($modelClassName)');
            assert('$modelClassName != ""');
            self::resolveModelClassNameForClassesWithoutBeans($modelClassName);
            assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
            return $this->modelClassNameToBean[$modelClassName];
        }

        /**
         * Used for mixins.
         */
        protected function setClassBean($modelClassName, RedBean_OODBBean $bean)
        {
            assert('is_string($modelClassName)');
            assert('$modelClassName != ""');
            assert('!array_key_exists($modelClassName, $this->modelClassNameToBean)');
            $this->modelClassNameToBean = array_merge(array($modelClassName => $bean),
                                                      $this->modelClassNameToBean);
        }

        public function getModelIdentifier()
        {
            return get_class($this) . strval($this->getPrimaryBean()->id);
        }

        /**
         * Returns metadata for the model.  Attempts to cache metadata, if it is not already cached.
         * @see getDefaultMetadata()
         * @returns An array of metadata.
         */
        public static function getMetadata()
        {
            try
            {
                return GeneralCache::getEntry(get_called_class() . 'Metadata');
            }
            catch (NotFoundException $e)
            {
                $className = get_called_Class();
                $defaultMetadata = $className::getDefaultMetadata();
                $metadata = array();
                foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy)) as $modelClassName)
                {
                    if ($modelClassName::getCanHaveBean())
                    {
                        if ($modelClassName::canSaveMetadata())
                        {
                            try
                            {
                                $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
                                $metadata[$modelClassName] = unserialize($globalMetadata->serializedMetadata);
                            }
                            catch (NotFoundException $e)
                            {
                                if (isset($defaultMetadata[$modelClassName]))
                                {
                                    $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
                                }
                            }
                        }
                        else
                        {
                            if (isset($defaultMetadata[$modelClassName]))
                            {
                                $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
                            }
                        }
                    }
                }
                if (YII_DEBUG)
                {
                    self::assertMetadataIsValid($metadata);
                }
                GeneralCache::cacheEntry(get_called_class() . 'Metadata', $metadata);
                return $metadata;
            }
        }

        /**
         * By default models cannot save their metadata, allowing
         * them to be loaded quickly because the loading of of
         * metadata can be avoided as much as possible.
         * To make a model able to save its metadata override
         * this method to return true. PUT it before the
         * getDefaultMetadata in the derived class.
         */
        public static function canSaveMetadata()
        {
            return false;
        }

        /**
         * Sets metadata for the model.
         * @see getDefaultMetadata()
         * @returns An array of metadata.
         */
        public static function setMetadata(array $metadata)
        {
            if (YII_DEBUG)
            {
                self::assertMetadataIsValid($metadata);
            }
            $className = get_called_class();
            foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy)) as $modelClassName)
            {
                if ($modelClassName::getCanHaveBean())
                {
                    if ($modelClassName::canSaveMetadata())
                    {
                        if (isset($metadata[$modelClassName]))
                        {
                            try
                            {
                                $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
                            }
                            catch (NotFoundException $e)
                            {
                                $globalMetadata = new GlobalMetadata();
                                $globalMetadata->className = $modelClassName;
                            }
                            $globalMetadata->serializedMetadata = serialize($metadata[$modelClassName]);
                            $saved = $globalMetadata->save();
                            // TODO: decide how to deal with this properly if it fails.
                            //       ie: throw or return false, or something other than
                            //           this naughty assert.
                            assert('$saved');
                        }
                    }
                }
            }
            RedBeanModelsCache::forgetAllByModelType(get_called_class());
            GeneralCache::forgetEntry(get_called_class() . 'Metadata');
        }

        /**
         * Returns the default meta data for the class.
         * It must be appended to the meta data
         * from the parent model, if any.
         */
        public static function getDefaultMetadata()
        {
            return array();
        }

        protected static function assertMetadataIsValid(array $metadata)
        {
            $className = get_called_Class();
            foreach (RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy) as $modelClassName)
            {
                if ($modelClassName::getCanHaveBean())
                {
                    if (isset($metadata[$modelClassName]['members']))
                    {
                        assert('is_array($metadata[$modelClassName]["members"])');
                        foreach ($metadata[$modelClassName]["members"] as $memberName)
                        {
                            assert('ctype_lower($memberName{0})');
                        }
                    }
                    if (isset($metadata[$modelClassName]['relations']))
                    {
                        assert('is_array($metadata[$modelClassName]["relations"])');
                        foreach ($metadata[$modelClassName]["relations"] as $relationName => $notUsed)
                        {
                            assert('ctype_lower($relationName{0})');
                        }
                    }
                    if (isset($metadata[$modelClassName]['rules']))
                    {
                        assert('is_array($metadata[$modelClassName]["rules"])');
                    }
                    if (isset($metadata[$modelClassName]['defaultSortAttribute']))
                    {
                        assert('is_string($metadata[$modelClassName]["defaultSortAttribute"])');
                    }
                    if (isset($metadata[$modelClassName]['rollupRelations']))
                    {
                        assert('is_array($metadata[$modelClassName]["rollupRelations"])');
                    }
                }
                // Todo: add more rules here as I think of them.
            }
        }

        /**
         * Downcasting in general is a bad concept, but when pulling
         * a Person from the database it would require a lot of
         * jumping through hoops to make the RedBeanModel automatically
         * figure out if that person is really a User, Contact, Customer
         * or whatever might be derived from Person. So to avoid that
         * complication and performance hit where it is not necessary
         * this method can be used to convert a model to one of
         * a given set of derivatives. If model is not one
         * of those NotFoundException is thrown.
         */
        public function castDown(array $derivedModelClassNames)
        {
            $bean = $this->getPrimaryBean();
            $thisModelClassName = get_called_class();
            $key = strtolower($thisModelClassName) . '_id';
            foreach ($derivedModelClassNames as $modelClassNames)
            {
                if (is_string($modelClassNames))
                {
                    $nextModelClassName = $modelClassNames;
                    if (get_class($this) == $nextModelClassName)
                    {
                        return $this;
                    }
                    $nextBean = self::findNextDerivativeBean($bean, $thisModelClassName, $nextModelClassName);
                }
                else
                {
                    assert('is_array($modelClassNames)');
                    $targetModelClassName = end($modelClassNames);
                    if (get_class($this) == $targetModelClassName)
                    {
                        return $this;
                    }
                    $currentModelClassName = $thisModelClassName;
                    $nextBean = $bean;
                    foreach ($modelClassNames as $nextModelClassName)
                    {
                        $nextBean = self::findNextDerivativeBean($nextBean, $currentModelClassName, $nextModelClassName);
                        if ($nextBean === null)
                        {
                            break;
                        }
                        $currentModelClassName = $nextModelClassName;
                    }
                }
                if ($nextBean !== null)
                {
                    return self::makeModel($nextBean, $nextModelClassName);
                }
            }
            throw new NotFoundException();
        }

        private static function findNextDerivativeBean($bean, $modelClassName1, $modelClassName2)
        {
            $key = strtolower($modelClassName1) . '_id';
            $tableName = self::getTableName($modelClassName2);
            $beans = R::find($tableName, "$key = :id", array('id' => $bean->id));
            if (count($beans) == 1)
            {
                return reset($beans);
            }
            return null;
        }

        /**
         * Returns whether the given object is of the same type with the
         * same id.
         */
        public function isSame(RedBeanModel $model)
        {
            // The two models are the same if they have the
            // same root model, and if for that model they
            // have the same id.
            $rootId1 = reset($this ->modelClassNameToBean)->id;
            $rootId2 = reset($model->modelClassNameToBean)->id;
            if ($rootId1 == 0)
            {
                $rootId1 = $this->pseudoId;
            }
            if ($rootId2 == 0)
            {
                $rootId2 = $model->pseudoId;
            }
            return $rootId1 == $rootId2 && $rootId1 != 0 &&
                   key($this ->modelClassNameToBean) ==
                   key($model->modelClassNameToBean);
        }

        /**
         * Returns the displayable string for the class. Should be
         * overridden in any model that can provide a meaningful string
         * representation of itself.
         * @return A string.
         */
        public function __toString()
        {
            return Zurmo::t('Core', '(None)');
        }

        /**
         * Exposes the members and relations of the model as if
         * they were actual attributes of the model. See __set().
         * @param $attributeName A non-empty string that is the name of a
         * member or relation.
         * @see attributeNames()
         * @return A value or model of the type specified as valid for the
         * member or relation by the meta data supplied by the extending
         * class's getMetadata() method.
         */
        public function __get($attributeName)
        {
            return $this->unrestrictedGet($attributeName);
        }

        /**
         * A protected version of __get() for models to talk to themselves
         * to use their dynamically created members from 'members'
         * and 'relations' in its metadata.
         */
        protected function unrestrictedGet($attributeName)
        {
            assert('is_string($attributeName)');
            assert('$attributeName != ""');
            assert("property_exists(\$this, '$attributeName') || \$this->isAttribute('$attributeName')");
            if (property_exists($this, $attributeName))
            {
                return $this->$attributeName;
            }
            elseif ($attributeName == 'id')
            {
                $id = intval($this->getPrimaryBean()->id);
                assert('$id >= 0');
                if ($id == 0)
                {
                    $id = $this->pseudoId;
                }
                return $id;
            }
            elseif ($this->isAttribute($attributeName))
            {
                list($bean, $attributeModelClassName) = $this->attributeNameToBeanAndClassName[$attributeName];
                if (!$this->isRelation($attributeName))
                {
                    $columnName = strtolower($attributeName);
                    return $bean->$columnName;
                }
                else
                {
                    if (!array_key_exists($attributeName, $this->relationNameToRelatedModel))
                    {
                        list($relationType, $relatedModelClassName, $owns, $relationPolyOneToManyName) =
                             $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName];

                        $tempRelatedModelClassName = $relatedModelClassName;
                        self::resolveModelClassNameForClassesWithoutBeans($tempRelatedModelClassName);
                        $relatedTableName          = self::getTableName($tempRelatedModelClassName);
                        switch ($relationType)
                        {
                            case self::HAS_ONE_BELONGS_TO:
                                $linkName          = strtolower(get_class($this));
                                $columnName        = $linkName . '_id';
                                $relatedBeans      = R::find($relatedTableName, $columnName . " = " . $bean->id);
                                if (count($relatedBeans) > 1)
                                {
                                    throw new NotFoundException();
                                }
                                elseif (count($relatedBeans) == 0)
                                {
                                    $relatedModel = new $relatedModelClassName();
                                }
                                else
                                {
                                    $relatedModel = self::makeModel(end($relatedBeans), $relatedModelClassName);
                                }
                                $this->relationNameToRelatedModel[$attributeName] = $relatedModel;
                                break;
                            case self::HAS_ONE:
                            case self::HAS_MANY_BELONGS_TO:
                                if ($relationType == self::HAS_ONE)
                                {
                                    $linkName = strtolower($attributeName);
                                    if ($linkName == strtolower($relatedModelClassName))
                                    {
                                        $linkName = null;
                                    }
                                }
                                else
                                {
                                    $linkName = null;
                                }
                                if ($bean->id > 0 && !in_array($attributeName, $this->unlinkedRelationNames))
                                {
                                    $linkFieldName = ZurmoRedBeanLinkManager::getLinkField($relatedTableName, $linkName);
                                    if ((int)$bean->$linkFieldName > 0)
                                    {
                                        $beanIdentifier = $relatedTableName .(int)$bean->$linkFieldName;
                                        try
                                        {
                                            $relatedBean = RedBeansCache::getBean($beanIdentifier);
                                        }
                                        catch (NotFoundException $e)
                                        {
                                            $relatedBean = ZurmoRedBeanLinkManager::getBean($bean, $relatedTableName, $linkName);
                                            RedBeansCache::cacheBean($relatedBean, $beanIdentifier);
                                        }
                                        if ($relatedBean !== null && $relatedBean->id > 0)
                                        {
                                            $relatedModel = self::makeModel($relatedBean, $relatedModelClassName);
                                        }
                                    }
                                }
                                if (!isset($relatedModel))
                                {
                                    $relatedModel = new $relatedModelClassName();
                                }
                                $this->relationNameToRelatedModel[$attributeName] = $relatedModel;
                                break;

                            case self::HAS_MANY:
                                $this->relationNameToRelatedModel[$attributeName] =
                                    new RedBeanOneToManyRelatedModels($bean,
                                                                      $relatedModelClassName,
                                                                      $attributeModelClassName,
                                                                      $owns,
                                                                      $relationPolyOneToManyName);
                                break;

                            case self::MANY_MANY:
                                $this->relationNameToRelatedModel[$attributeName] = new RedBeanManyToManyRelatedModels($bean, $relatedModelClassName);
                                break;

                            default:
                                throw new NotSupportedException();
                        }
                    }
                    return $this->relationNameToRelatedModel[$attributeName];
                }
            }
            else
            {
                throw new NotSupportedException('Invalid Attribute: ' . $attributeName);
            }
        }

        /**
         * Sets the members and relations of the model as if
         * they were actual attributes of the model. For example, if Account
         * extends RedBeanModel and its attributeNames() returns that one it has
         * a member 'name' and a relation 'owner' they are simply
         * accessed as:
         * @code
         *   $account = new Account();
         *   $account->name = 'International Corp';
         *   $account->owner = User::getByUsername('bill');
         *   $account->save();
         * @endcode
         * @param $attributeName A non-empty string that is the name of a
         * member or relation of the model.
         * @param $value A value or model of the type specified as valid for the
         * member or relation by the meta data supplied by the extending
         * class's getMetadata() method.
         */
        public function __set($attributeName, $value)
        {
            if ($attributeName == 'id' ||
                ($this->isAttributeReadOnly($attributeName) && !$this->isAllowedToSetReadOnlyAttribute($attributeName)))
            {
                throw new NotSupportedException();
            }
            else
            {
                if ($this->unrestrictedSet($attributeName, $value))
                {
                    $this->modified = true;
                    $this->onModified();
                }
            }
        }

        /**
         * A protected version of __set() for models to talk to themselves
         * to use their dynamically created members from 'members'
         * and 'relations' in its metadata.
         */
        protected function unrestrictedSet($attributeName, $value)
        {
            assert('is_string($attributeName)');
            assert('$attributeName != ""');
            assert("property_exists(\$this, '$attributeName') || \$this->isAttribute('$attributeName')");
            if (property_exists($this, $attributeName))
            {
                $this->$attributeName = $value;
            }
            elseif ($this->isAttribute($attributeName))
            {
                $bean = $this->attributeNameToBeanAndClassName[$attributeName][0];
                if (!$this->isRelation($attributeName))
                {
                    $columnName = strtolower($attributeName);
                    if ($bean->$columnName !== $value)
                    {
                        $bean->$columnName = $value;
                        return true;
                    }
                }
                else
                {
                    list($relationType, $relatedModelClassName, $owns, $relationPolyOneToManyName) =
                        $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName];
                    $relatedTableName = self::getTableName($relatedModelClassName);
                    $linkName = strtolower($attributeName);
                    if ($linkName == strtolower($relatedModelClassName))
                    {
                        $linkName = null;
                    }
                    switch ($relationType)
                    {
                        case self::HAS_MANY:
                        case self::MANY_MANY:
                            // The many sides of a relation cannot
                            // be assigned, they are changed by the using the
                            // RedBeanOneToManyRelatedModels or
                            // RedBeanManyToManyRelatedModels object
                            // on the 1 or other side of the relationship
                            // respectively.
                            throw new NotSupportedException();
                    }
                    // If the value is null we need to get the related model so that
                    // if there is none we can ignore the null and if there is one
                    // we can act on it.
                    if ($value === null                                         &&
                        !in_array($attributeName, $this->unlinkedRelationNames) &&
                        !isset($this->relationNameToRelatedModel[$attributeName]))
                    {
                        $this->unrestrictedGet($attributeName);
                    }
                    if (isset($this->relationNameToRelatedModel[$attributeName]) &&
                        $value !== null                                          &&
                        $this->relationNameToRelatedModel[$attributeName]->isSame($value))
                    {
                        // If there is a current related model and it is the same
                        // as the one being set then do nothing.
                    }
                    else
                    {
                        if (!in_array($attributeName, $this->unlinkedRelationNames) &&
                            isset($this->relationNameToRelatedModel[$attributeName]))
                        {
                            $this->unlinkedRelationNames[] = $attributeName;
                        }
                        if ($value === null)
                        {
                            unset($this->relationNameToRelatedModel[$attributeName]);
                        }
                        else
                        {
                            assert("\$value instanceof $relatedModelClassName");
                            $this->relationNameToRelatedModel[$attributeName] = $value;
                        }
                    }
                    return true;
                }
            }
            else
            {
                throw new NotSupportedException();
            }
            return false;
        }

        /**
         * Allows testing of the members and relations of the model as if
         * they were actual attributes of the model.
         */
        public function __isset($attributeName)
        {
            assert('is_string($attributeName)');
            assert('$attributeName != ""');
            return $this->isAttribute($attributeName) &&
                   $this->$attributeName !== null ||
                   !$this->isAttribute($attributeName) &&
                   isset($this->$attributeName);
        }

        /**
         * Allows unsetting of the members and relations of the model as if
         * they were actual attributes of the model.
         */
        public function __unset($attributeName)
        {
            assert('is_string($attributeName)');
            assert('$attributeName != ""');
            $this->$attributeName = null;
        }

        /**
         * Returns the member and relation names defined by the extending
         * class's getMetadata() method.
         */
        public function attributeNames()
        {
            return array_keys($this->attributeNameToBeanAndClassName);
        }

        /**
         * Returns true if the named attribute is one of the member or
         * relation names defined by the extending
         * class's getMetadata() method.
         */
        public function isAttribute($attributeName)
        {
            assert('is_string($attributeName)');
            assert('$attributeName != ""');
            return $attributeName == 'id' ||
                   array_key_exists($attributeName, $this->attributeNameToBeanAndClassName);
        }

        /**
         * Returns true if the attribute is read-only.
         */
        public function isAttributeReadOnly($attributeName)
        {
            assert("\$this->isAttribute(\"$attributeName\")");
            foreach ($this->validators as $validator)
            {
                if ($validator instanceof RedBeanModelReadOnlyValidator)
                {
                    if (in_array($attributeName, $validator->attributes, true))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /**
         * @param boolean $attributeName
         * @return true/false whether the attributeName specified, it is allowed to be set externally even though it is
         * a read-only attribute.
         */
        public function isAllowedToSetReadOnlyAttribute($attributeName)
        {
            return false;
        }

        /**
         * Given an attribute return the column name.
         * @param string $attributeName
         */
        public function getColumnNameByAttribute($attributeName)
        {
            assert('is_string($attributeName)');
            if ($this->isRelation($attributeName))
            {
                $modelClassName = get_class($this);
                $columnName = $modelClassName::getForeignKeyName($modelClassName, $attributeName);
            }
            else
            {
                $columnName = strtolower($attributeName);
            }
            return $columnName;
        }

        /**
         * This method is needed to interpret when the attributeName is 'id'.  Since id is not an attribute
         * on the model, we manaully check for this and return the appropriate class name.
         * @param string $attributeName
         * @return the model class name for the attribute.  This could be a casted up model class name.
         */
        public function resolveAttributeModelClassName($attributeName)
        {
            assert('is_string($attributeName)');
            if ($attributeName == 'id')
            {
                return get_class($this);
            }
            return $this->getAttributeModelClassName($attributeName);
        }

        /**
         * Returns the model class name for an
         * attribute name defined by the extending class's getMetadata() method.
         * For use by RedBeanModelDataProvider. Is unlikely to be of any
         * use to an application.
         */
        public function getAttributeModelClassName($attributeName)
        {
            assert("\$this->isAttribute(\"$attributeName\")");
            return $this->attributeNameToBeanAndClassName[$attributeName][1];
        }

        /**
         * Returns true if the named attribute is one of the
         * relation names defined by the extending
         * class's getMetadata() method.
         */
        public function isRelation($attributeName)
        {
            assert("\$this->isAttribute('$attributeName')");
            return array_key_exists($attributeName, $this->relationNameToRelationTypeModelClassNameAndOwns);
        }

        /**
         * Returns true if the named attribute is one of the
         * relation names defined by the extending
         * class's getMetadata() method, and specifies RedBeanModel::OWNED.
         */
        public function isOwnedRelation($attributeName)
        {
            assert("\$this->isAttribute('$attributeName')");
            return array_key_exists($attributeName, $this->relationNameToRelationTypeModelClassNameAndOwns) &&
                   $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][2];
        }

        /**
         * Returns the relation type
         * relation name defined by the extending class's getMetadata() method.
         */
        public function getRelationType($relationName)
        {
            assert("\$this->isRelation('$relationName')");
            return $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][0];
        }

        /**
         * Returns the model class name for a
         * relation name defined by the extending class's getMetadata() method.
         * For use by RedBeanModelDataProvider. Is unlikely to be of any
         * use to an application.
         */
        public function getRelationModelClassName($relationName)
        {
            assert("\$this->isRelation('$relationName')");
            return $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][1];
        }

        /**
         * See the yii documentation. Not used by RedBeanModel.
         * @see getMetadata()
         */
        public function rules()
        {
            throw new NotImplementedException();
        }

        /**
         * See the yii documentation.
         */
        public function behaviors()
        {
            return array();
        }

        /**
         * See the yii documentation.
         * RedBeanModels utilize untranslatedAttributeLabels to store any attribute information, which
         * can then be translated in this method.
         */
        public function attributeLabels()
        {
            $attributeLabels = array();
            foreach ($this->untranslatedAttributeLabels() as $attributeName => $label)
            {
                $attributeLabels[$attributeName] = Yii::t('Default', $label);
            }
            return $attributeLabels;
        }

        /**
         * Array of untranslated attribute labels.
         */
        protected function untranslatedAttributeLabels()
        {
            return array();
        }

        /**
         * Public for message checker only.
         */
        public function getUntranslatedAttributeLabels()
        {
            return $this->untranslatedAttributeLabels();
        }

        /**
         * See the yii documentation.
         * RedBeanModels utilize untranslatedAbbreviatedAttributeLabels to store any abbreviated attribute information, which
         * can then be translated in this method.
         */
        public function abbreviatedAttributeLabels()
        {
            $abbreviatedAttributeLabels = array();
            foreach ($this->untranslatedAbbreviatedAttributeLabels() as $attributeName => $label)
            {
                $abbreviatedAttributeLabels[$attributeName] = Yii::t('Default', $label);
            }
            return $abbreviatedAttributeLabels;
        }

        /**
         * Array of untranslated abbreviated attribute labels.
         */
        protected function untranslatedAbbreviatedAttributeLabels()
        {
            return array();
        }

        /**
         * Public for message checker only.
         */
        public function getUntranslatedAbbreviatedAttributeLabels()
        {
            return $this->untranslatedAbbreviatedAttributeLabels();
        }

        /**
         * Performs validation using the validators specified in the 'rules'
         * meta data by the extending class's getMetadata() method.
         * Validation occurs on a new model or a modified model, but only
         * proceeds to modified related models. Once validated a model
         * will pass validation without revalidating until it is modified.
         * Related models are only validated if the model validates.
         * Cyclic relationships are prevented from causing problems by the
         * validation either stopping at a non-validating model and only
         * proceeding to non-validated models.
         * @see RedBeanModel
         * @param $ignoreRequiredValidator - set to true in scenarios where you want to validate everything but the
         *                                   the required validator.  An example is a search form.
         */
        public function validate(array $attributeNames = null, $ignoreRequiredValidator = false)
        {
            if ($this->isValidating) // Prevent cycles.
            {
                return true;
            }
            $this->isValidating = true;
            try
            {
                $this->clearErrors();
                if ($this->beforeValidate())
                {
                    $hasErrors = false;
                    if ($attributeNames === null)
                    {
                        $attributeNames = $this->attributeNamesNotBelongsToOrManyMany;
                    }
                    foreach ($this->getValidators() as $validator)
                    {
                        if ($validator instanceof RedBeanModelRequiredValidator && $validator->applyTo($this->scenarioName))
                        {
                            if (!$ignoreRequiredValidator)
                            {
                                $validator->validate($this, $attributeNames);
                            }
                        }
                        elseif (!$validator instanceof CDefaultValueValidator && $validator->applyTo($this->scenarioName))
                        {
                            $validator->validate($this, $attributeNames);
                        }
                    }
                    $relatedModelsHaveErrors = false;
                    foreach ($this->relationNameToRelatedModel as $relationName => $relatedModel)
                    {
                        if ((!$this->$relationName instanceof RedBeanModel) ||
                             !$this->$relationName->isSame($this))
                        {
                            if (in_array($relationName, $attributeNames) &&
                                ($this->$relationName->isModified() ||
                                     ($this->isAttributeRequired($relationName) && !$ignoreRequiredValidator) &&
                                     !$this->isSame($this->$relationName))) // Prevent cycles.
                            {
                                if (!$this->$relationName->validate(null, $ignoreRequiredValidator))
                                {
                                    $hasErrors = true;
                                }
                            }
                        }
                    }
                    $this->afterValidate();
                    $hasErrors = $hasErrors || count($this->attributeNameToErrors) > 0;
                    // Put these asserts back if there are suspitions about validate/hasErrors/getErrors
                    // producing inconsistent results. But for now it is commented out because
                    // it makes too big an impact.
                    //assert('$hasErrors == (count($this->getErrors()) > 0)');
                    //assert('$hasErrors == $this->hasErrors()');
                    $this->isValidating = false;
                    return !$hasErrors;
                }
                $this->isValidating = false;
                return false;
            }
            catch (Exception $e)
            {
                $this->isValidating = false;
                throw $e;
            }
        }

        /**
         * See the yii documentation.
         */
        protected function beforeValidate()
        {
            $event = new CModelEvent($this);
            $this->onBeforeValidate($event);
            return $event->isValid;
        }

        /**
         * See the yii documentation.
         */
        protected function afterValidate()
        {
            $this->onAfterValidate(new CEvent($this));
        }

        /**
         * See the yii documentation.
         */
        public function onBeforeValidate(CModelEvent $event)
        {
            $this->raiseEvent('onBeforeValidate', $event);
        }

        /**
         * See the yii documentation.
         */
        public function onAfterValidate($event)
        {
            $this->raiseEvent('onAfterValidate', $event);
        }

        /**
         * See the yii documentation.
         */
        public function getValidatorList()
        {
            return $this->validators;
        }

        /**
         * See the yii documentation.
         */
        public function getValidators($attributeName = null)
        {
            assert("\$attributeName === null || \$this->isAttribute('$attributeName')");
            $validators = array();
            $scenarioName = $this->scenarioName;
            foreach ($this->validators as $validator)
            {
                if ($scenarioName === null || $validator->applyTo($scenarioName))
                {
                    if ($attributeName === null || in_array($attributeName, $validator->attributes, true))
                    {
                        $validators[] = $validator;
                    }
                }
            }
            return $validators;
        }

        /**
         * See the yii documentation.
         */
        public function createValidators()
        {
            throw new NotImplementedException();
        }

        /**
         * Returns true if the attribute value does not already exist in
         * the database. This is used in the unique validator, but on saving
         * RedBean can still throw because the unique constraint on the column
         * has been violated because it was concurrently updated between the
         * Yii validator being called and the save actually occuring.
         */
        public function isUniqueAttributeValue($attributeName, $value)
        {
            assert("\$this->isAttribute('$attributeName')");
            assert('$value !== null');
            if (!$this->isRelation($attributeName))
            {
                $modelClassName = $this->attributeNameToBeanAndClassName[$attributeName][1];
                $tableName = self::getTableName($modelClassName);
                $rows = R::getAll('select id from ' . $tableName . " where $attributeName = ?", array($value));
                return count($rows) == 0 || count($rows) == 1 && $rows[0]['id'] == $this->id;
            }
            else
            {
                $model = $this->$attributeName;
                if ($model->id == 0)
                {
                    return true;
                }
                $modelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][1];
                $tableName = self::getTableName($modelClassName);
                $rows = R::getAll('select id from ' . $tableName . ' where id = ?', array($model->id));
                return count($rows) == 0 || count($rows) == 1 && $rows[0]['id'] == $this->id;
            }
        }

        /**
         * Saves the model to the database. Models are only saved if they have been
         * modified and related models are saved before this model. If a related model
         * is modified and needs saving the deems the model to be modified and need
         * saving, which ensures that keys are updated.
         * Cyclic relationships are prevented from causing problems by the
         * save only proceeding to non-saved models.
         */
        public function save($runValidation = true, array $attributeNames = null)
        {
            if ($attributeNames !== null)
            {
                throw new NotSupportedException();
            }
            if ($this->isSaving) // Prevent cycles.
            {
                return true;
            }
            $this->isSaving = true;
            try
            {
                if (!$runValidation || $this->validate())
                {
                    if ($this->beforeSave())
                    {
                        $beans = array_values($this->modelClassNameToBean);
                        $this->linkBeans();
                        // The breakLink/link is deferred until the save to avoid
                        // disconnecting or creating an empty row if the model was
                        // never actually saved.
                        foreach ($this->unlinkedRelationNames as $key => $relationName)
                        {
                            $bean                      = $this->attributeNameToBeanAndClassName                [$relationName][0];
                            $relatedModelClassName     = $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][1];
                            $tempRelatedModelClassName = $relatedModelClassName;
                            self::resolveModelClassNameForClassesWithoutBeans($tempRelatedModelClassName);
                            $relatedTableName          = self::getTableName($tempRelatedModelClassName);
                            $linkName = strtolower($relationName);
                            if ($linkName == strtolower($relatedModelClassName))
                            {
                                $linkName = null;
                            }
                            ZurmoRedBeanLinkManager::breakLink($bean, $relatedTableName, $linkName);
                            unset($this->unlinkedRelationNames[$key]);
                        }
                        assert('count($this->unlinkedRelationNames) == 0');
                        foreach ($this->relationNameToRelatedModel as $relationName => $relatedModel)
                        {
                            $relationType = $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][0];
                            if (!in_array($relationType, array(self::HAS_ONE_BELONGS_TO,
                                                               self::HAS_MANY_BELONGS_TO)))
                            {
                                if ($relatedModel->isModified() ||
                                    ($this->isAttributeRequired($relationName)))
                                {
                                    //If the attribute is required, but already exists and has not been modified we do
                                    //not have to worry about saving it.
                                    if ($this->isSavableFromRelation &&
                                       !($this->isAttributeRequired($relationName) &&
                                         !$relatedModel->isModified() &&
                                         $relatedModel->id > 0))
                                    {
                                        if (!$relatedModel->save(false))
                                        {
                                            $this->isSaving = false;
                                            return false;
                                        }
                                    }
                                    elseif ($relatedModel->isModified())
                                    {
                                        throw new NotSuportedException();
                                    }
                                }
                            }
                            if ($relatedModel instanceof RedBeanModel)
                            {
                                $bean                  = $this->attributeNameToBeanAndClassName                [$relationName][0];
                                $relatedModelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][1];
                                $linkName = strtolower($relationName);
                                if (strtolower($linkName) == strtolower($relatedModelClassName))
                                {
                                    $linkName = null;
                                }
                                elseif ($relationType == RedBeanModel::HAS_MANY_BELONGS_TO ||
                                        $relationType == RedBeanModel::HAS_ONE_BELONGS_TO)
                                {
                                    $label = 'Relations of type HAS_MANY_BELONGS_TO OR HAS_ONE_BELONGS_TO must have the relation name ' .
                                             'the same as the related model class name. Relation: {relationName} ' .
                                             'Relation model class name: {relationModelClassName}';
                                    throw new NotSupportedException(Yii::t('Default', $label,
                                              array('{relationName}' => $linkName,
                                                    '{relationModelClassName}' => $relatedModelClassName)));
                                }
                                //Needed to exclude HAS_ONE_BELONGS_TO because an additional column was being created
                                //on the wrong side.
                                if ($relationType != RedBeanModel::HAS_ONE_BELONGS_TO && ($relatedModel->isModified() ||
                                    $relatedModel->id > 0       ||
                                    $this->isAttributeRequired($relationName)))
                                {
                                    $relatedModel = $this->relationNameToRelatedModel[$relationName];
                                    $relatedBean  = $relatedModel->getClassBean($relatedModelClassName);
                                    ZurmoRedBeanLinkManager::link($bean, $relatedBean, $linkName);

                                    if (!RedBeanDatabase::isFrozen())
                                    {
                                        $tableName  = self::getTableName($this->getAttributeModelClassName($relationName));
                                        $columnName = self::getForeignKeyName(get_class($this), $relationName);
                                        RedBeanColumnTypeOptimizer::optimize($tableName, $columnName, 'id');
                                    }
                                }
                            }
                        }
                        $baseModelClassName = null;
                        foreach ($this->modelClassNameToBean as $modelClassName => $bean)
                        {
                            R::store($bean);
                            assert('$bean->id > 0');
                            if (!RedBeanDatabase::isFrozen())
                            {
                                static::resolveMixinsOnSaveForEnsuringColumnsAreCorrectlyFormed($baseModelClassName,
                                                                                                $modelClassName);
                                $baseModelClassName = $modelClassName;
                            }
                        }
                        $this->modified = false;
                        $this->afterSave();
                        RedBeanModelsCache::cacheModel($this);
                        $this->isSaving = false;
                        return true;
                    }
                }
                $this->isSaving = false;
                return false;
            }
            catch (Exception $e)
            {
                $this->isSaving = false;
                throw $e;
            }
        }

        /**
         * Resolve that the id columns are properly formed as integers.
         * @param string or null $baseModelClassName
         * @param string $modelClassName
         */
        protected static function resolveMixinsOnSaveForEnsuringColumnsAreCorrectlyFormed($baseModelClassName, $modelClassName)
        {
            assert('$baseModelClassName == null || is_string($baseModelClassName)');
            assert('is_string($modelClassName)');
            if ($baseModelClassName !== null)
            {
                $tableName  = self::getTableName($modelClassName);
                $columnName = self::getTableName($baseModelClassName) . '_id';
                RedBeanColumnTypeOptimizer::optimize($tableName, $columnName, 'id');
            }
        }

        /**
         * This method is invoked before saving a record (after validation, if any).
         * The default implementation raises the {@link onBeforeSave} event.
         * You may override this method to do any preparation work for record saving.
         * Use {@link isNewModel} to determine whether the saving is
         * for inserting or updating record.
         * Make sure you call the parent implementation so that the event is raised properly.
         * @return boolean whether the saving should be executed. Defaults to true.
         */
        protected function beforeSave()
        {
            if ($this->hasEventHandler('onBeforeSave'))
            {
                $event = new CModelEvent($this);
                $this->onBeforeSave($event);
                return $event->isValid;
            }
            else
            {
                return true;
            }
        }

        protected function afterSave()
        {
            $event = new CEvent($this);
            $this->onAfterSave($event);
        }

        /**
         * This event is raised before the record is saved.
         * By setting {@link CModelEvent::isValid} to be false, the normal {@link save()} process will be stopped.
         * @param CModelEvent $event the event parameter
         * @since 1.0.2
         */
        public function onBeforeSave($event)
        {
            $this->raiseEvent('onBeforeSave', $event);
        }

        /**
         * This event is raised after the record is saved.
         * @param CEvent $event the event parameter
         * @since 1.0.2
         */
        public function onAfterSave($event)
        {
            $this->raiseEvent('onAfterSave', $event);
        }

        /**
         * This event is raised before the record is deleted.
         * By setting {@link CModelEvent::isValid} to be false, the normal {@link delete()} process will be stopped.
         * @param CModelEvent $event the event parameter
         * @since 1.0.2
         */
        public function onBeforeDelete($event)
        {
            $this->raiseEvent('onBeforeDelete', $event);
        }

        /**
         * This event is raised after the record is deleted.
         * @param CEvent $event the event parameter
         * @since 1.0.2
         */
        public function onAfterDelete($event)
        {
            $this->raiseEvent('onAfterDelete', $event);
        }

        protected function linkBeans()
        {
            $baseModelClassName = null;
            $baseBean = null;
            foreach ($this->modelClassNameToBean as $modelClassName => $bean)
            {
                if ($baseBean !== null)
                {
                    ZurmoRedBeanLinkManager::link($bean, $baseBean);
                    if (!RedBeanDatabase::isFrozen())
                    {
                        $tableName  = self::getTableName($modelClassName);
                        $columnName = self::getTableName($baseModelClassName) . '_id';
                        RedBeanColumnTypeOptimizer::optimize($tableName, $columnName, 'id');
                    }
                }
                $baseModelClassName = $modelClassName;
                $baseBean = $bean;
            }
        }

        /**
         * Returns true if the model has been modified since it was saved
         * or constructed.
         */
        public function isModified()
        {
            if ($this->modified)
            {
                return true;
            }
            if ($this->isInIsModified) // Prevent cycles.
            {
                return false;
            }
            $this->isInIsModified = true;
            try
            {
                foreach ($this->relationNameToRelatedModel as $relationName => $relatedModel)
                {
                    if ((!$this->$relationName instanceof RedBeanModel) ||
                        !$this->$relationName->isSame($this))
                    {
                        if (!in_array($this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][0],
                                      array(self::HAS_ONE_BELONGS_TO,
                                            self::HAS_MANY_BELONGS_TO,
                                            self::MANY_MANY)))
                        {
                            if ($this->$relationName->isModified() ||
                                $this->isAttributeRequired($relationName) &&
                                $this->$relationName->id <= 0)
                            {
                                $this->isInIsModified = false;
                                return true;
                            }
                        }
                    }
                }
                $this->isInIsModified = false;
                return false;
            }
            catch (Exception $e)
            {
                $this->isInIsModified = false;
                throw $e;
            }
        }

        /**
         * Deletes the model from the database.
         */
        public function delete()
        {
            if ($this->id < 0)
            {
                // If the model was never saved
                // then it doesn't need to be deleted.
                return false;
            }
            $modelClassName = get_called_class();
            if (!$modelClassName::isTypeDeletable() ||
                !$this->isDeletable())
            {
                // See comments below on isDeletable.
                throw new NotSupportedException();
            }
            if ($this->beforeDelete())
            {
                $deleted = $this->unrestrictedDelete();
                $this->afterDelete();
                return $deleted;
            }
            else
            {
                return false;
            }
        }

        /**
         * This method is invoked before deleting a record.
         * The default implementation raises the {@link onBeforeDelete} event.
         * You may override this method to do any preparation work for record deletion.
         * Make sure you call the parent implementation so that the event is raised properly.
         * @return boolean whether the record should be deleted. Defaults to true.
         */
        protected function beforeDelete()
        {
            if ($this->hasEventHandler('onBeforeDelete'))
            {
                $event = new CModelEvent($this);
                $this->onBeforeDelete($event);
                return $event->isValid;
            }
            else
            {
                return true;
            }
        }

        /**
         * This method is invoked after deleting a record.
         * The default implementation raises the {@link onAfterDelete} event.
         * You may override this method to do postprocessing after the record is deleted.
         * Make sure you call the parent implementation so that the event is raised properly.
         */
        protected function afterDelete()
        {
            if ($this->hasEventHandler('onAfterDelete'))
            {
                $this->onAfterDelete(new CEvent($this));
            }
        }

        protected function unrestrictedDelete()
        {
            $this->forget();
            // RedBeanModel only supports cascaded deletes on associations,
            // not on links. So for now at least they are done the slow way.
            foreach (RuntimeUtil::getClassHierarchy(get_class($this), static::$lastClassInBeanHeirarchy) as $modelClassName)
            {
                if ($modelClassName::getCanHaveBean())
                {
                    $this->deleteOwnedRelatedModels  ($modelClassName);
                    $this->deleteForeignRelatedModels($modelClassName);
                    $this->deleteManyManyRelations ($modelClassName);
                }
            }
            foreach ($this->modelClassNameToBean as $modelClassName => $bean)
            {
                R::trash($bean);
            }
            // The model cannot be used anymore.
            $this->deleted = true;
            return true;
        }

        public function isDeleted()
        {
            return $this->deleted;
        }

        protected function deleteOwnedRelatedModels($modelClassName)
        {
            foreach ($this->relationNameToRelationTypeModelClassNameAndOwns as $relationName => $relationTypeModelClassNameAndOwns)
            {
                assert('count($relationTypeModelClassNameAndOwns) == 3 || count($relationTypeModelClassNameAndOwns) == 4');
                $relationType = $relationTypeModelClassNameAndOwns[0];
                $owns         = $relationTypeModelClassNameAndOwns[2];
                if ($owns)
                {
                    if ((!$this->$relationName instanceof RedBeanModel) ||
                        !$this->$relationName->isSame($this))
                    {
                        assert('in_array($relationType, array(self::HAS_ONE, self::HAS_MANY))');
                        if ($relationType == self::HAS_ONE)
                        {
                            if ($this->$relationName->id > 0)
                            {
                                $this->$relationName->unrestrictedDelete();
                            }
                        }
                        else
                        {
                            foreach ($this->$relationName as $model)
                            {
                                $model->unrestrictedDelete();
                            }
                        }
                    }
                }
            }
        }

        protected function deleteForeignRelatedModels($modelClassName)
        {
            $metadata = $this->getMetadata();
            if (isset($metadata[$modelClassName]['foreignRelations']))
            {
                foreach ($metadata[$modelClassName]['foreignRelations'] as $relatedModelClassName)
                {
                    $relatedModels = $relatedModelClassName::
                                        getByRelatedClassId($relatedModelClassName,
                                                            $this->getClassId($modelClassName),
                                                            $modelClassName);
                    foreach ($relatedModels as $relatedModel)
                    {
                        $relatedModel->unrestrictedDelete();
                    }
                }
            }
        }

        protected static function getByRelatedClassId($relatedModelClassName, $id, $modelClassName = null)
        {
            assert('is_string($relatedModelClassName)');
            assert('$relatedModelClassName != ""');
            assert('is_int($id)');
            assert('$id > 0');
            assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
            if ($modelClassName === null)
            {
                $modelClassName = get_called_class();
            }
            $tableName = self::getTableName($relatedModelClassName);
            $foreignKeyName = strtolower($modelClassName) . '_id';
            $beans = R::find($tableName, "$foreignKeyName = $id");
            return self::makeModels($beans, $relatedModelClassName);
        }

        protected function deleteManyManyRelations($modelClassName)
        {
            $metadata = $this->getMetadata();
            if (isset($metadata[$modelClassName]['relations']))
            {
                foreach ($metadata[$modelClassName]['relations'] as $relationName => $relationTypeModelClassNameAndOwns)
                {
                    assert('in_array(count($relationTypeModelClassNameAndOwns), array(2, 3, 4))');
                    $relationType           = $relationTypeModelClassNameAndOwns[0];
                    if ($relationType == self::MANY_MANY)
                    {
                        $this->{$relationName}->removeAll();
                        $this->{$relationName}->save();
                    }
                }
            }
        }

        /**
         * To be overriden on intermediate derived classes
         * to return false so that deletes are not done on
         * intermediate classes because the object relational
         * mapping will not clean up properly.
         * For example if User is a Person, and Person is
         * a RedBeanModel delete should be called only on User,
         * not on Person. So User must override isDeletable
         * to return false.
         */
        public static function isTypeDeletable()
        {
            return true;
        }

        /**
         * To be overridden by derived classes to prevent
         * deletion.
         */
        public function isDeletable()
        {
            return true;
        }

        /**
         * Forgets about all of the objects so that when they are retrieved
         * again they will be recreated from the database. For use in testing.
         */
        public static function forgetAll()
        {
            RedBeanModelsCache::forgetAll();
            RedBeansCache::forgetAll();
        }

        /**
         * Forgets about the object so that if it is retrieved
         * again it will be recreated from the database. For use in testing.
         */
        public function forget()
        {
            RedBeanModelsCache::forgetModel($this);
            RedBeansCache::forgetBean(self::getTableName(get_called_class()) . $this->id);
        }

        /**
         * See the yii documentation.
         */
        public function isAttributeRequired($attributeName)
        {
            assert("\$this->isAttribute('$attributeName')");
            foreach ($this->getValidators($attributeName) as $validator)
            {
                if ($validator instanceof CRequiredValidator)
                {
                    return true;
                }
            }
            return false;
        }

        /**
         * See the yii documentation.
         */
        public function isAttributeSafe($attributeName)
        {
            $attributeNames = $this->getSafeAttributeNames();
            return in_array($attributeName, $attributeNames);
        }

        public static function getModelLabelByTypeAndLanguage($type, $language = null)
        {
            assert('in_array($type, array("Singular", "SingularLowerCase", "Plural", "PluralLowerCase"))');
            if ($type == 'Singular')
            {
               return Yii::t('Default', static::getLabel(),
                        LabelUtil::getTranslationParamsForAllModules(), null, $language);
            }
            if ($type == 'SingularLowerCase')
            {
               return strtolower(Yii::t('Default', static::getLabel(),
                        LabelUtil::getTranslationParamsForAllModules(), null, $language));
            }
            if ($type == 'Plural')
            {
               return Yii::t('Default', static::getPluralLabel(),
                        LabelUtil::getTranslationParamsForAllModules(), null, $language);
            }
            if ($type == 'PluralLowerCase')
            {
               return strtolower(Yii::t('Default', static::getPluralLabel(),
                        LabelUtil::getTranslationParamsForAllModules(), null, $language));
            }
        }

        protected static function getLabel()
        {
            return get_called_class();
        }

        protected static function getPluralLabel()
        {
            return static::getLabel() . 's';
        }

        /**
         * See the yii documentation.
         */
        public function getAbbreviatedAttributeLabel($attributeName)
        {
            return $this->getAbbreviatedAttributeLabelByLanguage($attributeName, Yii::app()->language);
        }

        /**
         * Given an attributeName and a language, retrieve the translated attribute label. Attempts to find a customized
         * label in the metadata first, before falling back on the standard attribute label for the specified attribute.
         * @return string - translated attribute label
         */
        protected function getAbbreviatedAttributeLabelByLanguage($attributeName, $language)
        {
            assert('is_string($attributeName)');
            assert('is_string($language)');
            $labels = $this->untranslatedAbbreviatedAttributeLabels();
            if (isset($labels[$attributeName]))
            {
                return ZurmoHtml::tag('span', array('title' => $this->generateAttributeLabel($attributeName)),
                                  Yii::t('Default', $labels[$attributeName],
                                  LabelUtil::getTranslationParamsForAllModules(), null, $language));
            }
            else
            {
                return null;
            }
        }

        /**
         * See the yii documentation.
         */
        public function getAttributeLabel($attributeName)
        {
            return $this->getAttributeLabelByLanguage($attributeName, Yii::app()->language);
        }

        /**
         * Given an attributeName and a language, retrieve the translated attribute label. Attempts to find a customized
         * label in the metadata first, before falling back on the standard attribute label for the specified attribute.
         * @return string - translated attribute label
         */
        protected function getAttributeLabelByLanguage($attributeName, $language)
        {
            assert('is_string($attributeName)');
            assert('is_string($language)');
            $labels       = $this->untranslatedAttributeLabels();
            $customLabel  = $this->getTranslatedCustomAttributeLabelByLanguage($attributeName, $language);
            if ($customLabel != null)
            {
                return $customLabel;
            }
            elseif (isset($labels[$attributeName]))
            {
                return Yii::t('Default', $labels[$attributeName],
                              LabelUtil::getTranslationParamsForAllModules(), null, $language);
            }
            else
            {
                //should do a T:: wrapper here too.
                return Yii::t('Default', $this->generateAttributeLabel($attributeName), array(), null, $language);
            }
        }

        /**
         * Given an attributeName, attempt to find in the metadata a custom attribute label for the given language.
         * @return string - translated attribute label, if not found return null.
         */
        protected function getTranslatedCustomAttributeLabelByLanguage($attributeName, $language)
        {
            assert('is_string($attributeName)');
            assert('is_string($language)');
            $metadata = $this->getMetadata();
            foreach ($metadata as $modelClassName => $modelClassMetadata)
            {
                if (isset($modelClassMetadata['labels']) &&
                    isset($modelClassMetadata['labels'][$attributeName]) &&
                    isset($modelClassMetadata['labels'][$attributeName][$language]))
                {
                    return $modelClassMetadata['labels'][$attributeName][$language];
                }
            }
            return null;
        }

        /**
         * Given an attributeName, return an array of all attribute labels for each language available.
         * @return array - attribute labels by language for the given attributeName.
         */
        public function getAttributeLabelsForAllSupportedLanguagesByAttributeName($attributeName)
        {
            assert('is_string($attributeName)');
            $attirbuteLabelData = array();
            foreach (Yii::app()->languageHelper->getSupportedLanguagesData() as $language => $name)
            {
                $attirbuteLabelData[$language] = $this->getAttributeLabelByLanguage($attributeName, $language);
            }
            return $attirbuteLabelData;
        }

        /**
         * See the yii documentation. The yii hasErrors() takes an optional
         * attribute name. RedBeanModel's hasErrors() takes an optional attribute
         * name or array of attribute names. See getErrors() for an explanation
         * of this difference.
         */
        public function hasErrors($attributeNameOrNames = null)
        {
            assert('$attributeNameOrNames === null   || ' .
                   'is_string($attributeNameOrNames) || ' .
                   'is_array ($attributeNameOrNames) && AssertUtil::all($attributeNameOrNames, "is_string")');
            if ($this->isInHasErrors) // Prevent cycles.
            {
                return false;
            }
            $this->isInHasErrors = true;
            try
            {
                if (is_string($attributeNameOrNames))
                {
                    $attributeName = $attributeNameOrNames;
                    $relatedAttributeNames = null;
                }
                elseif (is_array($attributeNameOrNames))
                {
                    $attributeName = $attributeNameOrNames[0];
                    if (count($attributeNameOrNames) > 1)
                    {
                        $relatedAttributeNames = array_slice($attributeNameOrNames, 1);
                    }
                    else
                    {
                        $relatedAttributeNames = null;
                    }
                }
                else
                {
                    $attributeName         = null;
                    $relatedAttributeNames = null;
                }
                assert("\$attributeName        === null || is_string('$attributeName')");
                assert('$relatedAttributeNames === null || is_array($relatedAttributeNames)');
                assert('!($attributeName === null && $relatedAttributeNames !== null)');
                if ($attributeName === null)
                {
                    if (count($this->attributeNameToErrors) > 0)
                    {
                        $this->isInHasErrors = false;
                        return true;
                    }
                    foreach ($this->relationNameToRelatedModel as $relationName => $relatedModelOrModels)
                    {
                        if ((!$this->$relationName instanceof RedBeanModel) ||
                             !$this->$relationName->isSame($this))
                        {
                            if (in_array($relationName, $this->attributeNamesNotBelongsToOrManyMany))
                            {
                                if ($relatedModelOrModels->hasErrors($relatedAttributeNames))
                                {
                                    $this->isInHasErrors = false;
                                    return true;
                                }
                            }
                        }
                    }
                    $this->isInHasErrors = false;
                    return false;
                }
                else
                {
                    if (!$this->isRelation($attributeName))
                    {
                        $this->isInHasErrors = false;
                        return array_key_exists($attributeName, $this->attributeNameToErrors);
                    }
                    else
                    {
                        if (in_array($attributeName, $this->attributeNamesNotBelongsToOrManyMany))
                        {
                            $this->isInHasErrors = false;
                            return isset($this->relationNameToRelatedModel[$attributeName]) &&
                                   count($this->relationNameToRelatedModel[$attributeName]->getErrors($relatedAttributeNames)) > 0;
                        }
                    }
                }
                $this->isInHasErrors = false;
                return false;
            }
            catch (Exception $e)
            {
                $this->isInHasErrors = false;
                throw $e;
            }
        }

        /**
         * See the yii documentation. The yii getErrors() takes an optional
         * attribute name. RedBeanModel's getErrors() takes an optional attribute
         * name or array of attribute names.
         * @param @attributeNameOrNames Either null, return all errors on the
         * model and its related models, an attribute name on the model, return
         * errors on that attribute, or an array of relation and attribute names,
         * return errors on a related model's attribute.

         */
        public function getErrors($attributeNameOrNames = null)
        {
            assert('$attributeNameOrNames === null   || ' .
                   'is_string($attributeNameOrNames) || ' .
                   'is_array ($attributeNameOrNames) && AssertUtil::all($attributeNameOrNames, "is_string")');
            if ($this->isInGetErrors) // Prevent cycles.
            {
                return array();
            }
            $this->isInGetErrors = true;
            try
            {
                if (is_string($attributeNameOrNames))
                {
                    $attributeName = $attributeNameOrNames;
                    $relatedAttributeNames = null;
                }
                elseif (is_array($attributeNameOrNames))
                {
                    $attributeName = $attributeNameOrNames[0];
                    if (count($attributeNameOrNames) > 1)
                    {
                        $relatedAttributeNames = array_slice($attributeNameOrNames, 1);
                    }
                    else
                    {
                        $relatedAttributeNames = null;
                    }
                }
                else
                {
                    $attributeName         = null;
                    $relatedAttributeNames = null;
                }
                assert("\$attributeName        === null || is_string('$attributeName')");
                assert('$relatedAttributeNames === null || is_array($relatedAttributeNames)');
                assert('!($attributeName === null && $relatedAttributeNames !== null)');
                if ($attributeName === null)
                {
                    $errors = $this->attributeNameToErrors;
                    foreach ($this->relationNameToRelatedModel as $relationName => $relatedModelOrModels)
                    {
                        if ((!$this->$relationName instanceof RedBeanModel) ||
                            !$this->$relationName->isSame($this))
                        {
                            if (!in_array($this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][0],
                                          array(self::HAS_ONE_BELONGS_TO,
                                                self::HAS_MANY_BELONGS_TO,
                                                self::MANY_MANY)))
                            {
                                $relatedErrors = $relatedModelOrModels->getErrors($relatedAttributeNames);
                                if (count($relatedErrors) > 0)
                                {
                                   $errors[$relationName] = $relatedErrors;
                                }
                            }
                        }
                    }
                    $this->isInGetErrors = false;
                    return $errors;
                }
                else
                {
                    if (isset($this->attributeNameToErrors[$attributeName]))
                    {
                        $this->isInGetErrors = false;
                        return  $this->attributeNameToErrors[$attributeName];
                    }
                    elseif (isset($this->relationNameToRelatedModel[$attributeName]))
                    {
                        if (!in_array($this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][0],
                                      array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO)))
                        {
                            $this->isInGetErrors = false;
                            return $this->relationNameToRelatedModel[$attributeName]->getErrors($relatedAttributeNames);
                        }
                    }
                }
                $this->isInGetErrors = false;
                return array();
            }
            catch (Exception $e)
            {
                $this->isInGetErrors = false;
                throw $e;
            }
        }

        /**
         * See the yii documentation.
         */
        public function getError($attributeName)
        {
            assert("\$this->isAttribute('$attributeName')");
            return isset($this->attributeNameToErrors[$attributeName]) ? reset($this->attributeNameToErrors[$attributeName]) : null;
        }

        /**
         * See the yii documentation.
         */
        public function addError($attributeName, $errorMessage)
        {
            assert("\$this->isAttribute('$attributeName')");
            if (!isset($this->attributeNameToErrors[$attributeName]))
            {
                $this->attributeNameToErrors[$attributeName] = array();
            }
            $this->attributeNameToErrors[$attributeName][] = $errorMessage;
        }

        /**
         * See the yii documentation.
         */
        public function addErrors(array $errors)
        {
            foreach ($errors as $attributeName => $error)
            {
                assert("\$this->isAttribute('$attributeName')");
                assert('is_array($error) || is_string($error)');
                if (is_array($error))
                {
                    if (!isset($this->attributeNameToErrors[$attributeName]))
                    {
                        $this->attributeNameToErrors[$attributeName] = array();
                    }
                    $this->attributeNameToErrors[$attributeName] =
                            array_merge($this->attributeNameToErrors[$attributeName], $error);
                }
                else
                {
                    $this->attributeNameToErrors[$attributeName][] = $error;
                }
            }
        }

        /**
         * See the yii documentation.
         */
        public function clearErrors($attributeName = null)
        {
            assert("\$attributeName === null || \$this->isAttribute('$attributeName')");
            if ($attributeName === null)
            {
                $this->attributeNameToErrors = array();
            }
            else
            {
                unset($this->attributeNameToErrors[$attributeName]);
            }
        }

        /**
         * See the yii documentation.
         */
        public function generateAttributeLabel($attributeName)
        {
            assert("\$this->isAttribute('$attributeName')");
            return ucfirst(preg_replace('/([A-Z0-9])/', ' \1', $attributeName));
        }

        /**
         * See the yii documentation.
         */
        public function getAttributes(array $attributeNames = null)
        {
            $values = array();
            if (is_array($attributeNames))
            {
                $values2 = array();
                $allModelAttributeNames = $this->attributeNames();
                foreach ($attributeNames as $attributeName)
                {
                    if (in_array($attributeName, $allModelAttributeNames))
                    {
                        $values2[$attributeName] = $this->$attributeName;
                    }
                }
                return $values2;
            }
            else
            {
                foreach ($this->attributeNames() as $attributeName)
                {
                    $values[$attributeName] = $this->$attributeName;
                }
                return $values;
            }
        }

        /**
         * See the yii documentation.
         */
        public function setAttributes(array $values, $safeOnly = true)
        {
            assert('is_bool($safeOnly)');
            $attributeNames = array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
            foreach ($values as $attributeName => $value)
            {
                if ($value !== null)
                {
                    if (!is_array($value))
                    {
                        assert('$attributeName != "id"');
                        if ($attributeName != 'id' && $this->isAttribute($attributeName))
                        {
                            if ($this->isAttributeSafe($attributeName) || !$safeOnly)
                            {
                                $this->$attributeName = $value;
                            }
                            else
                            {
                                $this->onUnsafeAttribute($attributeName, $value);
                            }
                        }
                    }
                    else
                    {
                        if ($this->isRelation($attributeName))
                        {
                            if (count($value) == 1 && array_key_exists('id', $value))
                            {
                                if (empty($value['id']))
                                {
                                    $this->$attributeName = null;
                                }
                                else
                                {
                                    $relatedModelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][1];
                                    $this->$attributeName  = $relatedModelClassName::getById(intval($value['id']), $relatedModelClassName);
                                }
                            }
                            else
                            {
                                $setAttributeMethodName = 'set' . ucfirst($attributeName);
                                if ($this->$attributeName instanceof RedBeanOneToManyRelatedModels &&
                                   method_exists($this, $setAttributeMethodName))
                                {
                                    $this->$setAttributeMethodName($value);
                                }
                                else
                                {
                                    $this->$attributeName->setAttributes($value);
                                }
                            }
                        }
                    }
                }
            }
        }

        /**
         * See the yii documentation.
         */
        public function unsetAttributes($attributeNames = null)
        {
            if ($attributeNames === null)
            {
                $attributeNames = $this->attributeNames();
            }
            foreach ($attributeNames as $attributeName)
            {
                $this->$attributeNames = null;
            }
        }

        /**
         * See the yii documentation.
         */
        public function onUnsafeAttribute($name, $value)
        {
            if (YII_DEBUG)
            {
                Yii::log(Yii::t('yii', 'Failed to set unsafe attribute "{attribute}".', array('{attribute}' => $name)), CLogger::LEVEL_WARNING);
            }
        }

        /**
         * See the yii documentation.
         */
        public function getScenario()
        {
            return $this->scenarioName;
        }

        /**
         * See the yii documentation.
         */
        public function setScenario($scenarioName)
        {
            assert('is_string($scenarioName)');
            $this->scenarioName = $scenarioName;
        }

        /**
         * See the yii documentation.
         */
        public function getSafeAttributeNames()
        {
            $attributeNamesToIsSafe = array();
            $unsafeAttributeNames   = array();
            foreach ($this->getValidators() as $validator)
            {
                if (!$validator->safe)
                {
                    foreach ($validator->attributes as $attributeName)
                    {
                        $unsafeAttributeNames[] = $attributeName;
                    }
                }
                else
                {
                    foreach ($validator->attributes as $attributeName)
                    {
                        $attributeNamesToIsSafe[$attributeName] = true;
                    }
                }
            }
            foreach ($unsafeAttributeNames as $attributeName)
            {
                unset($attributeNamesToIsSafe[$attributeName]);
            }
            return array_keys($attributeNamesToIsSafe);
        }

        /**
         * See the yii documentation.
         */
        public function getIterator()
        {
            throw new NotImplementedException();
        }

        /**
         * See the yii documentation.
         */
        public function offsetExists($offset)
        {
            throw new NotImplementedException();
        }

        /**
         * See the yii documentation.
         */
        public function offsetGet($offset)
        {
            throw new NotImplementedException();
        }

        /**
         * See the yii documentation.
         */
        public function offsetSet($offset, $item)
        {
            throw new NotImplementedException();
        }

        /**
         * See the yii documentation.
         */
        public function offsetUnset($offset)
        {
            throw new NotImplementedException();
        }

        /**
         * Creates an instance of the extending model wrapping the given
         * bean. For use only by models. Beans are never used by the
         * application directly.
         * @param $bean A <a href="http://www.redbeanphp.com/">RedBean</a>
         * bean.
         * @param $modelClassName Pass only when getting it at runtime
         *                        gets the wrong name.
         * @return An instance of the type of the extending model.
         */
        public static function makeModel(RedBean_OODBBean $bean, $modelClassName = null, $forceTreatAsCreation = false)
        {
            assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
            if ($modelClassName === null)
            {
                $modelClassName = get_called_class();
            }
            $modelIdentifier = $modelClassName . strval($bean->id);
            try
            {
                $model = RedBeanModelsCache::getModel($modelIdentifier);
                $model->constructIncomplete($bean, false);
                return $model;
            }
            catch (NotFoundException $e)
            {
                return new $modelClassName(true, $bean, $forceTreatAsCreation);
            }
        }

        /**
         * Creates an array of instances of the named model type wrapping the
         * given beans. For use only by models. Beans are never used by the
         * application directly.
         * @param $beans An array of <a href="http://www.redbeanphp.com/">RedBean</a>
         * beans.
         * @param $modelClassName Pass only when getting it at runtime
         *                        gets the wrong name.
         * @return An array of instances of the type of the extending model.
         */
        public static function makeModels(array $beans, $modelClassName = null)
        {
            if ($modelClassName === null)
            {
                $modelClassName = get_called_class();
            }
            $models = array();
            foreach ($beans as $bean)
            {
                assert('$bean instanceof RedBean_OODBBean');
                try
                {
                    $models[] = self::makeModel($bean, $modelClassName);
                }
                catch (MissingBeanException $e)
                {
                }
            }
            return $models;
        }

        public static function getModuleClassName()
        {
            return null;
        }

        /**
         * Given an array of data, create stringified content.
         * @param array $values
         */
        public function stringifyOneToManyRelatedModelsValues($values)
        {
            assert('is_array($values)');
            return ArrayUtil::stringify($values);
        }

        /**
         * @returns boolean
         */
        public static function getCanHaveBean()
        {
            return self::$canHaveBean;
        }

        /**
         * Resolve and get model class name used for table retrieval factoring in when a class does
         * not have a bean and must use a parent class
         * @param string $modelClassName
         */
        protected static function resolveModelClassNameForClassesWithoutBeans(& $modelClassName)
        {
            assert('is_string($modelClassName)');
            if (!$modelClassName::getCanHaveBean())
            {
                $modelClassName = get_parent_class($modelClassName);
                if (!$modelClassName::getCanHaveBean())
                {
                    //For the moment, only support a single class in a chain of classes not having a bean.
                    //Expand this support as needed.
                    throw new NotSupportedException();
                }
            }
            return $modelClassName;
        }
    }
?>
Back to Top