BEdita API doc | 4-cactus
  • Class
  • Tree
  • Deprecated
  • Download

Classes

  • Addon
  • AddressbookController
  • AddressbookShell
  • AdminController
  • Alias
  • Annotation
  • ApiAuthComponent
  • ApiBaseController
  • ApiFormatterComponent
  • ApiUploadComponent
  • ApiValidatorComponent
  • AppController
  • AppError
  • AppHelper
  • Application
  • AppModel
  • Area
  • AreasController
  • Audio
  • AuthenticationsController
  • BannedIp
  • BEAppModel
  • BEAppObjectModel
  • BeAuthComponent
  • BeAuthFacebookComponent
  • BeAuthGoogleComponent
  • BeAuthTwitterComponent
  • BeCallbackManager
  • BeConfigure
  • BeCustomPropertyComponent
  • BeditaAnnotationModel
  • BeditaBaseShell
  • BeditaCollectionModel
  • BeditaContentModel
  • BeditaExportFilter
  • BeditaImportFilter
  • BeditaObjectModel
  • BeditaProductModel
  • BeditaShell
  • BeditaSimpleObjectModel
  • BeditaSimpleStreamModel
  • BeditaStreamModel
  • BeEmbedFlashHelper
  • BeEmbedHtml5Helper
  • BeEmbedMediaHelper
  • BeErrorCode
  • BeExceptionHandler
  • BEFile
  • BeFileHandlerComponent
  • BeFormHelper
  • BeFrontHelper
  • BeHashComponent
  • BeHtmlHelper
  • BeLangTextComponent
  • BeLib
  • BeMailComponent
  • BEObject
  • BeObjectCache
  • BePaginatorToolbarHelper
  • BeSchema
  • BeSecurityComponent
  • BeSystem
  • BeSystemComponent
  • BeThumb
  • BeTimeHelper
  • BeToolbarHelper
  • BeTreeComponent
  • BeTreeHelper
  • BeUploadToObjComponent
  • BeurlHelper
  • BeVimeoComponent
  • BeYoutubeComponent
  • BuildFilterBehavior
  • CacheableBehavior
  • CacheShell
  • CallbackBehavior
  • CaptchaComponent
  • Caption
  • CaptionsBehavior
  • Card
  • CardsImportFilter
  • Category
  • CleanupDataTask
  • CleanupTask
  • Comment
  • CommentsController
  • CompactResultBehavior
  • Content
  • CreateIndexFieldsBehavior
  • DataShell
  • DataTransfer
  • DateItem
  • DbadminShell
  • DeleteDependentObjectBehavior
  • DeleteObjectBehavior
  • DeployShell
  • Document
  • DocumentsController
  • DumpModel
  • EditorialContentsShell
  • EditorNote
  • Event
  • EventLog
  • EventsController
  • FilesController
  • ForeignDependenceSaveBehavior
  • FrontendController
  • FrontendShell
  • GalleriesController
  • Gallery
  • GeoTag
  • GettextShell
  • Git
  • GravatarHelper
  • Group
  • HashJob
  • History
  • HomeController
  • Image
  • ImageInfoHelper
  • JsonExportFilter
  • JsonImportFilter
  • JsonView
  • LangText
  • Link
  • MailGroup
  • MailGroupCard
  • MailJob
  • MailLog
  • MailMessage
  • MailShell
  • MailTemplate
  • Mask
  • MediaShell
  • MigrateDumpModel
  • MigrateShell
  • Migration
  • MigrationBase
  • MigrationDateItemsShell
  • Module
  • ModulesController
  • ModuleShell
  • MultimediaController
  • NewsController
  • NewsletterController
  • NewsletterShell
  • NotifyBehavior
  • ObjectEditor
  • ObjectProperty
  • ObjectRelation
  • ObjectType
  • ObjectUser
  • PagesController
  • Permission
  • PermissionModule
  • PermsHelper
  • Product
  • Property
  • PropertyOption
  • PublicationShell
  • RedisShell
  • RelationCheck
  • RelationRepair
  • RelationShell
  • RelationStats
  • RemoveDummyNameBehavior
  • ResponseHandlerComponent
  • RestClientModel
  • Revision
  • RevisionObjectBehavior
  • SearchText
  • SearchTextSaveBehavior
  • Section
  • SectionDummy
  • SessionFilterComponent
  • SessionFilterHelper
  • ShortNews
  • SmartyView
  • SoapClientModel
  • SplitterSql
  • StatisticsController
  • Stream
  • StreamLog
  • StreamsController
  • Svn
  • TagsController
  • ThemeSmartyView
  • ThumbnailHelper
  • ThumbShell
  • TransactionComponent
  • TransactionFS
  • TranslationsController
  • Tree
  • TrHelper
  • User
  • UserProperty
  • UsersController
  • Utility
  • Version
  • Video
  • VimeoHelper
  • WebmarksController
  • XmlExportFilter
  • XmlImportFilter
  • XmlJsonConverter
  • XmlView
  • YoutubeHelper

Interfaces

  • ApiAuthInterface
  • MediaProviderInterface
  • UploadableInterface

Exceptions

  • BeditaAjaxException
  • BEditaAllowURLException
  • BeditaBadRequestException
  • BeditaConflictException
  • BEditaDeleteStreamObjException
  • BeditaException
  • BEditaFileExistException
  • BeditaForbiddenException
  • BeditaFrontAccessException
  • BeditaHashException
  • BEditaInfoException
  • BeditaInternalErrorException
  • BEditaIOException
  • BeditaLengthRequiredException
  • BeditaMailException
  • BEditaMediaProviderException
  • BeditaMethodNotAllowedException
  • BEditaMIMEException
  • BeditaNotFoundException
  • BeditaNotImplementedException
  • BeditaPublicationException
  • BeditaRuntimeException
  • BEditaSaveStreamObjException
  • BeditaServiceUnavailableException
  • BeditaUnauthorizedException
  • BEditaUploadPHPException
  • BEditaURLException
   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 
<?php
/*-----8<--------------------------------------------------------------------
 *
 * BEdita - a semantic content management framework
 *
 * Copyright 2008-2014 ChannelWeb Srl, Chialab Srl
 * 
 * This file is part of BEdita: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published 
 * by the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 * BEdita is distributed WITHOUT ANY WARRANTY; without even the implied 
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License 
 * version 3 along with BEdita (see LICENSE.LGPL).
 * If not, see <http://gnu.org/licenses/lgpl-3.0.html>.
 *
 *------------------------------------------------------------------->8-----
 */

App::import('Core', 'l10n');
App::import('Lib', 'BeLib');

/**
 * Controller base class for backends+frontends
 */
class AppController extends Controller {

    public $helpers = array('Javascript', 'Html', 'BeForm', 'Beurl', 'Tr', 'Session', 'Perms', 'BeEmbedMedia', 'SessionFilter', 'Paginator');

    public $components = array(
        'BeAuth',
        'BeTree',
        'BeCustomProperty',
        'Transaction',
        'Cookie',
        'Session',
        'RequestHandler',
        'ResponseHandler',
        'BeHash',
        'SessionFilter'
    );

    public $uses = array('EventLog');

    public $view = 'Smarty';

    public $ext = '.tpl';

    protected $moduleName = NULL;
    protected $moduleList = NULL;
    protected $modulePerms = NULL;
    /**
     * Result types for methods
     */
    const OK        = 'OK' ;
    const ERROR     = 'ERROR' ;
    const VIEW_FWD = 'view://'; //

    public $result      = 'OK' ;
    protected $skipCheck = false;

    protected static $current = NULL;

    protected $currLang = NULL; // selected UI lang
    protected $currLocale = NULL; // selected UI locale

    protected $profiling = false;
    
    /**
     * Specific per-controller model bindings
     *
     * @var array
     */
    protected $modelBindings = array();

    /**
     * Full url prefix
     *
     * @var string
     */
    protected $fullBaseUrl = '';
    
    /**
     * fields to save in history table
     *
     * @var array, set to null to avoid history insert also with history configure var setted
     */
    protected $historyItem = array();

    /**
     * If object cache is activate by objectCakeCache config param
     * it contains instance of BeObjectCache class in libs
     *
     * @var BeObjectCache
     */
    public $BeObjectCache = null;

    /**
     * Internal array to store and reuse object data like object_type_id or id from nickname
     * Avoid multiple load from database or cache of same data
     *
     * @var array
     */
    protected $objectData = array(
        'nicknames' => array(), 
        'typeIds' => array(), 
    );

    /**
     * Constructor
     * If debugKit is enabled in configuration and it's found in plugins paths
     * then add it to self::componenets array
     */
    public function __construct() {
        BeLib::getObject('BeConfigure')->initConfig();
        if (Configure::read('debugKit') && App::import('Component', 'DebugKit.Toolbar')) {
            $this->components[] = 'DebugKit.Toolbar';
        }
        parent::__construct();
    }

    public static function currentController() {
        return self::$current;
    }

    public static function usedUrl() {
        $url = !empty($_GET['url']) ? $_GET['url'] : (!empty($_POST['url']) ? $_POST['url'] : '');
        if (!empty($url)) {
            $url = ' - url: ' . $url;
        }
        return $url;
    }

    /**
     * Handle error utility
     *
     * @param string $eventMsg The event message
     * @param string $userMsg The user message
     * @param string|null $errTrace The error trace
     * @param array|null $usrMsgParams The user message parameters
     * @return void
     */
    public function handleError($eventMsg, $userMsg, $errTrace = null, $usrMsgParams = array()) {

        // avoid userid in logs / use ID instead
        $id = Set::extract('/id', $this->BeAuth->getUser());
        $id = (!empty($id)) ? $id[0] : '-';
        $logFile = 'error';
        if ($this->result != static::ERROR) {
            $logFile = strtolower($this->result);
        }
        $this->log(sprintf('%s user "%s" %s', trim($eventMsg), $id, trim(self::usedUrl())), $logFile);

        if (!empty($errTrace)) {
            $this->log($errTrace, 'exception');
        }
        // end transactions if necessary
        if (isset($this->Transaction)) {
            if ($this->Transaction->started()) {
                $this->Transaction->rollback();
            }
        }

        if (BACKEND_APP) {
            $this->eventError($eventMsg);
            $layout = (!isset($usrMsgParams['layout']))? 'message' : $usrMsgParams['layout'];
            $params = (!isset($usrMsgParams['params']))? array('class' => 'error') : $usrMsgParams['params'];
            $params['detail'] = $eventMsg;
            $this->userErrorMessage($userMsg, $layout, $params);
        }
    }

    public function setResult($r) {
        $this->result=$r;
    }

    protected function initAttributes() {}

    /**
     *  convienience method to do operations before login check
     *  for example you could set AppController::skipCheck to true avoiding user session check
     */
    protected function beforeCheckLogin() {}
    
    
    /**
     * Start profiler
     */
    protected function startProfiler() {
        if (Configure::read('enableProfiling') && function_exists('xhprof_enable')) {
            $this->profiling = true;
            xhprof_enable();
        }
    }
    
    /**
     * Stop profiler and save data
     */
    protected function stopProfiler($save = true) {
        if ($this->profiling) {
            $xhprof_data = xhprof_disable();
            if ($save) {
                App::import('Vendor', 'xhprof_lib', array('file' => 'xhprof'.DS.'xhprof_lib.php'));
                App::import('Vendor', 'xhprof_runs', array('file' => 'xhprof'.DS.'xhprof_runs.php'));
                $xhprof_runs = new XHProfRuns_Default();
                $profileName = str_replace(array('http://', 'https://', '.'), '', $this->fullBaseUrl);
                $profileName .= '-'. $this->name . '-' . $this->action; 
                $run_id = $xhprof_runs->save_run($xhprof_data, $profileName);
                $this->log('Profile run saved: ' . $run_id, 'debug');
            }
            $this->profiling = false;
        }
    }
    
    final function beforeFilter() {
        $this->startProfiler();
        // if frontend app (not staging) and object cache is active
        if (!BACKEND_APP && Configure::read('objectCakeCache') && !Configure::read('staging')) {
            $this->BeObjectCache = BeLib::getObject('BeObjectCache');
        }
        self::$current = $this;
        $conf = Configure::getInstance();
        $this->set('conf',  $conf);

        // check/setup localization
        $this->setupLocale();

        // only backend
        if (BACKEND_APP) {
            if(isset($this->data['login']) || $this->name === 'Authentications') {
                return;
            }
            // load publications public url
            $publications = ClassRegistry::init('Area')->find('all', array(
                'contain' => array('BEObject')
            ));
            $this->set('publications', $publications);
        }

        $this->beforeCheckLogin();
        $this->checkLogin();
        // convienience methods for frontends or backend to init attibutes before any other operations
        $this->initAttributes();
        $this->beditaBeforeFilter();
    }

    protected function setupLocale() {

        $this->currLang = $this->Session->read('Config.language');
        $conf = Configure::getInstance();
        if($this->currLang === null || empty($this->currLang)) {
            // read Cookie
            $lang = $this->Cookie->read('bedita.lang');
            if(isset($lang)) {
                $this->Session->write('Config.language', $lang);
                $this->currLang = $lang;
            } else {
                // HTTP autodetect
                $l10n = new L10n();
                $l10n->get();
                $this->currLang = $l10n->lang;
                if(!isset($this->currLang)) {
                    $this->currLang = $conf->defaultUILang;
                } else if(!array_key_exists($this->currLang, $conf->langsSystem)) {
                    if(isset( $conf->langsSystemMap[$this->currLang])) {
                        $this->currLang = $conf->langsSystemMap[$this->currLang];
                    } else { // use default
                        $this->currLang = $conf->defaultUILang;
                    }
                }
            }
            $this->Session->write('Config.language', $this->currLang);
            Configure::write('Config.language', $this->currLang);
        }
        $this->set('currLang', $this->currLang);
        if(isset($conf->langsSystemMapRev[$this->currLang])) {
            $this->set('currLang2', $conf->langsSystemMapRev[$this->currLang]);
        } else {
            $this->set('currLang2', $conf->defaultUILang2);
        }

        if(isset( $conf->locales[$this->currLang])) {
            $this->currLocale = setlocale(LC_ALL, $conf->locales[$this->currLang]);
        } else {
            $this->currLocale = setlocale(LC_ALL, '');
        }
        $this->set('currLocale', $this->currLocale);

        if(isset( $conf->datePatternLocale[$this->currLang])) {
            Configure::write('datePattern', $conf->datePatternLocale[$this->currLang]);
        }
        if(isset( $conf->dateTimePatternLocale[$this->currLang])) {
            Configure::write('dateTimePattern', $conf->dateTimePatternLocale[$this->currLang]);
        }
        $dateFormatValidation = $conf->datePattern;
        $dateFormatValidation = preg_replace(array('/%d/', '/%m/', '/%Y/'), array('dd','mm','yyyy'), $dateFormatValidation);
        Configure::write('dateFormatValidation', $dateFormatValidation);
    }

    /**
     * Redirect and class method result.
     * If form contains:
     *      $this->data['OK'] or $this->data['ERROR']
     * redirect to thes values (on OK, on ERROR)
     *
     * If the class defines:
     *      $this->REDIRECT[<method_name>]['OK'] or $this->REDIRECT[<method_name>]['ERROR']
     * redirect to thes values (on OK, on ERROR)
     *
     * Otherwise no redirect
     */
    final function beforeRender() {

        // convienience methods for frontends [like beforeRender]
        $this->beditaBeforeRender();

        if (defined('FULL_BASE_URL')) {
            $this->fullBaseUrl = FULL_BASE_URL;
        }
        if(isset($this->data[$this->result])) {
            $this->redirUrl($this->data[$this->result]);

        } elseif ($URL = $this->forward($this->action, $this->result)) {
            $this->redirUrl($URL);

        }

        // set up for view and BEDITA js object
        if (BACKEND_APP) {
            $allRelations = BeLib::getObject('BeConfigure')->mergeAllRelations();
            $this->set('allObjectsRelations', $allRelations);
        }

    }

    private function redirUrl($url) {
        if(strpos($url, self::VIEW_FWD) === 0) {
            $this->action=substr($url, strlen(self::VIEW_FWD));
        } else {
            $this->redirect($url);
        }
    }

    final function afterFilter() {
        // convienience methods for frontends [like afterFilter]
        $this->beditaAfterFilter();
        $this->updateHistory();
        $this->stopProfiler();
    }

    protected function updateHistory() {
        // if no history config, skip update history
        $historyConf = Configure::read('history');
        if (empty($historyConf) || empty($this->historyItem)) {
            return;
        }

        $url = Set::classicExtract($this->params, 'url.url');
        if (empty($url) || $url === '/') {
            // if params doesn't contain url.url, or url is /, skip update history
            return;
        }

        // if ajax or flash request, skip update history
        if ($this->RequestHandler->isAjax() || $this->RequestHandler->isFlash()) {
            return;
        }

        // update history
        $historyModel = ClassRegistry::init('History');
        $this->historyItem['url'] = sprintf('/%s', ltrim($this->params['url']['url'], '/')); // Prepend slash without duplicating.
        $user = $this->BeAuth->getUserSession();
        if (!empty($user)) {
            $this->historyItem['user_id'] = $user['id'];
            if (!$historyModel->save($this->historyItem)) {
                return;
            }
            $this->historyItem['id'] = $historyModel->id;
            $this->BeAuth->updateSessionHistory($this->historyItem, $historyConf);
        } elseif (!empty($historyConf['trackNotLogged'])) {
            $historyModel->save($this->historyItem);
        }
    }

    protected function forward($action, $outcome) { return false ; }

    /**
     *  local 'beforeFilter' (for backend or frontend)
     */
    protected function beditaBeforeFilter() {
    }

    /**
     *  local 'beforeRender' (for backend or frontend)
     */
    protected function beditaBeforeRender() {
    }

    /**
     *  local 'afterFilter' (for backend or frontend)
     */
    protected function beditaAfterFilter() {
    }

    /**
     * Event log creation
     *
     * @param string $level The log level
     * @param string $msg The message
     * @return void
     */
    protected function eventLog($level, $msg) {
        $userid = $this->BeAuth->userid();
        if (empty($userid)) {
            $userid = '-';
        }
        $event = array(
            'EventLog' => array(
                'log_level' => $level,
                'userid' => $userid,
                'msg' => $msg,
                'context' => strtolower($this->name)
            )
        );
        $this->EventLog->create();
        $this->EventLog->save($event);
    }

    /**
     * User error message (will appear in messages div)
     * @param string $msg
     */
    protected function userErrorMessage($msg, $layout='message', $params=array('class' => 'error')) {
        $this->Session->setFlash($msg, $layout, $params, 'error');
    }

    /**
     * User warning message (will appear in messages div)
     * @param string $msg
     */
    protected function userWarnMessage($msg, $layout='message', $params=array('class' => 'warn')) {
        $this->Session->setFlash($msg, $layout, $params, 'warn');
    }

    /**
     * User info message (will appear in messages div)
     * @param string $msg
     */
    protected function userInfoMessage($msg, $layout='message', $params=array('class' => 'info')) {
        $this->Session->setFlash($msg, $layout, $params, 'info');
    }

    /**
     * Info message in system event logs
     * @param string $msg
     */
    protected function eventInfo($msg) {
        return $this->eventLog('info', $msg);
    }

    /**
     * Warning message in system event logs
     *
     * @param string $msg
     */
    protected function eventWarn($msg) {
        return $this->eventLog('warn', $msg);
    }

    /**
     * Error message in system event logs
     *
     * @param string $msg
     */
    protected function eventError($msg) {
        return $this->eventLog('err', $msg);
    }

    /**
     * Modules access: verify user permits.
     * Uses BeAuth Component.
     *
     * Load the list of the modules availables for the user.
     */
    protected function checkLogin() {
        static  $_loginRunning = false ;

        if($_loginRunning) return true ;
        else $_loginRunning = true ;

        // skip authorization check, if specific controller set skipCheck = true
        if($this->skipCheck) return true;

        // Verify authorization
        if(!$this->BeAuth->isLogged()) {
            if ($this->RequestHandler->isAjax()) {
                throw new BeditaAjaxException(__('Session Expired', true), array('output' => 'reload'));
            }

            if ($this->Session->check('externalLoginRequestFailed')) {
                $msg = 'external login failed';
                $extUserId = $this->Session->read('externalLoginRequestFailed');
                if ($extUserId != true) {
                    $msg .= ': ' . $extUserId;
                }
                // avoid userid in logs / use ID instead or partially hide userid
                $this->eventWarn(sprintf('external login failed: %s', Mask::email($extUserId)));
                $this->userWarnMessage($msg);
                $this->Session->delete('externalLoginRequestFailed');
            };

            $this->set('externalAuthServices', $this->BeAuth->getExternalServices());

            if ($this->view == 'Smarty') {
                $viewFile = VIEWS . 'home' . DS . 'login.tpl';
            } elseif ($this->view == 'ThemeSmarty'){
                $viewFile = VIEWS . 'themed' . DS . $this->theme . DS . 'home' . DS . 'login.tpl';
            } elseif ($this->view == 'Theme'){
                $viewFile = VIEWS . 'themed' . DS . $this->theme . DS . 'home' . DS . 'login.ctp';
            } else {
                $viewFile = VIEWS . 'home' . DS . 'login.ctp';
            }

            if (Configure::read('debugKit') && isset($this->Component->_loaded['Toolbar'])) {
                $this->Toolbar->startup($this);
            }
            echo $this->render(null, null, $viewFile);
            $_loginRunning = false;
            exit;
        }

        // module list
        $this->moduleList = ClassRegistry::init('PermissionModule')->getListModules($this->BeAuth->userid());
        $this->set('moduleList', $this->moduleList) ;
        $this->set('moduleListInv', array_reverse($this->moduleList)) ;

        // verify basic access
        if(isset($this->moduleName)) {
            $moduleStatus = ClassRegistry::init('Module')->field('status', array('name' => $this->moduleName));
            if ($moduleStatus != 'on') {
                if ($this->RequestHandler->isAjax()) {
                    throw new BeditaAjaxException(__('Module not available', true));
                }
                $logMsg = 'Module ['. $this->moduleName.  '] status off';
                $this->handleError($logMsg, __('Module not available',true), $logMsg);
                $this->redirect($this->referer());
            }
            foreach ($this->moduleList as $mod) {
                if($this->moduleName == $mod['name']) {
                    $this->modulePerms = $mod['flag'];
                }
            }
            $this->set('module_modify',(isset($this->moduleName) && ($this->modulePerms & BEDITA_PERMS_MODIFY)) ? '1' : '0');
            if(!isset($this->modulePerms) || !($this->modulePerms & BEDITA_PERMS_READ)) {
                if ($this->RequestHandler->isAjax()) {
                    throw new BeditaAjaxException(__("You haven't grants for this operation", true));
                }
                $logMsg = 'Module ['. $this->moduleName.  '] access not authorized';
                $this->handleError($logMsg, __('Module access not authorized',true), $logMsg);
                $this->redirect('/');
            }
            $this->set('moduleName', $this->moduleName);
            if (!empty($this->moduleName))
                $this->set('currentModule', $this->moduleList[$this->moduleName]);


        }

        $_loginRunning = false ;

        return true ;
    }

    /**
     * Function arguments setup.
     * If variable is null, use $this->params[url].
     * Parameters:
     * 0..N array:
     *      0   var name
     *      1   type [string] (for the function settype)
     *      2   reference to the variable to modify
     *
     */
    protected function setup_args() {
        $size = func_num_args() ;
        $args = func_get_args() ;

        for($i=0; $i < $size ; $i++) {
            // If parameter is in 'params' or in 'pass', load it
            if(isset($this->params['url'][$args[$i][0]]) && !empty($this->params['url'][$args[$i][0]])) {
                $args[$i][2] = $this->params['url'][$args[$i][0]] ;
                $this->passedArgs[$args[$i][0]] = $this->params['url'][$args[$i][0]] ;

            } elseif(isset($this->params['named'][$args[$i][0]]) && !empty($this->params['named'][$args[$i][0]])) {
                $args[$i][2] = $this->params['named'][$args[$i][0]] ;
                $this->passedArgs[$args[$i][0]] = $this->params['named'][$args[$i][0]] ;

            } elseif(isset($this->passedArgs[$args[$i][0]])) {
                $args[$i][2] = $this->passedArgs[$args[$i][0]] ;
            }

            // If value is not null, define type and insert in 'namedArgs'
            if(!is_null($args[$i][2])) {
                settype($args[$i][2], $args[$i][1]) ;
                $this->params['url'][$args[$i][0]] = $args[$i][2] ;

                $this->namedArgs[$args[$i][0]] = $args[$i][2] ;
            }
        }

    }


    protected function loadModelByObjectTypeId($obj_type_id) {
        $conf  = Configure::getInstance();
        if (isset($conf->objectTypes[$obj_type_id])) {
            $modelClass = $conf->objectTypes[$obj_type_id]['model'];
        } else {
            $modelClass = $conf->objectTypesExt[$obj_type_id]['model'];
        }
        return $this->loadModelByType($modelClass);
    }

    protected function loadModelByType($modelClass) {
        if (!is_string($modelClass)) {
            throw new BeditaException(__('Model class must be a string. Given', true) . ' ' . gettype($modelClass));
        }

        $model = ClassRegistry::init($modelClass);
        if($model === false) {
            throw new BeditaException(__('Object type not found - ', true).$modelClass);
        }
        return $model;
    }

    /**
     * set model bindings and return the array used
     *
     * @param Model $modelObj
     * @param string $level binding level as defined in Model::modelBindings array
     * @return array
     */
    protected function modelBindings(Model $modelObj, $level = 'default') {
        $conf = Configure::getInstance();
        $name = $modelObj->name;
        $bindings = array();
        if(isset ($this->modelBindings[$name])) {
            $bindings = $this->modelBindings[$name];
            $modelObj->contain($bindings);
        } else if(isset ($conf->modelBindings[$name])) {
            $bindings = $conf->modelBindings[$name];
            $modelObj->contain($bindings);
        } else {
            $bindings = $modelObj->containLevel($level);
        }
        return $bindings;
    }

    /**
     * set model bindings for BEdita object
     *
     * @param string $modelType model name of BE object
     * @param string $level model binding level
     * @return array that contains:
     *              "bindings_used" => multidimensional array of bindings used,
     *              "bindings_list" => one dimensional array with the simple list of bindings ordered using a "natural order" algorithm
     *
     */
    protected function setObjectBindings($modelType, $level = 'frontend') {
        if(!isset($this->{$modelType})) {
            $this->{$modelType} = $this->loadModelByType($modelType);
        }
    
        if (!$this->baseLevel) {
            $bindingsUsed = $this->modelBindings($this->{$modelType}, $level);
        } else {
            $bindingsUsed = array("BEObject" => array("LangText"));
            if ($modelType == "Section") {
                $bindingsUsed[] = "Tree";
            }
            $this->{$modelType}->contain($bindingsUsed);
        }
        $listOfBindings = BeLib::getInstance()->arrayValues($bindingsUsed, true);
        natsort($listOfBindings);
        return array("bindings_used" => $bindingsUsed, "bindings_list" => $listOfBindings);
    }

    /**
     * Get object type (or model name) from object id using object cache
     * 
     * @param int $id Object id to search
     * @return string Object type (or model name) on success, false on failure
     */
    protected function objectTypeCache($id) {
        $typeId = $this->objectTypeIdCache($id);
        return Configure::read('objectTypes.' . $typeId . '.model');;
    }

    /**
     * Get object "type id" from object id using object cache
     * 
     * @param int $id Object id to search
     * @return int Object "type id" on success, false on failure
     */
    protected function objectTypeIdCache($id) {
        $typeId = null;
        if (!empty($this->objectData['typeIds'][$id])) {
            return $this->objectData['typeIds'][$id];
        }
        $cacheOpts = array();
        if ($this->BeObjectCache) {
            $typeId = $this->BeObjectCache->read($id, $cacheOpts, 'type');
        }
        if (empty($typeId)) {
            $typeId = $this->BEObject->findObjectTypeId($id);
            if ($typeId && $this->BeObjectCache) {
                $this->BeObjectCache->write($id, $cacheOpts, $typeId, 'type');
            }
        }
        $this->objectData['typeIds'][$id] = $typeId;
        return $typeId;
    }

    /**
     * Get object id from object nickname using object cache
     * 
     * @param string $nickname Object nickname to search
     * @return int Object id on success, false on failure
     */
    protected function idFromNicknameCache($nickname) {
        $id = false;
        if (!empty($this->objectData['nicknames'][$nickname])) {
            return $this->objectData['nicknames'][$nickname];
        }
        if ($this->BeObjectCache && !$this->BeObjectCache->hasFileEngine()) {
            $id = $this->BeObjectCache->readIdFromNickname($nickname);
        }
        if (empty($id)) {
            $id = $this->BEObject->getIdFromNickname($nickname);
            if ($id && $this->BeObjectCache && !$this->BeObjectCache->hasFileEngine()) {
                $this->BeObjectCache->writeNicknameId($nickname, $id);
            }
        }
        $this->objectData['nicknames'][$nickname] = $id;
        return $id;
    }

    /**
     * Reorder content objects relations in array where keys are relation names
     *
     * @param array $objectArray
     * @param array $status, default get all objects
     * @param array $options, possible values are
     *                        'mainLanguage' => set fields with "mainLanguage" value
     *                        'user' => in frontend app check frontend access that user
     * @return array
     */
    public function objectRelationArray($objectArray, $status=array(), $options=array()) {
        $conf = Configure::getInstance() ;
        $relationArray = array();
        $beObject = ClassRegistry::init("BEObject");
        $permission = ClassRegistry::init("Permission");
        foreach ($objectArray as $obj) {
            $rel = $obj['switch'];
            if (BACKEND_APP) {
                $modelClass = $beObject->getType($obj['object_id']);
            } else {
                $modelClass = $this->objectTypeCache($obj['object_id']);                
            }
            $this->{$modelClass} = $this->loadModelByType($modelClass);
            if (BACKEND_APP) {
                // TODO: return $bindings array like in setObjectBindings
                $this->modelBindings($this->{$modelClass}, 'default');
                $bindings = array();
            } else {
                $bindings = $this->setObjectBindings($modelClass);
            }
            
            $objDetail = null;
            if ($this->BeObjectCache) {
                $objDetail = $this->BeObjectCache->read($obj['object_id'], $bindings);
            }
            
            if (empty($objDetail)) {
                $objDetail = $this->{$modelClass}->findById($obj['object_id']);
                if (empty($objDetail)) {
                    continue;
                } elseif ($this->BeObjectCache) {
                    $this->BeObjectCache->write($obj['object_id'], $bindings, $objDetail);
                }
            }

            if (empty($status) || in_array($objDetail["status"],$status)) {
                // if frontend app add object_type and check frontend obj permission
                if (!BACKEND_APP) {
                    $objDetail['object_type'] = $modelClass;
                    if (!$this->skipCheck) {
                        $userdata = (!empty($options['user']))? $options['user'] : array();
                        $frontendAccess = $permission->frontendAccess($objDetail['id'], $userdata);
                        if ($frontendAccess == 'denied' && empty($this->showUnauthorized)) {
                            continue;
                        }
                        if ($frontendAccess == 'free') {
                            $objDetail['free_access'] = true;
                            $objDetail['authorized'] = true;
                        } else {
                            $objDetail['free_access'] = false;
                            $objDetail['authorized'] = ($frontendAccess == 'full') ? true : false;
                        }
                    } else {
                        $objDetail['free_access'] = true;
                        $objDetail['authorized'] = true;
                    }
                }

                $objDetail['priority'] = $obj['priority'];
                $objDetail['params'] = !empty($obj['params']) ? $obj['params'] : array();
                if (isset($objDetail['url'])) {
                    $objDetail['filename'] = substr($objDetail['url'],strripos($objDetail['url'],"/")+1);
                }

                // set fields with "mainLanguage" value. Usually used in frontend (frontend_controller.php)
                if (!empty($options["mainLanguage"])) {
                    if(!isset($this->BeLangText)) {
                        App::import('Component', 'BeLangText');
                        $this->BeLangText = new BeLangTextComponent();
                    }
                    $this->BeLangText->setObjectLang($objDetail, $options["mainLanguage"], $status);
                }

                $relationArray[$rel][] = $objDetail;
            }
        }
        return $relationArray;
    }

    /**
     * Setup object array with annotations-type details
     *
     * @param array $objectArray
     * @param array $status, default get all objects
     * @return array
     */
    protected function setupAnnotations(array &$objectArray, $status=array()) {
        $typesCount = array();
        $beObject = ClassRegistry::init('BEObject');
        $annotationModel = ClassRegistry::init('Annotation');
        foreach ($objectArray['Annotation'] as $obj) {
            $modelClass = $beObject->getType($obj['id']);
            $this->{$modelClass} = $this->loadModelByType($modelClass);
            $level = (BACKEND_APP)? 'default' : 'frontend';
            $this->modelBindings($this->{$modelClass}, $level);
            if(!($objDetail = $this->{$modelClass}->findById($obj['id']))) {
                continue ;
            }
            if (empty($status) || in_array($objDetail['status'],$status)) {
                // if frontend app add object_type
                if (!BACKEND_APP) {
                    $objDetail['object_type'] = $modelClass;
                }
                if (!isset($objectArray[$modelClass])) {
                    $objectArray[$modelClass] = array();
                }
                $annotationModel->putAnnotationInThread($objectArray[$modelClass], $objDetail);
                if(!array_key_exists($modelClass, $typesCount)) {
                    $typesCount[$modelClass] = 1;
                } else {
                    $typesCount[$modelClass] = $typesCount[$modelClass] + 1;
                }
            }
        }
        foreach ($typesCount as $k => $v) {
            $objectArray['num_of_'.Inflector::underscore($k)] = $v;
        }
    }

    protected function checkObjectWritePermission($objectId) {
        $permission = ClassRegistry::init('Permission');
        if (!$permission->isWritable($objectId, $this->BeAuth->getUser())) {
            throw new BeditaException(__('No write permissions on object', true));
        }
    }

    /**
     * Prepare `$this->data` with relations data checking if them are to unserialize.
     *
     * If exits `$this->data['relations_serialized']` then unserialize it and put result in `$this->data['RelatedObject']`
     *
     * @throws BeditaException When are defined both `$this->data['relations_serialized']` and `$this->data['RelatedObject']`
     * @return void
     */
    protected function prepareRelationsToSave() {
        if (array_key_exists('relations_serialized', $this->data)) {
            if (!empty($this->data['RelatedObject'])) {
                throw new BeditaException(
                    __('Wrong data to save. RelatedObject and relations_serialized can not be set together', true)
                );
            }

            $relationUnserialized = array_reduce(
                array_map(
                    function ($chunk) {
                        parse_str(implode('&', $chunk), $parsed);
                        return $parsed;
                    },
                    array_chunk(explode('&', $this->data['relations_serialized']), ini_get('max_input_vars'))
                ),
                array('Set', 'pushDiff'),
                array()
            );

            if (!empty($relationUnserialized['data']['RelatedObject'])) {
                $this->data['RelatedObject'] = $relationUnserialized['data']['RelatedObject'];
            }
            unset($this->data['relations_serialized']);
        }
    }

    protected function saveObject(BEAppModel $beModel, array $options = array()) {
        if (empty($this->data)) {
            throw new BeditaException( __('No data', true));
        }

        $options += array(
            'handleTagList' => true, // true to handle comma separated tag list creating tags don't exist
            'emptyPermission' => true, // true to remove permission ob object if any is passed
            'saveTree' => true // true to save tree
        );

        $new = (empty($this->data['id'])) ? true : false ;
        if (!$new) {
            $this->checkObjectWritePermission($this->data['id']);
        }

        $this->prepareRelationsToSave();

        // Format custom properties
        $this->BeCustomProperty->setupForSave() ;

        $name = Inflector::underscore($beModel->name);

        $categoryModel = ClassRegistry::init("Category");
        $tagList = array();

        if ($options['handleTagList']) {
            if (isset($this->params['form']['tags']) || isset($this->data['Category'])) {
                if (!empty($this->params['form']['tags'])) {
                    $tagList = $categoryModel->saveTagList($this->params['form']['tags']);
                }

                $this->data['Category'] = (!empty($this->data['Category']))? array_merge($this->data['Category'], $tagList) : $tagList;
            }
        }

        $fixed = false;
        if (!$new) {
            $fixed = ClassRegistry::init('BEObject')->isFixed($this->data['id']);
            if($fixed) { // unset pubblication date, TODO: throw exception if pub date is set!
                unset($this->data['start_date']);
                unset($this->data['end_date']);
            }
        }

        if ($options['emptyPermission'] && !isset($this->data['Permission'])) {
            $this->data['Permission'] = array();
        }

        if (isset($this->data['DateItem']) && is_array($this->data['DateItem'])) {
            // reorder array index from 0 to avoid removal
            $this->data['DateItem'] = array_values($this->data['DateItem']);
        }

        $success = $beModel->save($this->data);
        if (!$success) {
            throw new BeditaException(__("Error saving $name", true), $beModel->validationErrors);
        }

        // handle tree. Section and Area handled in AreaController
        if ($options['saveTree']) {
            if(!$fixed && isset($success[$beModel->alias]['destination']) && $beModel->name != 'Section' &&  $beModel->name != 'Area') {
                if (!$new) {
                    $this->BeTree->setupForSave($beModel->id, $success[$beModel->alias]['destination']);
                }
                ClassRegistry::init('Tree')->updateTree($beModel->id, $success[$beModel->alias]['destination']);
            }
        }
    }

    /**
     * Delete objects
     *
     * @param model name
     * @return string of objects'ids deleted
     */
    protected function deleteObjects($model) {
        $objectsToDel = array();
        $objectsListDesc = '';

        if (!empty($this->params['form']['objects_selected'])) {
            $objectsToDel = $this->params['form']['objects_selected'];
        } else {
            if (empty($this->data['id'])) {
                throw new BeditaException(__('No data', true));
            }
            $objectsToDel = array($this->data['id']);
        }

        $this->Transaction->begin();
        $beObject = ClassRegistry::init('BEObject');
        foreach ($objectsToDel as $id) {
            $this->checkObjectWritePermission($id);

            if ($beObject->isFixed($id)) {
                throw new BeditaException(__('Error, trying to delete fixed object!', true));
            }

            $objectModel = ClassRegistry::init($model);
            $parentClass = get_parent_class($objectModel);
            if ($model == 'Stream' || in_array($parentClass, array('BeditaSimpleStreamModel', 'BeditaStreamModel'))) {
                if (empty($this->BeFileHandler)) {
                    App::import('Component', 'BeFileHandler');
                    $this->BeFileHandler = new BeFileHandlerComponent();
                    $this->BeFileHandler->startup($this);
                }
                $result = $this->BeFileHandler->del($id);
            }  else {
                $result = $objectModel->delete($id);
            }

            if (!$result) {
                throw new BeditaException(__('Error deleting object: ', true) . $id);
            }

            $objectsListDesc .= $id . ',';
        }
        $this->Transaction->commit();

        return trim($objectsListDesc, ',');
    }

    /**
     * View revision data for a specific object and revision number:
     *  * all data as in revision in $revision array
     *  * array of changed fields in $diff
     *
     * @param BEAppModel $beModel
     * @param int $id, object ud
     * @param int $rev, revision number
     */
    protected function viewRevision(BEAppModel $beModel, $id, $rev) {
        if(empty($id) || empty($rev)) {
            throw new BeditaException(__('Missing object id or revision number', true));
        }
        $versionModel = ClassRegistry::init('Version');
        $nRev = $versionModel->numRevisions($id);
        if($rev < 1 || $rev > $nRev) {
            throw new BeditaException(__('Wrong revision number', true));
        }
        $revisionData = $versionModel->revisionData($id, $rev, $beModel);
        $diffData = $versionModel->diffData($id, $rev);
        $this->set('totRevision',   $nRev);
        $this->set('revision',  $revisionData);
        $this->set('diff',  $diffData);
        $versionRow = $versionModel->find('all', array('conditions' =>
            array('Version.object_id' => $id, 'Version.revision' => $rev)));
        $this->set('version',   $versionRow[0]['Version']);
        $this->set('user',  $versionRow[0]['User']);
        $conf = Configure::getInstance();
        $moduleName = $conf->objectTypes[Inflector::underscore($beModel->alias)]['module_name'];
        $this->set('moduleName', $moduleName);
    }

    /**
     * Set model bindings.
     *
     * @param string $modelName
     * @param array $bindings
     */
    public function setModelBindings($modelName, array $bindings) {
        $this->modelBindings[$modelName] = $bindings;
    }

    /**
     * Restore model bindings.
     *
     * @param string $modelName
     */
    public function unsetModelBindings($modelName) {
        unset($this->modelBindings[$modelName]);
    }
}

/**
 * Base class for modules
 *
 */
abstract class ModulesController extends AppController {

    /**
     * Controller-specific categorizable models.
     *
     * @var array
     */
    protected $categorizableModels = array();

    /**
     * Define a relations order by Model
     * The order will be reflected in every module object view detail
     * Example:
     *
     * ```
     * array(
     *     'Image' => array('attached_to', 'poster_of'),
     *     'Video' => array('seealso')
     * )
     * ```
     *
     * @see self::viewObject()
     * @var array
     */
    protected $relationsOrder = array();

    // @todo uncomment once all module plugin will be updated to use BeSecurity
    // public function __construct() {
    //     $this->components[] = 'BeSecurity';
    //     parent::__construct();
    // }

    protected function checkWriteModulePermission() {
        if (isset($this->moduleName) && !($this->modulePerms & BEDITA_PERMS_MODIFY)) {
            throw new BeditaException(__('No write permissions in module', true));
        }
    }

    /**
     * Method for paginated objects, used in ModuleController::index()...
     *
     * @param unknown_type $id
     * @param unknown_type $filter
     * @param unknown_type $order
     * @param unknown_type $dir
     * @param unknown_type $page
     * @param unknown_type $dim
     */
    protected function paginatedList($id, $filter, $order, $dir, $page, $dim) {
        $this->setup_args(
            array('id', 'integer', &$id),
            array('page', 'integer', &$page),
            array('dim', 'integer', &$dim),
            array('order', 'string', &$order),
            array('dir', 'boolean', &$dir)
        );

        $sessionFilter = $this->SessionFilter->setFromUrl();
        $filter = array_merge($filter, $sessionFilter);

        // get selected section
        $sectionSel = null;
        $pubSel = null;
        if (isset($id)) {
            $section = $this->loadModelByType('section');
            $section->containLevel('minimum');
            $sectionSel = $section->findById($id);
            $pubSel = $this->BeTree->getAreaForSection($id);
        }

        $afterFilter = array(
            array(
                'className' => 'ObjectProperty',
                'methodName' => 'objectsCustomProperties'
            ),
            array(
                'className' => 'Content',
                'methodName' => 'appendContentFields'
            ),
            array(
                'className' => 'ObjectRelation',
                'methodName' => 'countRelations',
                'options' => array(
                    'relations' => array('attach', 'seealso', 'download')
                )
            ),
            array(
                'className' => 'Tree',
                'methodName' => 'countUbiquity'
            )
        );

        if (!empty($filter['afterFilter'])) {
            if (!isset($filter['afterFilter'][0])) {
                $filter['afterFilter'][] = $filter['afterFilter'];
            }
            $filter['afterFilter'] = array_merge($filter['afterFilter'], $afterFilter);
        } else {
            $filter['afterFilter'] = $afterFilter;
        }

        $filter['count_permission'] = true;

        $objects = $this->BeTree->getChildren($id, null, $filter, $order, $dir, $page, $dim);

        $this->params['toolbar'] = &$objects['toolbar'] ;

        $properties = ClassRegistry::init('Property')->find('all', array(
            'conditions' => array('object_type_id' => $filter['object_type_id']),
            'contain' => array()
        ));

        // get publications
        $user = $this->BeAuth->getUserSession();
        $expandBranch = array();
        if (!empty($filter['parent_id'])) {
            $expandBranch[] = $filter['parent_id'];
        } elseif (!empty($id)) {
            $expandBranch[] = $id;
        }
        $treeModel = ClassRegistry::init('Tree');
        $tree = $treeModel->getAllRoots($user['userid'], null, array('count_permission' => true), $expandBranch);

        // get available relations
        $availableRelations = array();
        if (!empty($filter['object_type_id'])) {
            $objectRelation = ClassRegistry::init('ObjectRelation');
            if (!is_array($filter['object_type_id'])) {
                $filter['object_type_id'] = array($filter['object_type_id']);
            }
            foreach ($filter['object_type_id'] as $objectTypeId) {
                $r = $objectRelation->availableRelations($objectTypeId);
                $availableRelations = array_merge($availableRelations, $r);
            }
        }

        // template data
        $this->set('tree', $tree);
        $this->set('sectionSel',$sectionSel);
        $this->set('pubSel',$pubSel);
        $this->set('objects', $objects['items']);
        $this->set('objectsToolbar', $objects['toolbar']);
        $this->set('properties', $properties);
        $this->set('availableRelations', $availableRelations);

        // set prevNext array to session
        $this->setSessionForObjectDetail($objects['items']);
    }

    /**
     * Change "lang" field in bulk to objects.
     *
     * Used by "list_objects_bulk.tpl" view element.
     */
    public function changeLanguageObjects()
    {
        if (!empty($this->params['form']['objects_selected'])) {
            $objectsToModify = $this->params['form']['objects_selected'];
            $this->changeBulkObjects($objectsToModify, 'lang', $this->data['lang']);
        }
    }

    /**
     * Change "rights" field in bulk to objects.
     *
     * Used by "list_objects_bulk.tpl" view element.
     */
    public function changeRightsObjects()
    {
        if (!empty($this->params['form']['objects_selected'])) {
            $objectsToModify = $this->params['form']['objects_selected'];
            $this->changeBulkObjects($objectsToModify, 'rights', $this->data['rights']);
        }
    }

    /**
     * Change objects field value in bulk.
     *
     * @param integer[] $objectIds - IDs of the objects to change
     * @param string    $field     - name of the field to change
     * @param string    $value     - new value for the field
     *
     * @throws BeditaException
     */
    protected function changeBulkObjects($objectIds, $field, $value)
    {
        $beObject = ClassRegistry::init('BEObject');
        $this->Transaction->begin();

        foreach ($objectIds as $id) {
            $this->checkObjectWritePermission($id);

            if ($beObject->isFixed($id)) {
                throw new BeditaException(sprintf(__('Error: changing %s to a fixed object!', true), $field));
            }

            $beObject->id = $id;

            if (!$beObject->saveField($field, $value)) {
                throw new BeditaException(sprintf(__('Error saving %s for item: %s', true), $field, $id));
            }
        }

        $this->Transaction->commit();
    }

    /**
     * Add multiple permissions in bulk to objects.
     *
     * Used by "list_objects_bulk.tpl" view element.
     */
    public function addPermissionsObjects()
    {
        if (!empty($this->params['form']['objects_selected'])) {
            $objectIds = $this->params['form']['objects_selected'];
            $permission = ClassRegistry::init('Permission');
            $group = ClassRegistry::init('Group');
            $errors = array();

            foreach ($objectIds as $objectId) {
                foreach ($this->data['Permission'] as $permissionData) {
                    $ugid = $group->field('id', array('name' => $permissionData['name']));
                    $countPermission = $permission->find('count', array(
                        'conditions' => array(
                            'object_id' => $objectId,
                            'switch' => 'group',
                            'ugid' => $ugid,
                            'flag' => $permissionData['flag'],
                        ),
                    ));
                    if ($countPermission > 0) {
                        $errors[$objectId][] = sprintf(__("permission for '%s' already set", true), $permissionData['name']);
                        continue;
                    }

                    try {
                        $permission->add($objectId, array($permissionData));
                    } catch (Exception $e) {
                        $errors[$objectId][] = sprintf(__("error adding permission for '%s': %s", true), $e->getMessage());
                        $this->log(sprintf("Error adding permission '%s' to object %s: %s", $permissionData['name'], $objectId, $e->getMessage()), 'error');
                    }
                }
            }

            if (!empty($errors)) {
                $errorDetails = array_map(function ($errorMessage, $objectId) {
                    return sprintf("object: %s\n  %s", $objectId, implode("\n  ", $errorMessage));
                }, $errors, array_keys($errors));
                
                $this->userWarnMessage(__("Not all permissions have been added", true), 'message', array(
                    'class' => 'warn',
                    'detail' => implode("\n\n", $errorDetails),
                ));
            }
        }
    }

    public function changeStatusObjects($modelName=null) {
        $objectsToModify = array();
        $objectsListDesc = '';
        $beObject = ClassRegistry::init('BEObject');

        if(!empty($this->params['form']['objects_selected'])) {
            $objectsToModify = $this->params['form']['objects_selected'];

            $this->Transaction->begin() ;

            if (empty($modelName))
                $modelName = 'BEObject';

            foreach ($objectsToModify as $id) {
                $this->checkObjectWritePermission($id);
                $model = $this->loadModelByType($modelName);
                if ($beObject->isFixed($id)) {
                    throw new BeditaException(__('Error: changing status to a fixed object!', true));
                }
                $model->id = $id;
                if(!$model->saveField('status',$this->params['form']['newStatus']))
                    throw new BeditaException(__('Error saving status for item: ', true) . $id);
                $objectsListDesc .= $id . ',';
            }

            $this->Transaction->commit() ;
        }
        return trim($objectsListDesc, ',');
    }

    public function assocCategory() {
        $this->checkWriteModulePermission();
        if(!empty($this->params['form']['objects_selected'])) {
            $objects_to_assoc = $this->params['form']['objects_selected'];
            $category_id = $this->data['category'];
            $category = ClassRegistry::init('Category');
            $this->Transaction->begin() ;
            foreach($objects_to_assoc as $k => $id) {
                if(!$category->addObjectCategory($category_id, $id)) {
                    throw new BeditaException(__('Error saving object category', true) .
                              ' category: ' . $category_id, ' object: ' . $id);
                }
            }
            $this->Transaction->commit() ;
            $this->userInfoMessage(__('Added items association to category', true) . ' - ' . $category_id);
            $this->eventInfo('added items association to category ' . $category_id);
        }
    }

    public function disassocCategory() {
        $this->checkWriteModulePermission();
        if(!empty($this->params['form']['objects_selected'])) {
            $objects_to_assoc = $this->params['form']['objects_selected'];
            $category_id = $this->data['category'];
            $beObject = ClassRegistry::init('BEObject');
            $categories = array();
            $this->Transaction->begin() ;
            foreach($objects_to_assoc as $k => $id) {
                $object_type_id = $beObject->findObjectTypeId($id);
                $modelLoaded = $this->loadModelByObjectTypeId($object_type_id);
                $modelLoaded->contain(array('BEObject'=>array('Category')));
                $obj = $modelLoaded->findById($id);
                $category_present = false;
                foreach($obj['Category'] as $key => $cat) {
                    if($cat['id'] == $category_id) {
                        $category_present = true;
                    } else {
                        $categories[$cat['id']] = $cat['id'];
                    }
                }
                if($category_present) {
                    unset($obj['Category']);
                    $obj['Category'] = $categories;
                    $modelLoaded->create();
                    $modelLoaded->save($obj);
                }
            }
            $this->Transaction->commit() ;
            $this->userInfoMessage(__('Removed items association to category', true) . ' - ' . $category_id);
            $this->eventInfo('removed items association to category ' . $category_id);
        }
    }

    public function addItemsToAreaSection() {
        $this->itemsAreaSectionOp('add',$this->params['form']['objects_selected'],$this->data['destination']);
    }

    public function moveItemsToAreaSection() {
        $this->itemsAreaSectionOp('del',$this->params['form']['objects_selected'],$this->data['source'],false);
        $this->itemsAreaSectionOp('add',$this->params['form']['objects_selected'],$this->data['destination']);
    }

    public function removeItemsFromAreaSection() {
        $this->itemsAreaSectionOp('del',$this->params['form']['objects_selected'],$this->data['source']);
    }

    private function itemsAreaSectionOp($op='add',$objects_to_assoc=array(),$area_section_id=null,$user_info=true) {
        $this->checkWriteModulePermission();
        if(!empty($objects_to_assoc)) {
            $modelTree = ClassRegistry::init('Tree');
            $beObject = ClassRegistry::init('BEObject');
            $object_type_id = $beObject->findObjectTypeId($area_section_id);
            $modelLoaded = $this->loadModelByObjectTypeId($object_type_id);
            $modelLoaded->contain('BEObject');
            if(!($area_section = $modelLoaded->findById($area_section_id))) {
                throw new BeditaException(sprintf(__('Error loading section: %d', true), $area_section_id));
            }
            $this->Transaction->begin() ;
            for($i=0; $i < count($objects_to_assoc) ; $i++) {
                if ($beObject->isFixed($objects_to_assoc[$i])) {
                    throw new BeditaException(__('Error: modifying a fixed object!', true));
                }
                $parents = $this->BeTree->getParents($objects_to_assoc[$i]);
                $is_already_present = in_array($area_section_id, $parents);
                if ($op=='add' && !$is_already_present) {
                    if(!$modelTree->appendChild($objects_to_assoc[$i],$area_section_id)) {
                        throw new BeditaException( __('Error during append child', true));
                    }
                } else if ($op=='del' && $is_already_present) {
                    if(!$modelTree->removeChild($objects_to_assoc[$i],$area_section_id)) {
                        throw new BeditaException( __('Error during remove child', true));
                    }
                }
            }
            $this->Transaction->commit() ;
            $op_str = ($op=='add') ? 'associated to' : 'removed from';
            if($user_info) {
                $this->userInfoMessage(__("Items $op_str area/section", true) . ' - ' . $area_section['title']);
            }
            $this->eventInfo("items $op_str area/section " . $area_section_id);
        }
    }

    /**
     * Return preview links for $obj_nick in publications
     *
     * @param $sections array of section/area id
     * @param $obj_nick object nickname
     * @return array of previews divided by publications, all object's url are in 'object_url' => array
     */
    public function previewsForObject($sections,$obj_nick) {
        $previews = array();
        if(empty($obj_nick) || empty($sections)) {
            return $previews;
        }

        $treeModel = ClassRegistry::init('Tree');
        $beObjectModel = ClassRegistry::init('BEObject');
        $areaModel = ClassRegistry::init('Area');

        $pubId = array();
        foreach($sections as $key => $section_id) {
            $path = $treeModel->field('parent_path', array('id' => $section_id));
            $path = trim($path,'/');
            $parents = array();
            $nickPath = '';
            if (!empty($path)) {
                $parents = explode('/', $path);
                $area_id = array_shift($parents);
                if (!empty($parents)) {
                    foreach ($parents as $val) {
                        $nickPath .= '/' . $beObjectModel->getNicknameFromId($val);
                    }
                }
                $nickPath .= '/' . $beObjectModel->getNicknameFromId($section_id);
            } else {
                $area_id = $section_id;
            }

            $nickPath .= '/' . $obj_nick;

            if (empty($previews[$area_id])) {
                $previews[$area_id] = $areaModel->find('first', array(
                    'conditions' => array('Area.id' => $area_id),
                    'contain' => array('BEObject')
                    )
                );
                $previews[$area_id]['object_url'] = array();
            }

            $obj_url = array();
            if (!empty($previews[$area_id]['public_url'])) {
                $obj_url['public_url'] = $previews[$area_id]['public_url'] . $nickPath;
            }
            if (!empty($previews[$area_id]['staging_url'])) {
                $obj_url['staging_url'] = $previews[$area_id]['staging_url'] . $nickPath;
            }

            $previews[$area_id]['object_url'][] = $obj_url;
        }

        return $previews;
    }

    public function cloneObject() {
        unset($this->data['id']);
        unset($this->data['nickname']);
        unset($this->data['user_created']);
        $this->data['status'] = 'draft';
        $this->data['fixed'] = 0;
        $this->save();
    }

    protected function checkAutoSave() {
        $new = (empty($this->data['id'])) ? true : false ;
        $beObject = ClassRegistry::init('BEObject');
        if(!$new) {
            $objectId = $this->data['id'];
            $status = $beObject->field('status', "id = $objectId");
            if($status == 'on') {
                throw new BeditaException(__('Autosave: bad status', true));
            }

            // check perms on object/module
            $user = $this->Session->read('BEAuthUser');
            $permission = ClassRegistry::init('Permission');
            if(!$permission->isWritable($objectId, $user)) {
                throw new BeditaException(__('Autosave: no write permission', true));
            }

            // check editors
            $objectEditor = ClassRegistry::init('ObjectEditor');
            $objectEditor->cleanup($objectId);
            $res = $objectEditor->loadEditors($objectId);
            if(count($res) > 1) {
                throw new BeditaException(__('Autosave: other editors present', true));
            }
        }

        if(!($this->modulePerms & BEDITA_PERMS_MODIFY)) {
            throw new BeditaException(__('Autosave: no module permission', true));
        }
    }

    public function autoSaveObject(BEAppObjectModel $model) {
        $this->checkAutoSave();
        // disable behaviors
        $disableBhv = array('RevisionObject', 'Notify');
        $disabled = array();
        foreach ($disableBhv as $dis) {
            if($model->Behaviors->enabled($dis)) {
                $model->Behaviors->disable($dis);
                $disabled[] = $dis;
            }
        }
        $this->saveObject($model);
        // re-enable behaviors
        foreach ($disabled as $d) {
            $model->Behaviors->enable($d);
        }
        $this->set('id', $model->id);
    }

    protected function viewObject(BEAppModel $beModel, $id = null) {
        if (Configure::read('langOptionsIso') == true) {
            Configure::load('langs.iso') ;
        }
        $obj = null ;
        $parents_id = array();
        $relations = array();
        $relationsCount = array();
        $previews = array();
        $name = Inflector::underscore($beModel->name);
        $treeModel = ClassRegistry::init('Tree');
        if (isset($id)) {
            // check if object is forbidden for user
            $user = $this->Session->read('BEAuthUser');
            $permission = ClassRegistry::init('Permission');
            if ($permission->isForbidden($id, $user)) {
                throw new BeditaException(__('Access forbidden to object', true) . " $id");
            }

            $id = ClassRegistry::init('BEObject')->objectId($id);
            $objEditor = ClassRegistry::init('ObjectEditor');
            $objEditor->cleanup($id);

            $beModel->containLevel('detailed');
            if (!($obj = $beModel->findById($id))) {
                throw new BeditaException(__("Error loading $name: ", true).$id);
            }
            if (!$beModel->checkType($obj['object_type_id'])) {
               throw new BeditaException(__('Wrong content type: ', true).$id);
            }
            if (!empty($obj['RelatedObject'])) {
                $relations = $this->objectRelationArray($obj['RelatedObject']);
                $obj['relations'] = $relations;
            }
            foreach ($relations as $k=>$v) {
                $relationsCount[$k] = count($v);
            }
            if (!empty($obj['Annotation'])) {
                $this->setupAnnotations($obj);
            }
            unset($obj['Annotation']);
            // build array of id's categories associated
            $obj['assocCategory'] = array();
            if (isset($obj['Category'])) {
                $objCat = array();
                foreach ($obj['Category'] as $oc) {
                    $objCat[] = $oc['id'];
                }
                $obj['assocCategory'] = $objCat;
            }
            $parents_id = $treeModel->getParents($id) ;

            $previews = $this->previewsForObject($parents_id, $obj['nickname']);

            $this->historyItem['object_id'] = $id;

            // #1078, #1080 - hidden subsection management
            $this->readonlyTreePaths($id);
            $this->isInsideHiddenBranch($id);
        }

        $property = $this->BeCustomProperty->setupForView($obj, Configure::read('objectTypes.' . $name . '.id'));
        $relationsOrder = !empty($this->relationsOrder[$beModel->alias]) ? $this->relationsOrder[$beModel->alias] : array();
        $availabeRelations = ClassRegistry::init('ObjectRelation')->availableRelations($name, $relationsOrder);

        $this->set('object',    $obj);
        $this->set('attach', isset($relations['attach']) ? $relations['attach'] : array());
        $this->set('relObjects', $relations);
        $this->set('relationsCount', $relationsCount);
        $this->set('objectProperty', $property);
        $this->set('availabeRelations', $availabeRelations);

        // get publications
        $user = $this->BeAuth->getUserSession();
        $tree = $treeModel->getAllRoots($user['userid'], null, array('count_permission' => true), $parents_id);

        $this->set('tree', $tree);
        $this->set('parents', $parents_id);
        $this->set('previews', $previews);
        $categoryModel = ClassRegistry::init('Category');
        $areaCategory = $categoryModel->getCategoriesByArea(Configure::read('objectTypes.'.$name.'.id'));
        $this->set('areaCategory', $areaCategory);
        $this->setSessionForObjectDetail();
    }


    /**
     * set session vars to use in objects detail:
     *      - backFromView
     *      - array with prev and next
     *
     * @param array $objects if it's defined prepare prevNext array for session
     */
    protected function setSessionForObjectDetail($objects=null) {
        $modulePath = $this->viewVars['currentModule']['url'];

        // set array of previous and next objects
        if (!empty($objects) && strstr($this->here, $modulePath)) {
            foreach ($objects as $k => $o) {
                $prevNextArr[$o['id']]['prev'] = (!empty($objects[$k-1]))? $objects[$k-1]['id'] : '';
                $prevNextArr[$o['id']]['next'] = (!empty($objects[$k+1]))? $objects[$k+1]['id'] : '';
            }
            $this->Session->write('prevNext', $prevNextArr);
        }

        $backURL = $this->Session->read('backFromView');

        $baseModuleUrl = rtrim($this->base,'/') . '/' . $modulePath;

        // set backFromView session vars and reset prevNext if necessary
        if (!empty($this->here) && (strstr($this->here, $modulePath . '/index') || rtrim($this->here, '/') === $baseModuleUrl)) {
            $backURL = (empty($this->params['form']['searchstring']))? $this->here : rtrim($this->here,'/') . '/query:' . urlencode($this->params['form']['searchstring']);
            $this->Session->write('backFromView', $backURL);
        } elseif (empty($backURL) || !strstr($backURL, $modulePath) || !strstr($this->referer(), $modulePath)) {
            $this->Session->write('backFromView', $baseModuleUrl);
            $this->Session->write('prevNext', '');
        }
    }

    protected function loadCategories($objectTypes = array()) {
        $categoryModel = ClassRegistry::init('Category');
        $categoryModel->Behaviors->disable('CompactResult');
        $categories = $categoryModel->find('list', array(
            'fields' => array('id','label'),
            'conditions' => array('object_type_id' => $objectTypes),
            'order' => 'label'
        ));
        $categoryModel->Behaviors->enable('CompactResult');
        $this->set('categories',$categories);
    }

    protected function showCategories(BEAppModel $beModel) {
        $type = Configure::read('objectTypes.' . Inflector::underscore($beModel->name) . '.id');
        if (is_null($type)) {
            return;
        }
        $this->paginate = array(
            'fields' => array('Category.id','Category.label','Category.name','Category.status','Category.area_id'),
            'conditions' => array('object_type_id' => $type),
            'limit' => 10,
            'order' => 'label'
        );
        $categories = $this->paginate('Category');
        $this->set('categories', $categories);
        $this->set('object_type_id', $type);
        $this->set('areasList', ClassRegistry::init('BEObject')->find('list', array(
                'conditions' => 'object_type_id=' . Configure::read('objectTypes.area.id'),
                'order' => 'title',
                'fields' => 'BEObject.title'
                )
            )
        );
    }

    /**
     * Saves a category. Controllers should specify the list of categorizable models in $categorizableModels property.
     */
    public function saveCategories() {
        $this->checkWriteModulePermission();

        $Category = ClassRegistry::init('Category');
        $ExceptionClass = $this->params['isAjax'] ? 'BeditaAjaxException' : 'BeditaException';
        $exceptionOptions = $this->params['isAjax'] ? array('output' => 'json') : array();

        if (empty($this->data['label'])) {
            throw new $ExceptionClass(__('No data', true), $exceptionOptions);
        }

        // Object type ID checks.
        if (!in_array(Configure::read('objectTypes.' . $this->data['object_type_id'] . '.model'), $this->categorizableModels)) {
            // Object type not categorizable in current controller.
            throw new $ExceptionClass(__('Object type not allowed', true), $exceptionOptions);
        }
        if (array_key_exists('id', $this->data)) {
            // Existing category.
            $cat = $Category->findById($this->data['id']);
            if ($cat['object_type_id'] != $this->data['object_type_id']) {
                // Trying to change object_type_id of category.
                throw new $ExceptionClass(__('Cannot change object type for category', true), $exceptionOptions);
            }
        }

        $this->Transaction->begin();
        if (!$Category->save($this->data)) {
            throw new $ExceptionClass(__('Error saving tag', true), $exceptionOptions + $Category->validationErrors);
        }
        $this->Transaction->commit();

        $this->eventInfo('Category [' .$this->data['label'] . '] saved');

        $info = __('Category saved', true) . ' - ' . $this->data['label'];
        if ($this->params['isAjax']) {
            $this->ResponseHandler->setType('json');
            $this->set(compact('info'));
            $this->set('_serialize', array('info'));
        } else {
            $this->userInfoMessage($info);
            $this->redirect('/'. $this->moduleName . '/categories');
        }
    }

    /**
     * Deletes a category. Controllers should specify the list of categorizable models in $categorizableModels property.
     *
     * @deprecated
     */
    public function deleteCategories() {
        $this->checkWriteModulePermission();

        $Category = ClassRegistry::init('Category');

        if (empty($this->data['ids'])) {
            throw new BeditaException(__('No data', true));
        }

        // Object type ID checks.
        $cat = $Category->findById($this->data['id']);
        if (!in_array(Configure::read('objectTypes.' . $cat['object_type_id'] . '.model'), $this->categorizableModels)) {
            // Object type not categorizable in current controller.
            throw new BeditaException(__('Object type not allowed', true));
        }

        $this->Transaction->begin();
        if (!$Category->delete($this->data['id'])) {
            throw new BeditaException(__('Error saving tag', true), $Category->validationErrors);
        }
        $this->Transaction->commit();

        $this->userInfoMessage(__('Category deleted', true) . ' - ' . $cat['label']);
        $this->eventInfo('Category ' . $this->data['id'] . '-' . $cat['label'] . ' deleted');
    }

    /**
     * Performs bulk actions on categories.
     */
    public function bulkCategories() {
        $this->checkWriteModulePermission();

        $Category = ClassRegistry::init('Category');

        $action = null;
        if (array_key_exists('merge', $this->data)) {
            $action = 'merge';
        } elseif (array_key_exists('delete', $this->data)) {
            $action = 'delete';
        } else {
            throw new BeditaException(__('Unknown action'), array_keys($this->data));
        }
        if (empty($this->data['ids'])) {
            throw new BeditaException(__('No data', true));
        }

        // Object type ID checks.
        $objectTypeIds = Set::classicExtract($Category->find('all', array(
            'contain' => array(),
            'fields' => array('object_type_id'),
            'conditions' => array('Category.id' => $this->data['ids'])
        )), '{n}.object_type_id');
        foreach (array_unique($objectTypeIds) as $otid) {
            if (!in_array(Configure::read('objectTypes.' . $otid . '.model'), $this->categorizableModels)) {
                // Object type not categorizable in current controller.
                throw new BeditaException(__('Object type not allowed', true));
            }
        }

        $mergeInfo;
        $this->Transaction->begin();
        if ($action == 'merge') {
            // Merge.
            $mergeId = array_shift($this->data['ids']);  // Get first category and remove from array.
            $objectIds = ClassRegistry::init('ObjectCategory')->find('list', array(
                'fields' => array('ObjectCategory.object_id'),
                'conditions' => array(
                    'ObjectCategory.category_id' => $this->data['ids'],
                ),
            ));  // Find objects in other categories.
            foreach ($objectIds as $id) {
                // Merge to elected category.
                if (!$Category->addObjectCategory($mergeId, $id)) {
                    throw new BeditaException(__('Error merging categories'), true);
                }
            }
            $mergeInfo = $Category->read('name', $mergeId);
        }
        //*/
        foreach ($this->data['ids'] as $id) {
            // Delete.
            if (!$Category->delete($id)) {
                throw new BeditaException(__('Error deleting categories'), true);
            }
        }
        /*/  // The following should be way faster but ain't working. Don't know why...
        if (!$Category->deleteAll(array('Category.id' => $this->data['ids']), true, false)) {
            // Delete.
            throw new BeditaException(__('Error deleting categories'), true);
        }
        //*/
        $this->Transaction->commit();

        $msg = $action == 'merge' ? "merged to {$mergeInfo['name']}" : 'deleted';
        $ids = implode(', ', $this->data['ids']);
        $this->userInfoMessage(__('Categories ' . $msg, true) . ' - ' . $ids);
        $this->eventInfo('Categories ' . $ids . ' ' . $msg);
    }

    /**
     * return array of object types belong to module
     *
     * @param string $moduleName
     * @return array
     */
    protected function getModuleObjectTypes($moduleName) {
        $otModel = ClassRegistry::init('ObjectType');
        $ot = $otModel->find('all', array(
                'conditions' => array('module_name' => $moduleName),
                'fields' => 'id',
                'contain' => array()
            )
        );
        $objectTypes = array();
        if (!empty($ot)) {
            foreach ($ot as $o) {
                $objectTypes[] = $o['ObjectType']['id'];
            }
        }
        return $objectTypes;
    }

    protected function loadFilters($filterType = 'export') {
        $ff = array();
        $filters = Configure::read('filters.' . $filterType);
        if (!empty($filters)) {
            foreach($filters as $filter => $className) {
                $filterModel = ClassRegistry::init($className);
                if (!empty($filterModel)) {
                    if (!empty($filterModel->label)) {
                        $ff[$className]['label'] = $filterModel->label;
                    }
                    if (!empty($filterModel->options)) {
                        $ff[$className]['options'] = $filterModel->options;
                    }
                    if (!empty($filterModel->defaultExtension)) {
                        $ff[$className]['defaultExtension'] = $filterModel->defaultExtension;
                    }
                }
                if (empty($ff[$className]['label'])) {
                    $ff[$className]['label'] = $filter;
                }
                if (empty($ff[$className]['options'])) {
                    $ff[$className]['options'] = array();
                }
                if (empty($ff[$className]['defaultExtension'])) {
                    $ff[$className]['defaultExtension'] = '';
                }
            }
        }
        return $ff;
    }

    /**
     * Generic view method: to override in real modules or create specific view methods
     * if more types are handled by this module, like view[ModelName] (e.g. viewDocument, viewEvent...)
     * This methods will be called automagically....
     *
     * @param integer $id object id to view
     */
    public function view($id) {
        $modelName = ClassRegistry::init('BEObject')->getType($id);
        $method = 'view' . $modelName;
        if (!method_exists($this, $method)) {
            throw new BeditaException(__('Missing view method', true).' - '.$method);
        }
        $this->action = $method;
        $this->{$method}($id);
    }

    /**
     * Generic delete method: to override in real modules.
     * If more types are handled by this module create specific delete methods
     * like delete[ModelName] (e.g. deleteDocument, deleteEvent...)
     * This methods will be called automagically....
     */
    public function delete() {
        $modelName = ClassRegistry::init('BEObject')->getType($this->data['id']);
        $method = 'delete' . $modelName;
        if (!method_exists($this, $method)) {
            throw new BeditaException(__('Missing delete method', true).' - '.$method);
        }
        $this->action = $method;
        $this->{$method}();
    }

    /**
     * Generic save method: to override in real modules.
     * If more types are handled by this module create specific 'save' methods
     * like save[ModelName] (e.g. saveDocument, saveEvent...)
     * This methods will be called automagically....
     */
    public function save() {
        if(!empty($this->data['id'])) {
            $modelName = ClassRegistry::init('BEObject')->getType($this->data['id']);
        } else {
            $objTypeId = $this->data['object_type_id'];
            $modelName = Configure::read("objectTypes.$objTypeId.model");
        }
        $method = 'save' . $modelName;
        if (!method_exists($this, $method)) {
            throw new BeditaException(__('Missing save method', true).' - '.$method);
        }
        $this->action = $method;
        $this->{$method}();
    }

    /*
     * Set 'readonlyTreePaths' data for a specified $id passed, if $id resides in an hidden tree branch
     * Data look like:
     * [
     *     {
     *         'ids' => [223481, 274603], // array of integers
     *         'parentId' => 274603, // integer parent id
     *         'idsPath' => '/223481/274603', // string representing ids path
     *         'titles' => [
     *             223481 => 'Publication A', // publication title
     *             274603 => 'Section B' // section title
     *          ],
     *         'titlesPath' => 'Publication A > Section B' // string that concats titles
     *     },
     *     // ...
     * ]
     *
     * @param int $id object id
     * @return void
     */
    public function readonlyTreePaths($id) {
        $treeModel = ClassRegistry::init('Tree');
        $hiddenParentIds = Configure::read('excludeFromTreeIds');
        if (!empty($hiddenParentIds)) {
            $paths = null;
            if (in_array($id, $hiddenParentIds)) {
                $paths = $treeModel->titlesPaths($id, $hiddenParentIds);
            } else {
                $hasHiddenParent = false;
                foreach ($hiddenParentIds as $parentId) {
                    if ($treeModel->isParent($parentId, $id)) {
                        $hasHiddenParent = true;
                    }
                }
                if ($hasHiddenParent) {
                    $paths = $treeModel->titlesPaths($id, $hiddenParentIds);
                }
            }
            if (!empty($paths)) {
                $this->set('readonlyTreePaths', $paths);
            }
        }
    }

    /**
     * Set 'isInsideHiddenBranch' for a specified $id passed, if $id is inside hidden branch id config 'excludeFromTreeIds'
     * 
     * @param int $id section id
     * @return void
     */
    public function isInsideHiddenBranch($id) {
        $hiddenParentIds = Configure::read('excludeFromTreeIds');
        if (empty($hiddenParentIds)) {
            return $this->set('isInsideHiddenBranch', false);
        }

        $isInsideHiddenBranch = in_array($id, $hiddenParentIds);
        if (!$isInsideHiddenBranch) {
            $treeModel = ClassRegistry::init('Tree');
            foreach ($hiddenParentIds as $parentId) {
                if ($treeModel->isParent($parentId, $id)) {
                    $isInsideHiddenBranch = true;
                }
            }
        }
        $this->set('isInsideHiddenBranch', $isInsideHiddenBranch);
    }

    /**
     * Default module controller forward given $action and $result.
     * Default rules are used, you may pass custom rules in $moduleRedirect array
     * 
     * @param string $action
     * @param string $result
     * @param string $moduleRedirect
     * @return mixed, redirect url or false if no redirect is found
     */
    public function moduleForward($action, $result, $moduleRedirect = array()) {
        $referer = $this->referer();
        if (!empty($this->uses)) {
            $modelName = $this->uses[0];
            $viewUrl = '/' . $this->moduleName . '/view/' . @$this->{$modelName}->id;
        } else {
            $viewUrl = $referer;
        }
        $categoriesUrl = '/'. $this->moduleName . '/categories';
        
        $defaultRedirect = array(
                'addItemsToAreaSection' =>  array(
                        'OK'    => $referer,
                        'ERROR' => $referer
                ),
                'assocCategory' =>  array(
                        'OK'    => $this->referer(),
                        'ERROR' => $this->referer()
                ),
                'bulkCategories'    => array(
                        'OK'    => $categoriesUrl,
                        'ERROR' => $categoriesUrl
                ),
                'changeStatusObjects'   =>  array(
                        'OK'    => $this->referer(),
                        'ERROR' => $this->referer()
                ),
                'changeLanguageObjects'   =>  array(
                        'OK'    => $this->referer(),
                        'ERROR' => $this->referer()
                ),
                'changeRightsObjects'   =>  array(
                        'OK'    => $this->referer(),
                        'ERROR' => $this->referer()
                ),
                'addPermissionsObjects'   =>  array(
                        'OK'    => $this->referer(),
                        'ERROR' => $this->referer()
                ),
                'cloneObject'   =>  array(
                        'OK'    => $viewUrl,
                        'ERROR' => $viewUrl
                ),
                'delete' => array(
                        'OK'    => $this->fullBaseUrl . $this->Session->read('backFromView'),
                        'ERROR' => $referer
                ),
                'deleteCategories'  => array(
                        'OK'    => $categoriesUrl,
                        'ERROR' => $categoriesUrl
                ),
                'deleteSelected' => array(
                        'OK'    => $referer,
                        'ERROR' => $referer
                ),
                'disassocCategory'  =>  array(
                        'OK'    => $this->referer(),
                        'ERROR' => $this->referer()
                ),
                'moveItemsToAreaSection'    =>  array(
                        'OK'    => $this->referer(),
                        'ERROR' => $this->referer()
                ),
                'removeItemsFromAreaSection'    =>  array(
                        'OK'    => $this->referer(),
                        'ERROR' => $this->referer()
                ),
                'save'  =>  array(
                        'OK'    => $viewUrl,
                        'ERROR' => $referer
                ),
                'view'  =>  array(
                        'ERROR' => '/'.$this->moduleName
                ),
        );
        $redirect = array_merge($defaultRedirect, $moduleRedirect);
        if (isset($redirect[$action][$result])) {
            return $redirect[$action][$result] ;
        }
        return false ;
    }

    /** 
     * Default forward for BEdita modules - to overrider in module controllers if needed
     * @see AppController::forward()
     */
    protected function forward($action, $result) {
        return $this->moduleForward($action, $result);
    }

}
BEdita API doc | 4-cactus API documentation generated by ApiGen