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 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 
<?php
/*-----8<--------------------------------------------------------------------
 *
 * BEdita - a semantic content management framework
 *
 * Copyright 2014-2015 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-----
 */

/**
 * ApiBaseController class
 *
 * Abstract Base Api Controller
 * It must to be extended by ApiController in frontend apps
 */
abstract class ApiBaseController extends FrontendController {

    /**
     * The Models used
     *
     * @var array
     */
    public $uses = array();

    /**
     * The Components used
     *
     * @var array
     */
    public $components = array(
        'ResponseHandler' => array('type' => 'json'),
        'ApiFormatter',
        'ApiValidator',
        'ApiUpload'
    );

    /**
     * Contain the instance of API auth component used
     * Normally it corresponds to ApiAuthComponent but it can contain another auth component
     * To do it a custom component, named for example 'MyAuth', has to be activated via conf
     *
     * ```
     * $config['api'] = array(
     *     'baseUrl' => '/api',
     *     'auth' => array(
     *         'component' => 'MyAuth'
     *     ),
     *     ...
     * );
     * ```
     *
     * Note that the custom auth component should implements ApiAuthInterface
     *
     * @var Object
     */
    public $ApiAuth = null;

    /**
     * The default endpoints
     *
     * @var array
     */
    private $defaultEndPoints = array('objects', 'auth', 'me', 'posters', 'files');

    /**
     * The default binding level
     *
     * @see FrontendController::defaultBindingLevel
     * @var string
     */
    protected $defaultBindingLevel = 'api';

    /**
     * Allowed model bindings
     * Used to get more or less fields and associations through GET /objects param 'binding'
     * By default no one is permit but it is overridable in ApiController
     *
     * Example:
     *```
     * protected $allowedModelBindings = array('default', 'frontend', 'minimum');
     * ```
     *
     * and call GET /objects/:name?binding=minimum
     *
     * @var array
     */
    protected $allowedModelBindings = array();

    /**
     * Other endpoints specified in the frontend app
     * They will be merged with self::defaultEndPoints()
     *
     * @var array
     */
    protected $endPoints = array();

    /**
     * Endpoints blacklisted
     * Useful for blacklisting self::defaultEndPoints
     *
     * @var array
     */
    protected $blacklistEndPoints = array();

    /**
     * White list of object types that have to be mapped to endpoints
     * For example setting
     *
     * ```
     * $whitelistObjectTypes = array('document', 'event')`;
     * ```
     *
     * enable '/documents' and '/events' endpoints that filter objects respectively by document and event object type.
     *
     * @var array
     */
    protected $whitelistObjectTypes = array();

    /**
     * The response data for client
     *
     * @var array
     */
    protected $responseData = array();

    /**
     * If response has to be built automatically at the end of the action
     *
     * @see self::response() set autoResponse to false
     * @see self::route() if autoResponse is true call self::response()
     * @var boolean
     */
    protected $autoResponse = true;

    /**
     * Pagination options used to paginate objects
     * Default values are
     *
     *  ```
     * 'page' => 1, // the page to load
     * 'pageSize' => 20, // the dimension of the page
     * 'maxPageSize' => 100 // the max page dimension in a request
     * ```
     *
     * If 'page' or 'page_size' are in query url then they override those default
     *
     * @var array
     */
    protected $paginationOptions = array(
        'page' => 1,
        'pageSize' => 20,
        'maxPageSize' => 100
    );

    /**
     * The POST data in request
     *
     * @var array
     */
    private $postData = array();

    /**
     * An array of filter to apply to objects
     *
     * @var array
     */
    protected $objectsFilter = array();

    /**
     * The request method invoked (get, post, put, delete)
     *
     * @var string
     */
    protected $requestMethod = null;

    /**
     * The complete base url for API
     * i.e. https://example.com/api/v1
     * It is filled the first time self::baseUrl() is called
     *
     * @var string
     */
    private $fullApiBaseUrl = null;

    /**
     * The allowed url path you can apply to /objects endpoint.
     * The url path is divided by request type 'get', 'post', 'put' and 'delete'
     *
     * For example GET /objects/1/children search the children of object with id = 1
     *
     * Override in ApiController to limit or add functionality to /objects endpoint
     * For example adding to 'get' array 'foo' filter and adding ApiController::getObjectsFoo() you can call /objects/1/foo
     *
     * All filters must have a corresponding class method built as self::requestMethod + Objects + filter camelized, for example:
     * - getObjectsChildren() maps $allowedObjectsUrlPath['get']['children']
     * - postObjectsRelations() maps $allowedObjectsUrlPath['post']['relations']
     *
     * @var array
     */
    protected $allowedObjectsUrlPath = array(
        'get' => array(
            'relations',
            'children',
            'contents',
            'sections',
            'descendants',
            'siblings',
            //'ancestors',
            //'parents'
        ),
        'post' => array(
            'relations',
            'children'
        ),
        'put' => array(
            'relations',
            'children'
        ),
        'delete' => array(
            'relations',
            'children'
        )
    );

    /**
     * The default supported url query string parameters names for every endpoint
     * It's an array as
     *
     * ```
     * array(
     *     'endpoint_1' => array('name_one'),
     *     'endpoint_2' => array('name_one', 'name_two'),
     *     ...
     * )
     * ```
     *
     * keys starting with '_' are special words that defines groups of string names to reuse in endpoints i.e.
     *
     * ```
     * array(
     *     '_groupOne' => array('name1', 'name2')
     *     'endpoint_1' => array('name_one', '_groupOne'), // it's like array('name_one', 'name1', 'name2')
     *     'endpoint_2' => array('_groupOne') // it's like array('name1', 'name2')
     * )
     * ```
     *
     * Key '__all' it's a special key that contains query string names valid for every endpoint and every request method.
     * Other endpoints params are only valid for GET requests.
     *
     * @var array
     */
    private $defaultAllowedUrlParams = array(
        '__all' => array('access_token'),
        '_pagination' => array('page', 'page_size'),
        'objects' => array('id', 'filter[object_type]', 'filter[substring]', 'filter[query]', 'embed[relations]', '_pagination', 'lang'),
        'posters' => array('id', 'width', 'height', 'mode')
    );

    /**
     * Other supported query string parameters names for every endpoint.
     * Override it according to your needs.
     *
     * @see self::$defaultAllowedUrlParams to the right format
     * @var array
     */
    protected $allowedUrlParams = array();

    /**
     * Constructor
     *
     * - Add auth component (default 'ApiAuth') to self::$components
     * - Setup endpoints available:
     *  - Merge self::defaultEndPoints, self::endPoints
     *  - Add to endpoints object types whitelisted
     *  - remove blacklisted endpoints (self::blacklistEndPoints)
     */
    public function __construct() {
        Configure::write('Session.start', false);
        $authComponent = Configure::read('api.auth.component');
        if (empty($authComponent)) {
            $authComponent = 'ApiAuth';
        }
        $this->components[] = $authComponent;
        parent::__construct();
        $this->endPoints = array_unique(array_merge($this->defaultEndPoints, $this->endPoints));
        $objectTypeQueryString = array_diff($this->defaultAllowedUrlParams['objects'], array('filter[object_type]'));
        $objectTypes = Configure::read('objectTypes');
        foreach ($objectTypes as $key => $value) {
            if (is_numeric($key) && in_array($value['name'], $this->whitelistObjectTypes)) {
                $objectTypeEndPoint = Inflector::pluralize($value['name']);
                $this->endPoints[] = $objectTypeEndPoint;
                $this->defaultAllowedUrlParams[$objectTypeEndPoint] = $objectTypeQueryString;
            }
        }
        $this->endPoints = array_diff($this->endPoints, $this->blacklistEndPoints);

        // for backward compatibility with 3.6.0
        if (!empty($this->allowedObjectsFilter)) {
            $this->$allowedObjectsUrlPath = $this->allowedObjectsFilter;
        }
    }

    /**
     * Enables calling methods for object types as /documents, /events, etc... delegating the action to self::objects()
     *
     * @param string $method name of the method to be invoked
     * @param array $arguments list of arguments passed to the function
     * @return mixed
     */
    public function __call($method, $arguments) {
        $objectType = Configure::read('objectTypes.' . Inflector::singularize($method));
        if (!empty($objectType) && $this->requestMethod == 'get') {
            $this->objectsFilter['object_type_id'] = $objectType['id'];
            return call_user_func_array(array($this, $this->requestMethod . 'Objects'), $arguments);
        }

        throw new BeditaMethodNotAllowedException();
    }

    /**
     * Return the HTTP verb of the request
     *
     * @return string
     */
    public function getRequestMethod() {
        return $this->requestMethod;
    }

    /**
     * Normalize POST/PUT data
     *
     * This function searches for POST/PUT data in the global var $_POST and in 'php://input' alias file
     * Some Javascript XHR wrappers POSTs, PUTs data are passed through 'php://input'
     * If CONTENT_TYPE in request headers is 'application/x-www-form-urlencoded' then it parses string
     * else it tries to json encode string
     *
     * @return array
     */
    private function handleInputData() {
        if (!empty($this->params['form'])) {
            return;
        }

        $contentType = env('CONTENT_TYPE');
        if (strpos($contentType, 'application/x-www-form-urlencoded') === false
            && strpos($contentType, 'application/json') === false) {
            return;
        }

        try {
            $inputData = file_get_contents('php://input');
            if (strpos($contentType, 'application/x-www-form-urlencoded') !== false) {
                parse_str($inputData, $this->params['form']);
            } else {
                $this->params['form'] = json_decode($inputData, true);
                $jsonError = json_last_error();
                if (!empty($jsonError)) {
                    $this->params['form'] = array();
                }
            }
        } catch (Exception $ex) {
            $this->params['form'] = array();
        }
        // set self::data
        if (!empty($this->params['form']['data'])) {
            $this->data = $this->params['form']['data'];
            unset($this->params['form']['data']);
        }
    }

    /**
     * Return the current `$paginationOptions`
     *
     * @return array
     */
    public function getPagination() {
        return $this->paginationOptions;
    }

    /**
     * Setup the pagination options self:paginationOptions
     * Merging default with query url params
     *
     * @return void
     */
    private function setupPagination() {
        $paramsUrl = $this->params['url'];
        if (isset($paramsUrl['page'])) {
            // check that 'page' is positive integer
            $intVal = (int) $paramsUrl['page'];
            $floatVal = (float) $paramsUrl['page'];
            if (!is_numeric($paramsUrl['page']) || $paramsUrl['page'] < 1 || $intVal != $floatVal) {
                throw new BeditaBadRequestException('page param must be a positive integer');
            }
            $this->paginationOptions['page'] = (int) $paramsUrl['page'];
        }

        if (isset($paramsUrl['page_size'])) {
            // check that 'page_size' is positive integer
            $intVal = (int) $paramsUrl['page_size'];
            $floatVal = (float) $paramsUrl['page_size'];
            if (!is_numeric($paramsUrl['page_size']) || $paramsUrl['page_size'] < 1 || $intVal != $floatVal) {
                throw new BeditaBadRequestException('page_size param must be a positive integer');
            }
            $this->paginationOptions['pageSize'] = (int) $paramsUrl['page_size'];
        }
        if ($this->paginationOptions['pageSize'] > $this->paginationOptions['maxPageSize']) {
            throw new BeditaBadRequestException('Max page_size supported is ' . $this->paginationOptions['maxPageSize']);
        }
        $this->paginationOptions['dim'] = $this->paginationOptions['pageSize'];
    }

    /**
     * Common operations that every call must do:
     *
     * - setup auth component
     * - check origin
     * - setup self::requestMethod to http verb used
     * - normalize post data
     *
     * If method is overridden in frontend ApiController remember to call parent::beforeCheckLogin()
     *
     * @return void
     */
    protected function beforeCheckLogin() {
        $this->setupAuthComponent();
        $this->setupValidatorComponent();
        // Cross origin check.
        $this->checkOrigin();

        $this->ResponseHandler->sendHeader('Access-Control-Allow-Methods', "POST, GET, PUT, DELETE, OPTIONS, HEAD");
        $acrh = env('HTTP_ACCESS_CONTROL_REQUEST_HEADERS');
        if (!$acrh && function_exists('getallheaders')) {
            $headers = getallheaders();
            if (!empty($headers['Access-Control-Request-Headers'])) {
                $acrh = $headers['Access-Control-Request-Headers'];
            }
        }
        if (!empty($acrh)) {
            $this->ResponseHandler->sendHeader('Access-Control-Allow-Headers', $acrh);
        }

        $this->requestMethod = strtolower(env('REQUEST_METHOD'));
        if ($this->requestMethod == 'post' || $this->requestMethod == 'put') {
            $this->handleInputData();
        } elseif ($this->requestMethod == 'options' || $this->requestMethod == 'head') {
            $this->_stop();
        }

        $this->setupPagination();
        $this->ApiValidator->registerAllowedUrlParams($this->defaultAllowedUrlParams);
        $this->ApiValidator->registerAllowedUrlParams($this->allowedUrlParams);
    }

    /**
     * Override FrontendController::checkLogin()
     *
     * @return mixed
     */
    protected function checkLogin() {
        if ($this->ApiAuth->identify()) {
            $this->logged = true;

            return;
        }

        // allow POST /auth also with `api.protected === true`
        if ($this->params['url']['url'] === 'auth' && $this->requestMethod === 'post') {
            return;
        }

        if (Configure::read('api.protected')) {
            throw new BeditaUnauthorizedException();
        }
    }

    /**
     * Override FrontendController::checkPublicationPermissions()
     *
     * Return true if the publication is authorized for user
     * Return null if client is trying to authenticate via `POST /auth`
     *
     * @throws BeditaUnauthorizedException
     * @throws BeditaForbiddenException
     * @return mixed
     */
    protected function checkPublicationPermissions() {
        if ($this->publication['authorized']) {
            return true;
        }
        if (!empty($this->params['pass']) && $this->params['pass']['0'] == 'auth' && $this->requestMethod == 'post' && in_array('auth', $this->endPoints)) {
            return null;
        }

        if (!$this->ApiAuth->identify()) {
            throw new BeditaUnauthorizedException();
        }
        throw new BeditaForbiddenException();
    }

    /**
     * Setup component used for authentication:
     *
     * - check configuration (api.auth.component) to see if adhoc component should be used and assign it to self::$ApiAuth
     * - replace self::BeAuth with self::ApiAuth to work properly in FrontendController.
     *   BeAuthComponent is not used in API context. JWT is usually used instead via ApiAuthComponent
     *
     * @return void
     */
    private function setupAuthComponent() {
        $componentName = Configure::read('api.auth.component');
        if (!empty($componentName) && $componentName != 'ApiAuth' && !empty($this->{$componentName})) {
            $this->ApiAuth = &$this->{$componentName};
        }
        if (empty($this->ApiAuth)) {
            throw new BeditaInternalErrorException('API auth component is not properly loaded in API controller');
        }
        $this->BeAuth = &$this->ApiAuth;
    }

    /**
     * Setup component used for validation:
     *
     * - check configuration (api.validator.component) to see if adhoc component should be used and assign it to self::$ApiValidator
     *
     * @return void
     */
    private function setupValidatorComponent() {
        $componentName = Configure::read('api.validator.component');
        if (!empty($componentName) && $componentName != 'ApiValidator' && !empty($this->{$componentName})) {
            $this->ApiValidator = &$this->{$componentName};
        }
        if (empty($this->ApiValidator)) {
            throw new BeditaInternalErrorException('API validator component is not properly loaded in API controller');
        }
    }

    /**
     * Setup component used for format response and request data:
     *
     * - check configuration (api.formatter.component) to see if adhoc component should be used and assign it to `self::$ApiFormatter`
     *
     * @return void
     */
    private function setupFormatterComponent() {
        $componentName = Configure::read('api.formatter.component');
        if (!empty($componentName) && $componentName != 'ApiFormatter' && !empty($this->{$componentName})) {
            $this->ApiFormatter = &$this->{$componentName};
        }
        if (empty($this->ApiFormatter)) {
            throw new BeditaInternalErrorException('API formatter component is not properly loaded in API controller');
        }
    }

    /**
     * Set common meta data for response
     * Meta data are:
     *  - url
     *  - params
     *  - api
     */
    private function setBaseResponse() {
        $this->responseData['url'] = Router::url('/', true) . $this->params['url']['url'];
        $urlParams = array_slice($this->params['url'], 1);
        $getParams = array_slice($_GET, 0);
        unset($getParams['url']);
        $this->responseData['params'] = array_merge($urlParams, $this->params['named'], $getParams);
        $this->responseData['api'] = $this->action;
        $this->responseData['method'] = $this->requestMethod;
    }

    /**
     * set self::responseData['data'] array used as output data by self::response()
     *
     * @param array $data
     * @param boolean $merge true if $data has to be merged with previous set
     * @return void
     */
    protected function setData(array $data = array(), $merge = false) {
        $this->responseData['data'] = ($merge && isset($this->responseData['data'])) ? array_merge($this->responseData['data'], $data) : $data;
    }

    /**
     * set self::responseData['paging'] array used by self::response() to output pagination data
     *
     * @param array $paginationData
     * @return void
     */
    protected function setPaging(array $paginationData) {
        $this->responseData['paging'] = $paginationData;
    }

    /**
     * Any Api request has to pass from this method (see frontend app routes.php)
     * Override FrontendController::route()
     *
     * The method checks for valid api endpoints and call method or fallback to self::__call()
     *
     * @return void
     */
    public function route() {
        $args = func_get_args();
        $name = array_shift($args);
        // generic methodName
        $methodName = str_replace('.', '_', $name);
        if (!empty($methodName)) {
            // avoid to call methods that aren't endpoints
            if (!in_array($methodName, $this->endPoints)) {
                $this->action = $methodName;
                throw new BeditaMethodNotAllowedException();
            } else {
                $this->ApiValidator->checkUrlParams($methodName);
                $this->action = $methodName;
                $specificMethodName = Inflector::camelize($this->requestMethod . '_' . $methodName);
                if (method_exists($this, $specificMethodName)) {
                    call_user_func_array(array($this, $specificMethodName), $args);
                } else {
                    call_user_func_array(array($this, $methodName), $args);
                }
            }
        } else {
            $this->baseUrlResponse();
            return $this->response(array('setBase' => false));
        }

        if ($this->autoResponse) {
            $this->response();
        }
    }

    /**
     * Return the full or partial API base url
     * If $full is true set self::fullApiBaseUrl too and reuse it for the next time
     *
     * @param boolean $full if the url should be complete or partial
     * @return string
     */
    public function baseUrl($full = true) {
        if (!$full) {
            return Configure::read('api.baseUrl');
        }
        if (!$this->fullApiBaseUrl) {
            $baseUrl = Configure::read('api.baseUrl');
            $url = Router::url($baseUrl, true);
            $this->fullApiBaseUrl = trim($url, '/');
        }
        return $this->fullApiBaseUrl;
    }

    /**
     * prepare response data for base api url
     *
     * default response: show list of available endpoints with urls
     * override in subclasses for custom response
     */
    protected function baseUrlResponse() {
        foreach ($this->endPoints as $endPoint) {
            $this->responseData[$endPoint] = $this->baseUrl() . '/' . $endPoint;
        }
    }

    /**
     * setup self::$objectsFilter from url params
     *
     * @return void
     */
    protected function setupObjectsFilter() {
        $urlParams = $this->ApiFormatter->formatUrlParams();
        if (!empty($urlParams['filter'])) {
            $this->objectsFilter = array_merge($this->objectsFilter, $urlParams['filter']);
        }
    }

    /**
     * Set and return the related objects filter.
     *
     * Since the filter is used both in `BEAppModel::findObjects()` than in `Model::find()`
     * the `$conditions` must be written in CakePHP way to ensure compatibility with both methods.
     *
     * Since is also used to count relations and the count conditions are limited to `BEObject`
     * that filter must be limited to that.
     *
     * If no param is passed it returns the current filter.
     * Pass an empty array to empty the filter.
     *
     * @see self::getObjectsRelations()
     * @see self::addRelatedObjects()
     * @see ApiFormatter::formatRelationsCount()
     * @param array|null $conditions The conditions used to set filter.
     * @return array
     */
    public function relatedObjectsFilter($conditions = null) {
        static $relatedFilter = array();

        if (!is_array($conditions)) {
            return $relatedFilter;
        }

        $relatedFilter = $conditions;
        return $relatedFilter;
    }

    /**
     * Set and return the children objects filter.
     *
     * Since the filter is used both in `BEAppModel::findObjects()` than in `Model::find()`
     * the `$conditions` must be written in CakePHP way to ensure compatibility with both methods.
     *
     * Since is also used to count children and the count conditions are limited to `BEObject`
     * that filter must be limited to that.
     *
     * If no param is passed it returns the current filter.
     * Pass an empty array to empty the filter.
     *
     * @see self::responseChildren()
     * @see ApiFormatter::formatChildrenCount()
     * @param array|null $conditions The conditions used to set filter.
     * @return array
     */
    public function childrenFilter($conditions = null) {
        static $childrenFilter = array();

        if (!is_array($conditions)) {
            return $childrenFilter;
        }

        $childrenFilter = $conditions;
        return $childrenFilter;
    }

    /**
     * Setup locale settings - nothing to set, for api
     * override FrontendController::setupLocale
     * override AppController::setupLocale
     *
     * @see FrontendController::setupLocale()
     * @see AppController::setupLocale()
     */
    protected function setupLocale() {
        $this->setupFormatterComponent();
        $urlParams = $this->ApiFormatter->formatUrlParams();
        if (!empty($urlParams['lang'])) {
            $conf = Configure::getInstance();
            if (array_key_exists($urlParams['lang'], $conf->frontendLangs)) {
                $this->currLang = $urlParams['lang'];
            }
        }
    }

    /**
     * GET /objects
     *
     * If $name is passed try to load an object with that id or nickname
     *
     * @param int|string $name an object id or nickname
     * @param string $filterType can be a value between those defined in self::allowedObjectsUrlPath['get']
     * @return void
     */
    protected function getObjects($name = null, $filterType = null) {
        $this->setupObjectsFilter();
        $urlParams = $this->ApiFormatter->formatUrlParams();
        if (!empty($name)) {
            // GET /objects/:id supports only 'embed', '__all' and 'lang' params
            if (empty($filterType)) {
                $this->ApiValidator->setAllowedUrlParams('objects', array('embed[relations]', 'lang', '__all'), false);
                if (!$this->ApiValidator->isUrlParamsValid('objects')) {
                    $validParams = implode(', ', $this->ApiValidator->getAllowedUrlParams('objects'));
                    throw new BeditaBadRequestException(
                        'GET /objects/:id supports url params: ' . $validParams
                    );
                }
            }
            // GET /objects/:id/$filterType?id=x not valid
            if (array_key_exists('id', $this->params['url'])) {
                throw new BeditaBadRequestException(
                    'GET /objects/:id/' . $filterType . ' does not support url params: id'
                );
            }
            // check embed[relations] params
            if (!empty($urlParams['embed']['relations'])) {
                $this->ApiValidator->checkEmbedRelations(
                    $urlParams['embed']['relations'],
                    1,
                    $this->paginationOptions['maxPageSize']
                );
            }
            $id = is_numeric($name) ? $name : $this->BEObject->getIdFromNickname($name);
            $this->ApiValidator->checkObjectReachable($id);
            if (!empty($filterType)) {
                $args = func_get_args();
                $args[0] = $id;
                call_user_func_array(array($this, 'routeObjectsFilterType'), $args);

                if (!empty($urlParams['embed']['relations']) && !empty($this->responseData['data']['objects'])) {
                    foreach ($this->responseData['data']['objects'] as &$o) {
                        $o = $this->addRelatedObjects($o, $urlParams['embed']['relations']);
                    }
                }
            } else {
                $options = array('explodeRelations' => false);
                if (!empty($this->params['url']['binding']) && in_array($this->params['url']['binding'], $this->allowedModelBindings)) {
                    $options['bindingLevel'] = $this->params['url']['binding'];
                }
                $object = $this->loadObj($id, true, $options);
                if ($object == parent::UNLOGGED) {
                    throw new BeditaUnauthorizedException();
                }
                if ($object == parent::UNAUTHORIZED) {
                    throw new BeditaForbiddenException();
                }
                // check if id corresponds to object type requested (if any)
                if (!empty($this->objectsFilter['object_type_id']) && $object['object_type_id'] != $this->objectsFilter['object_type_id']) {
                    throw new BeditaNotFoundException('Object type mismatch');
                }

                $object = $this->ApiFormatter->formatObject(
                    $object,
                    array('countRelations' => true, 'countChildren' => true)
                );
                if (!empty($urlParams['embed']['relations'])) {
                    $object['object'] = $this->addRelatedObjects($object['object'], $urlParams['embed']['relations']);
                }
                $this->setData($object);
            }
        } else {
            // get list of object ids (check reachability)
            if (!empty($urlParams['id'])) {
                $this->ApiValidator->setAllowedUrlParams('objects', array('id', 'embed[relations]', '__all'), false);
                if (!$this->ApiValidator->isUrlParamsValid('objects')) {
                    $validParams = implode(', ', $this->ApiValidator->getAllowedUrlParams('__all'));
                    throw new BeditaBadRequestException(
                        'GET /objects?id=xx,yy,... supports only these other url params: ' . $validParams
                    );
                }
                $ids = is_array($urlParams['id']) ? $urlParams['id'] : array($urlParams['id']);
                if (count($ids) > $this->paginationOptions['maxPageSize']) {
                    throw new BeditaBadRequestException('Too objects requested. Max is ' . $this->paginationOptions['maxPageSize']);
                }
                // check embed[relations] params
                if (!empty($urlParams['embed']['relations'])) {
                    $this->ApiValidator->checkEmbedRelations(
                        $urlParams['embed']['relations'],
                        count($ids),
                        $this->paginationOptions['maxPageSize']
                    );
                }
                $objects = array();
                foreach ($ids as $id) {
                    $this->ApiValidator->checkObjectReachable($id);
                    $objects[] = $this->loadObj($id, true, array('explodeRelations' => false));
                }
                $objects = $this->ApiFormatter->formatObjects(
                    $objects,
                    array('countRelations' => true, 'countChildren' => true)
                );
                if (!empty($urlParams['embed']['relations'])) {
                    foreach ($objects['objects'] as &$o) {
                        $o = $this->addRelatedObjects($o, $urlParams['embed']['relations']);
                    }
                }
                $this->setData($objects);
            // list of publication descendants
            } else {
                // check embed[relations] params
                if (!empty($urlParams['embed']['relations'])) {
                    $this->ApiValidator->checkEmbedRelations(
                        $urlParams['embed']['relations'],
                        $this->paginationOptions['pageSize'],
                        $this->paginationOptions['maxPageSize']
                    );
                }
                $publication = $this->getPublication();
                $this->responseChildren($publication['id'], array(
                    'filter' => array('descendants' => true)
                ));
            }
        }
    }

    /**
     * Add related objects to $object
     * The $relations is an array that contains info
     * about the number of objects to get for each relation
     * For example
     *
     * ```
     * array(
     *     'attach' => 5,
     *     'seealso' => 2,
     *     'poster' => 1
     * )
     * ```
     *
     * @param array $object the object
     * @param array $relations the relations info
     * @return array
     */
    protected function addRelatedObjects(array $object, array $relations) {
        foreach ($relations as $relName => $dim) {
            if (!empty($object['object_type']) && $this->ApiValidator->isRelationValid($relName, $object['object_type'])) {
                $relObj = $this->loadRelatedObjects($object['id'], $relName, array(
                    'dim' => $dim,
                    'filter' => $this->relatedObjectsFilter()
                ));
                if (!empty($relObj['items'])) {
                    $this->loadRelationParams($relObj['items'], $object['id'], $relName);
                    $relObjs = $this->ApiFormatter->formatObjects(
                        $relObj['items'],
                        array('countRelations' => true, 'countChildren' => true)
                    );
                    $object['relations'][$relName]['objects'] = $relObjs['objects'];
                }
            }
        }
        return $object;
    }

    /**
     * Load available relation params for a list of related objects.
     * 
     * @param array $items List of related objects.
     * @param int $objectId ID of object to consider as starting point for relation.
     * @param string $relName Relation name.
     * @return void
     */
    protected function loadRelationParams(array &$items, $objectId, $relName)
    {
        $ids = Set::classicExtract($items, '{n}.id');
        $params = ClassRegistry::init('ObjectRelation')->find('list', array(
            'fields' => array('ObjectRelation.object_id', 'ObjectRelation.params'),
            'conditions' => array(
                'ObjectRelation.id' => $objectId,
                'ObjectRelation.switch' => $relName,
                'ObjectRelation.object_id' => $ids,
            ),
        ));

        foreach ($items as &$item) {
            if (!array_key_exists($item['id'], $params)) {
                continue;
            }

            $item['meta']['relation_params'] = $params[$item['id']] ?: new stdClass();
        }
    }

    /**
     * Route calls made by /objects endpoint using $filterType and request method self::requestMethod
     *
     * @see self:objects() for param description
     * @param int $id
     * @param string $filterType
     * @return void
     */
    private function routeObjectsFilterType($id, $filterType) {
        if (empty($this->allowedObjectsUrlPath[$this->requestMethod])) {
            throw new BeditaMethodNotAllowedException();
        }
        $allowedFilterTypes = $this->allowedObjectsUrlPath[$this->requestMethod];
        if (!in_array($filterType, $allowedFilterTypes)) {
            $allowedFilter = implode(', ', $allowedFilterTypes);
            throw new BeditaBadRequestException($filterType . ' not valid. Valid options are: ' . $allowedFilter);
        }
        $method = $this->requestMethod . 'Objects' . Inflector::camelize($filterType);
        $args = func_get_args();
        unset($args[1]);

        return call_user_func_array(array($this, $method), $args);
    }

    /**
     * POST /objects
     *
     * @param int|string $name the object id or nickname
     * @param string $filterType can be a value between those defined in self::allowedObjectsUrlPath['post']
     * @return void
     */
    protected function postObjects($name = null, $filterType = null) {
        if (!$this->ApiAuth->identify()) {
            throw new BeditaUnauthorizedException();
        }

        if (empty($this->data)) {
            throw new BeditaBadRequestException('Missing data to save');
        }

        if (!empty($name)) {
            if (func_num_args() == 1) {
                throw new BeditaMethodNotAllowedException('POST /objects/:id is not supported');
            }
            $id = is_numeric($name) ? $name : $this->BEObject->getIdFromNickname($name);
            $this->ApiValidator->checkObjectReachable($id);
            $args = func_get_args();
            $args[0] = $id;
            call_user_func_array(array($this, 'routeObjectsFilterType'), $args);
            return;
        }

        $isNew = (empty($this->data['id'])) ? true : false;
        if ($isNew) {
            if (empty($this->data['object_type'])) {
                throw new BeditaBadRequestException('Missing object_type');
            }
            $confType = $this->data['object_type'];

            if (array_key_exists('upload_token', $this->data)) {
                $uploadToken = $this->data['upload_token'];
                unset($this->data['upload_token']);
                $this->data = array_merge(
                    $this->data,
                    $this->ApiUpload->uploadedFileData($uploadToken, $confType)
                );
            }
        } else {
            $confType = $this->BEObject->findObjectTypeId($this->data['id']);
        }

        $objectTypeConf = Configure::read('objectTypes.' . $confType);
        if (empty($objectTypeConf)) {
            throw new BeditaBadRequestException('Invalid object type');
        }
        $objectModel = $this->loadModelByType($objectTypeConf['model']);

        $this->Transaction->begin();
        $this->saveObject($objectModel);
        $savedObjectId = $objectModel->id;
        if (isset($uploadToken) && !$this->ApiUpload->removeToken($uploadToken)) {
            throw new BeditaInternalErrorException('Error removing upload token');
        }
        $this->Transaction->commit();

        $this->getObjects($savedObjectId);
        if ($isNew) {
            $this->ResponseHandler->sendStatus(201);
            $this->ResponseHandler->sendHeader('Location', $this->baseUrl() . '/objects/' . $savedObjectId);
        }
    }

    /**
     * PUT /objects/:id
     * PUT of entire object is not allowed. If you want modify an object you should use POST
     *
     * @param int|string $name the object id or nickname
     * @param string $filterType can be a value between those defined in self::allowedObjectsUrlPath['put']
     * @return void
     */
    protected function putObjects($name = null, $filterType = null) {
        if (!$this->ApiAuth->identify()) {
            throw new BeditaUnauthorizedException();
        }
        if (empty($name) || empty($filterType)) {
            throw new BeditaBadRequestException();
        }
        $id = is_numeric($name) ? $name : $this->BEObject->getIdFromNickname($name);
        $this->ApiValidator->checkObjectReachable($id);
        $args = func_get_args();
        $args[0] = $id;
        call_user_func_array(array($this, 'routeObjectsFilterType'), $args);
    }

    /**
     * DELETE /objects/:id
     *
     * @param int|string $name
     * @param string $filterType can be a value between those defined in self::allowedObjectsUrlPath['delete']
     * @return void
     */
    protected function deleteObjects($name = null, $filterType = null) {
        if (!$this->ApiAuth->identify()) {
            throw new BeditaUnauthorizedException();
        }
        if (empty($name)) {
            throw new BeditaMethodNotAllowedException('Unsupported endpoint for DELETE request. It should be /objects/:id');
        }
        if (!empty($this->params['form']) || !empty($this->data)) {
            throw new BeditaBadRequestException('DELETE do not support input data');
        }
        $id = is_numeric($name) ? $name : $this->BEObject->getIdFromNickname($name);
        $this->ApiValidator->checkObjectReachable($id);
        // delete object
        if (empty($filterType)) {
            $modelName = $this->BEObject->getType($id);
            $this->data['id'] = $id;
            parent::deleteObjects($modelName);
            $this->emptyResponse();
        } else {
            $args = func_get_args();
            $args[0] = $id;
            call_user_func_array(array($this, 'routeObjectsFilterType'), $args);
        }
    }

    /**
     * Override AppController::saveObject()
     *
     * - set default $options different from AppController::saveObject()
     * - set additional data (status, user_created, user_modified, object_type_id,...)
     * - check object data through ApiValidator
     * - format object data through ApiFormatter
     * - save object using parent::saveObject()
     * - save parents in case (remove old parents and add new one)
     * - save relations in case
     *
     * @param BEAppModel $beModel
     * @param array $options
     * @return void
     */
    protected function saveObject(BEAppModel $beModel, array $options = array()) {
        $user = $this->ApiAuth->identify();
        if (!$user) {
            throw new BeditaUnauthorizedException();
        }
        $options += array(
            'handleTagList' => false,
            'emptyPermission' => false,
            'saveTree' => false
        );

        if (empty($this->data['object_type_id'])) {
            if (empty($this->data['object_type'])) {
                if (empty($this->data['id'])) {
                    throw new BeditaBadRequestException('Missing object type or it can not be retrieved');
                }
                $this->data['object_type_id'] = $this->BEObject->findObjectTypeId($this->data['id']);
            } else {
                $this->data['object_type_id'] = Configure::read('objectTypes.' . $this->data['object_type'] . '.id');
            }
        }

        $objectType = Configure::read('objectTypes.' . $this->data['object_type_id'] . '.name');

        $this->data['status'] = 'on';
        if (empty($this->data['id'])) {
            $this->data['user_created'] = $user['id'];
        }
        $this->data['user_modified'] = $user['id'];

        // validate and format data for save
        $this->ApiValidator->checkObject($this->data);
        $this->data = $this->ApiFormatter->formatObjectForSave($this->data);

        // #883 skip tree update when saving section
        if ($objectType == 'section') {
            $this->data['skipTreeUpdate'] = true;
        }

        parent::saveObject($beModel, $options);

        // save parents
        if (!empty($this->data['parents'])) {
            $tree = ClassRegistry::init('Tree');
            $tree->updateTree(
                $beModel->id,
                $this->data['parents'],
                array(
                    'area_id' => $this->publication['id'],
                    'status' => $this->getStatus()
                )
            );

            if ($objectType == 'section') {
                $menu = (isset($this->data[$this->name]['menu']) && $this->data[$this->name]['menu'] == 0) ? 0 : 1;
                $tree->saveMenuVisibility($beModel->id, $this->data['parents'][0], $menu);
            }

            $this->BEObject->clearCacheByIds($this->data['parents']);
        }

        // save custom properties
        if (!empty($this->data['custom_properties'])) {
            $propertyIds = Set::extract('/property_id', $this->data['custom_properties']);
            // delete previous custom properties
            $delRes = $this->BEObject->ObjectProperty->deleteAll(array(
                'property_id' => $propertyIds,
                'object_id' => $beModel->id
            ));
            if (!$delRes) {
                throw BeditaInternalErrorException('Error saving custom properties');
            }
            foreach ($this->data['custom_properties'] as $customProp) {
                // save not null custom properties
                if ($customProp['property_value'] !== null) {
                    $customProp['object_id'] = $beModel->id;
                    $this->BEObject->ObjectProperty->create();
                    if (!$this->BEObject->ObjectProperty->save($customProp)) {
                        throw new BeditaInternalErrorException('Error saving custom property ' . $customProp['property_id']);
                    }
                }
            }
        }
    }

    /**
     * Save relations $relationName between $objectId and related objects in $this->data
     *
     * If you want to save only one relation $this->data should be
     * ```
     * array(
     *     'related_id' => 10, // required
     *     'priority' => 1, // optional
     *     'params' => array() // optional
     * )
     * ```
     *
     * If you want to save many relations $this->data should be
     * ```
     * array(
     *     array(
     *         'related_id' => 10, // required
     *         'priority' => 1, // optional
     *         'params' => array() // optional
     *     ),
     *     array(...)
     * )
     * ```
     *
     * @see ApiValidatorComponent::checkRelations()
     * @param int $objectId the main object id
     * @param string $relationName the relation name (direct or inverse)
     * @return void
     */
    protected function postObjectsRelations($objectId, $relationName) {
        if (func_num_args() > 2) {
            throw new BeditaBadRequestException();
        }
        $objectTypeId = $this->BEObject->findObjectTypeId($objectId);
        $this->data = isset($this->data[0]) ? $this->data : array($this->data);
        $this->ApiValidator->checkRelations(
            array($relationName => $this->data),
            $objectTypeId
        );
        $objectRelation = ClassRegistry::init('ObjectRelation');
        $inverseName = $objectRelation->inverseOf($relationName);
        $created = false;
        $responseData = array();
        $this->Transaction->begin();
        foreach ($this->data as $relData) {
            $exists = $objectRelation->relationExists($objectId, $relData['related_id'], $relationName);
            // create
            if (!$exists) {
                $params = isset($relData['params']) ? $relData['params'] : array();
                $priority = isset($relData['priority']) ? $relData['priority'] : null;
                $result = $objectRelation->createRelationAndInverse($objectId, $relData['related_id'], $relationName, $inverseName, $priority, $params);
                if ($result === false) {
                    throw new BeditaInternalErrorException(
                        'Error saving relation ' . $relationName . ' between ' . $objectId . ' and ' . $relData['related_id']
                    );
                }
                $created = true;
            // update
            } else {
                // update direct (params and priority) and inverse (only params) relation
                $set = array();
                if (array_key_exists('params', $relData)) {
                    $set['params']  = $relData['params'];
                }
                if (array_key_exists('priority', $relData)) {
                    $set['priority'] = $relData['priority'];
                }
                if (array_key_exists('params', $set) || array_key_exists('priority', $set)) {
                    $result = $objectRelation->updateRelation($objectId, $relData['related_id'], $relationName, $set);
                    if ($result === false) {
                        throw new BeditaInternalErrorException(
                            'Error updating relation ' . $relationName . ' between ' . $objectId . ' and ' . $relData['related_id']
                        );
                    }
                }
            }

            // get added/updated relations to build response for client
            $result = $objectRelation->find('first', array(
                'conditions' => array(
                    'id' => $objectId,
                    'object_id' => $relData['related_id'],
                    'switch' => $relationName
                )
            ));
            if (empty($result)) {
                throw new BeditaInternalErrorException(
                    'Error fetching relation ' . $relationName . ' between ' . $objectId . ' and ' . $relData['related_id']
                );
            }
            $d = array(
                'related_id' => (int) $result['ObjectRelation']['object_id'],
                'priority' => (int) $result['ObjectRelation']['priority']
            );
            if (!empty($result['ObjectRelation']['params'])) {
                $d['params'] = $result['ObjectRelation']['params'];
            }
            $responseData[] = $d;
        }
        $this->Transaction->commit();
        if ($created) {
            $this->ResponseHandler->sendStatus(201);
            $this->ResponseHandler->sendHeader('Location', $this->baseUrl() . '/objects/' . $objectId .'/relations/' . $relationName);
        }
        $this->setData($responseData);
    }

    /**
     * Save (insert or update) children ($this->data) of $objectId
     *
     * If you want to save only one child $this->data should be
     * ```
     * array(
     *     'child_id' => 10,
     *     'priority' => 1
     * )
     * ```
     *
     * If you want to save children $this->data should be
     * ```
     * array(
     *     array(
     *         'child_id' => 10,
     *         'priority' => 1
     *     ),
     *     array(...)
     * )
     * ```
     *
     * @see ApiValidatorComponent::checkChildren() to see the right format
     * @param int $objectId the object id
     * @return void
     */
    protected function postObjectsChildren($objectId) {
        if (func_num_args() > 1) {
            throw new BeditaBadRequestException();
        }
        $this->data = isset($this->data[0]) ? $this->data : array($this->data);
        $this->ApiValidator->checkChildren($this->data, $objectId);
        // append children
        $this->Transaction->begin();
        $tree = ClassRegistry::init('Tree');
        $created = false;
        $responseData = array();
        foreach ($this->data as $key => $child) {
            $row = $tree->find('first', array(
                'conditions' => array(
                    'parent_id' => $objectId,
                    'id' => $child['child_id']
                )
            ));
            // append child (insert)
            if (empty($row)) {
                $priority = !empty($child['priority']) ? $child['priority'] : null;
                if (!$tree->appendChild($child['child_id'], $objectId, $priority)) {
                    throw new BeditaInternalErrorException(
                        'Error appending ' . $child['child_id'] . ' to ' . $objectId,
                        $tree->validationErrors
                    );
                }
                $created = true;
            // update priority if any and different from current value
            } elseif (!empty($child['priority']) && $child['priority'] != $row['Tree']['priority']) {
                $row['Tree']['priority'] = $child['priority'];
                if (!$tree->save($row)) {
                    throw new BeditaInternalErrorException('Error updating priority ' . $priority . ' for child ' . $child['child_id']);
                }
            }

            $this->BEObject->clearCacheByIds(array($child['child_id']));

            $d = array('child_id' => $child['child_id']);
            // get current priority to prepare response
            $d['priority'] = empty($child['priority']) ? $tree->getPriority($child['child_id'], $objectId) : $child['priority'];
            $d['priority'] = (int) $d['priority'];
            $responseData[] = $d;

        }
        $this->BEObject->clearCacheByIds(array($objectId));
        $this->Transaction->commit();
        if ($created) {
            $this->ResponseHandler->sendStatus(201);
            $this->ResponseHandler->sendHeader('Location', $this->baseUrl() . '/objects/' . $objectId .'/children');
        }
        $this->setData($responseData);
    }

    /**
     * Update relation $relationName between $objectId and $relatedId objects
     *
     * $this->data should be
     * ```
     * array(
     *     'priority' => 1,
     *     'params' => array()
     * )
     * ```
     *
     * If 'priority' or 'params' is not passed then they are set to null to update db field to NULL.
     * Indeed PUT replaces all relation data with new one
     *
     * @param int $objectId the main object id
     * @param string $relationName the relation name (direct or inverse)
     * @param int $relatedId the related object id
     * @return void
     */
    protected function putObjectsRelations($objectId, $relationName = null, $relatedId = null) {
        if (func_num_args() != 3) {
            throw new BeditaBadRequestException();
        }
        if (empty($this->data['priority']) && empty($this->data['params'])) {
            throw new BeditaBadRequestException('No data to use in PUT request');
        }
        $this->ApiValidator->checkPositiveInteger($relatedId, true);
        $this->data['related_id'] = (int) $relatedId;
        $objectTypeId = $this->BEObject->findObjectTypeId($objectId);
        $this->ApiValidator->checkRelations(
            array($relationName => array($this->data)),
            $objectTypeId
        );

        $objectRelation = ClassRegistry::init('ObjectRelation');
        $exists = $objectRelation->relationExists($objectId, $relatedId, $relationName);
        if (!$exists) {
            throw new BeditaBadRequestException('You can not modify a relation that not exists.');
        }

        // set default value to null if not defined
        if (empty($this->data['priority'])) {
            $this->data['priority'] = null;
        }
        if (empty($this->data['params'])) {
            $this->data['params'] = null;
        }

        $this->Transaction->begin();
        $result = $objectRelation->updateRelation($objectId, $relatedId, $relationName, $this->data);
        if ($result === false) {
            throw new BeditaInternalErrorException(
                'Error updating relation ' . $relationName . ' between ' . $objectId . ' and ' . $relatedId
            );
        }
        $this->Transaction->commit();
        $this->getObjectsRelations($objectId, $relationName, $relatedId);
    }

    /**
     * Update 'priority' (position relative to all children) of $childId son of $objectId
     *
     * $this->data should be
     * ```
     * array(
     *     'priority' => 1
     * )
     * ```
     *
     * If 'priority' is not passed then a 400 is thrown
     * $childId must already be a child of $objectId
     *
     * If `move_siblings` is set to `true`, all siblings with a priority greater than or
     * equal to the `priority` passed will have their priority increased by one.
     *
     * @param int $objectId the parent object id
     * @param int $childId the child object id
     * @return void
     */
    protected function putObjectsChildren($objectId, $childId = null) {
        if (func_num_args() != 2) {
            throw new BeditaBadRequestException();
        }
        if (empty($this->data['priority'])) {
            throw new BeditaBadRequestException('No data to use in PUT request');
        }
        $this->ApiValidator->checkPositiveInteger($childId, true);
        $this->data['child_id'] = (int) $childId;
        $this->ApiValidator->checkChildren(array($this->data), $objectId);

        $moveSiblings = !empty($this->data['move_siblings']);

        $this->Transaction->begin();

        $this->updateSiblingsPriority($objectId, $childId, $this->data['priority'], $moveSiblings);

        $this->Transaction->commit();

        $this->getObjectsChildren($objectId, $childId);
    }

    /**
     * Delete a relation named $relation between $objectId and $relatedId
     *
     * @param int $objectId the object id
     * @param string $relation the relation name
     * @param int $relatedId the related id
     * @return void
     */
    protected function deleteObjectsRelations($objectId, $relation, $relatedId) {
        if (func_num_args() != 3) {
            throw new BeditaBadRequestException();
        }
        $this->ApiValidator->checkPositiveInteger($relatedId, true);
        $objectTypeId = $this->BEObject->findObjectTypeId($objectId);
        if (!$this->ApiValidator->isRelationValid($relation, $objectTypeId)) {
            throw new BeditaBadRequestException($relation . ' is not valid for object id ' . $objectId);
        }
        $objectRelation = ClassRegistry::init('ObjectRelation');
        $exists = $objectRelation->relationExists($objectId, $relatedId, $relation);
        if (!$exists) {
            throw new BeditaNotFoundException('Relation ' . $relation . ' between ' . $objectId . ' and ' . $relatedId . ' not found');
        }
        if (!$objectRelation->deleteRelationAndInverse($objectId, $relatedId, $relation)) {
            throw new BeditaInternalErrorException();
        }
        $this->emptyResponse();
    }

    /**
     * Delete from trees object $childId with $parentId as parent
     *
     * @param int $parentId the object parent id
     * @param int $childId the object child id
     * @return void
     */
    protected function deleteObjectsChildren($parentId, $childId) {
        if (func_num_args() != 2) {
            throw new BeditaBadRequestException();
        }
        $this->ApiValidator->checkPositiveInteger($childId, true);
        $objectTypeId = $this->BEObject->findObjectTypeId($childId);
        if ($objectTypeId == Configure::read('objectTypes.section.id')) {
            throw new BeditaBadRequestException('Section ' .$childId . ' can not be removed from parents');
        }
        $this->ApiValidator->checkObjectAccess($childId);
        $tree = ClassRegistry::init('Tree');
        $count = $tree->find('count', array(
            'conditions' => array(
                'id' => $childId,
                'parent_id' => $parentId
            )
        ));
        if (!$count) {
            throw new BeditaNotFoundException($childId . ' is not child of ' . $parentId);
        }
        if (!$tree->removeChild($childId, $parentId)) {
            throw new BeditaInternalErrorException();
        }

        $this->BEObject->clearCacheByIds(array($parentId, $childId));
        $this->emptyResponse();
    }

    /**
     * Get list of children with access restricted to $user.
     * If it's set to skip permissions or to show unauthorized objects it returns empty array.
     *
     * @param int $parentId the parent id
     * @param array $user array with user data, empty if no user is logged
     * @return array list of forbidden object ids, may be empty
     */
    protected function forbiddenChildren($parentId, array $user = array()) {
        if ($this->showUnauthorized || $this->skipCheck) {
            return array();
        }

        // add conditions on not accessible objects (frontend_access_with_block)
        // @todo move to FrontendController::loadSectionObjects()?
        $objectsForbidden = array();
        $childrenForbidden = false;
        if ($this->BeObjectCache) {
            $cacheOpts = array();
            $childrenForbidden = $this->BeObjectCache->read($parentId, $cacheOpts, 'children-forbidden');
        }
        if ($childrenForbidden === false) {
            $treeJoin = array(
                'table' => 'trees',
                'alias' => 'Tree',
                'type' => 'inner',
                'conditions' => array(
                    'Tree.id = Permission.object_id',
                    'Tree.parent_id' => $parentId,
                )
            );

            $fields = array('Tree.id', 'Permission.ugid');
            $conditions = array(
                'Permission.flag' => Configure::read('objectPermissions.frontend_access_with_block'),
                'Permission.switch' => 'group',
            );

            $permission = ClassRegistry::init('Permission');
            $perms = $permission->find('all', array(
                'fields' => $fields,
                'joins' => array($treeJoin),
                'conditions' => $conditions,
            ));

            $childrenForbidden = array();
            foreach ($perms as $value) {
                $objId = $value['Tree']['id'];
                $childrenForbidden[$objId][] = $value['Permission']['ugid'];
            }

            if ($this->BeObjectCache) {
                $this->BeObjectCache->write($parentId, $cacheOpts, $childrenForbidden, 'children-forbidden');
            }
        }

        // check user allowed if there are forbidden objs
        if (!empty($childrenForbidden)) {
            if (!empty($user)) {
                $groupIds = (!empty($user['groupsIds'])) ? $user['groupsIds'] : array();
                foreach ($childrenForbidden as $id => $groups) {
                    $intersect = array_intersect($groups, $groupIds);
                    if (empty($intersect)) {
                        $objectsForbidden[] = $id;
                    }
                }
            } else {
                $objectsForbidden = array_keys($childrenForbidden);
            }
        }
        return $objectsForbidden;
    }

    /**
     * Get children of $parentId object, prepare and set response data
     * The response is automatically paginated using `self::$paginationOptions`
     * `self::$objectsFilter` and `self::childrenFilter()` are recursively merged and used to populate the filter.
     *
     * `$options` available are:
     * - 'explodeRelations' If the relations should be exploded (default false)
     * - 'filter' An array of filter merged with `self::$objectsFilter` and `self::childrenFilter()`
     *
     * @see FrontendController::loadSectionObjects()
     * @param int $parentId the parent id
     * @param array $options an array of options for filter results
     * @return void
     */
    protected function responseChildren($parentId, array $options = array()) {
        $defaultOptions = array('explodeRelations' => false, 'filter' => array());
        $options = array_merge($defaultOptions, $this->paginationOptions, $options);
        $options['filter'] = Set::merge($this->objectsFilter, $this->childrenFilter(), $options['filter']);
        // assure to have result in 'children' key
        $options['itemsTogether'] = true;
        $user = $this->ApiAuth->getUser();
        $objectsForbidden = $this->forbiddenChildren($parentId, $user);
        if (!empty($objectsForbidden)) {
            $options['filter']['NOT']['BEObject.id'] = $objectsForbidden;
        }

        $result = $this->loadSectionObjects($parentId, $options);
        if (empty($result['children'])) {
            $this->setData();
        } else {
            $objects = $this->ApiFormatter->formatObjects(
                $result['children'],
                array('countRelations' => true, 'countChildren' => true)
            );
            // embed related objects if request
            $urlParams = $this->ApiFormatter->formatUrlParams();
            if (!empty($urlParams['embed']['relations'])) {
                foreach ($objects['objects'] as &$o) {
                    $o = $this->addRelatedObjects($o, $urlParams['embed']['relations']);
                }
            }
            $this->setData($objects);
            $this->setPaging($this->ApiFormatter->formatPaging($result['toolbar']));
        }
    }

    /**
     * Load children of object $id setting data for response
     *
     * @param int $id
     * @return void
     */
    protected function getObjectsChildren($id, $childId = null) {
        if (func_num_args() > 2) {
            throw new BeditaBadRequestException();
        }
        // get list of children
        if (empty($childId)) {
            $this->responseChildren($id);
        // get children position i.e. 'priority' value
        } else {
            if (!$this->ApiValidator->isUrlParamsValid('__all')) {
                $validParams = implode(', ', $this->ApiValidator->getAllowedUrlParams('__all'));
                throw new BeditaBadRequestException(
                    'GET /objects/:id/children/:child_id supports url params: ' . $validParams
                );
            }
            $priority = ClassRegistry::init('Tree')->getPriority($childId, $id);
            if (empty($priority)) {
                throw new BeditaNotFoundException();
            }
            $this->setData(array(
                'priority' => (int) $priority
            ));
        }
    }

    /**
     * Load sections children of object $id setting data for response
     *
     * @param int $id
     * @return void
     */
    protected function getObjectsSections($id) {
        if (func_num_args() > 1) {
            throw new BeditaBadRequestException();
        }
        if (isset($this->objectsFilter['object_type'])) {
            throw new BeditaBadRequestException('GET /objects/:id/sections does not support filter[object_type] param');
        }
        $sectionObjectTypeId = Configure::read('objectTypes.section.id');
        $result = $this->responseChildren($id, array(
            'filter' => array(
                'BEObject.object_type_id' => array($sectionObjectTypeId)
            )
        ));
    }

    /**
     * Load contents children of object $id setting data for response
     *
     * @param int $id
     * @return void
     */
    protected function getObjectsContents($id) {
        if (func_num_args() > 1) {
            throw new BeditaBadRequestException();
        }
        if (!empty($this->objectsFilter['object_type'])) {
            $ot = is_array($this->objectsFilter['object_type']) ? $this->objectsFilter['object_type'] : array($this->objectsFilter['object_type']);
            if (in_array('section', $ot)) {
                throw new BeditaBadRequestException('GET /objects/:id/contents does not support filter[object_type] section value');
            }
        }
        $sectionObjectTypeId = Configure::read('objectTypes.section.id');
        $result = $this->responseChildren($id, array(
            'filter' => array(
                'NOT' => array(
                    'BEObject.object_type_id' => array($sectionObjectTypeId)
                )
            )
        ));
    }

    /**
     * Load descendants of object $id setting data for response
     *
     * @param int $id
     * @return void
     */
    protected function getObjectsDescendants($id) {
        if (func_num_args() > 1) {
            throw new BeditaBadRequestException();
        }
        $this->responseChildren($id, array(
            'filter' => array('descendants' => true)
        ));
    }

    /**
     * Load siblings of object $id setting data for response
     *
     * @param int $id
     * @return void
     */
    protected function getObjectsSiblings($id) {
        if (func_num_args() > 1) {
            throw new BeditaBadRequestException();
        }
        // get only first parent?
        $parentIds = ClassRegistry::init('Tree')->getParents($id, $this->publication['id'], $this->getStatus());
        if (empty($parentIds)) {
            throw new BeditaNotFoundException('The object ' . $id . ' have no parents');
        }
        $this->responseChildren($parentIds[0], array(
            'filter' => array('NOT' => array('BEObject.id' => $id))
        ));
    }

    /**
     * Load relations of object $id setting data for response
     *
     * @param int $id the main object id
     * @param string $relation the relation name
     * @param int $relatedId the related object id
     * @return void
     */
    protected function getObjectsRelations($id, $relation = null, $relatedId = null) {
        if (func_num_args() > 3) {
            throw new BeditaBadRequestException();
        }
        // count relations of object $id
        if ($relation === null) {
            $relCount = $this->ApiFormatter->formatRelationsCount(array('id' => $id));
            $this->setData($relCount);
        } else {
            $objectTypeId = $this->BEObject->findObjectTypeId($id);
            if (!$this->ApiValidator->isRelationValid($relation, $objectTypeId)) {
                throw new BeditaBadRequestException($relation . ' is not valid for object id ' . $id);
            }

            // detail of related objects
            if ($relatedId === null) {
                $defaultOptions = array(
                    'explodeRelations' => false,
                    'filter' => Set::merge($this->objectsFilter, $this->relatedObjectsFilter())
                );
                $options = array_merge($defaultOptions, $this->paginationOptions);
                $result = $this->loadRelatedObjects($id, $relation, $options);
                if (empty($result['items'])) {
                    $this->setData();
                } else {
                    $this->loadRelationParams($result['items'], $id, $relation);
                    $objects = $this->ApiFormatter->formatObjects(
                        $result['items'],
                        array('countRelations' => true)
                    );
                    $this->setData($objects);
                    $this->setPaging($this->ApiFormatter->formatPaging($result['toolbar']));
                }
            // relation detail (params and priority)
            } else {
                if (!$this->ApiValidator->isUrlParamsValid('__all')) {
                    $validParams = implode(', ', $this->ApiValidator->getAllowedUrlParams('__all'));
                    throw new BeditaBadRequestException(
                        'GET /objects/:id/relations/:rel_name/:related_id supports url params: ' . $validParams
                    );
                }
                $this->ApiValidator->checkPositiveInteger($relatedId, true);
                $objectTypeId = $this->BEObject->findObjectTypeId($id);
                if (!$this->ApiValidator->isRelationValid($relation, $objectTypeId)) {
                    throw new BeditaBadRequestException($relation . ' is not valid for object id ' . $id);
                }
                $objectRelation = ClassRegistry::init('ObjectRelation');
                $relationData = $objectRelation->find('first', array(
                    'conditions' => array(
                        'switch' => $relation,
                        'id' => $id,
                        'object_id' => $relatedId
                    )
                ));
                if (empty($relationData['ObjectRelation'])) {
                    throw new BeditaNotFoundException();
                }
                $data = array();
                $data['priority'] = (int) $relationData['ObjectRelation']['priority'];
                if (!empty($relationData['ObjectRelation']['params'])) {
                    $data['params'] = $relationData['ObjectRelation']['params'];
                }
                $this->setData($data);
            }
        }
    }

    /**
     * user profile end point method
     *
     * @param int|string $userid an user id or userid
     * @return void
     */
    protected function profile($userid = null) {
        if (!empty($userid)) {
            $id = is_numeric($userid) ? intval($userid) : $userid;
            $userModel = ClassRegistry::init('User');
            $cardId = $userModel->findCardId($userid);
            if ($cardId !== false) {
                $this->getObjects($cardId);
            } else {
                throw new BeditaNotFoundException();
            }
        } else {
            throw new BeditaBadRequestException();
        }
    }

    /**
     * logged user profile end point method
     *
     * @return void
     */
    protected function me() {
        $user = $this->ApiAuth->identify();
        if ($user) {
            $this->profile($user['id']);
        } else {
            throw new BeditaUnauthorizedException();
        }
    }

    /**
     * GET /posters endpoint
     * Return a poster thumbnail url of object $id or list of id's
     * using 'id' parameter with a comma separated list of id's
     * As 'posters' an image object is retrived using following order:
     * 1. if object $id has a 'poster' relation return that image object
     * 2. else if object $id is an image object type return it
     * 3. else if object $id has an 'attach' relation with an image return that image
     *
     * Possible query url paramters are:
     *
     * - 'width' the thumbnail width
     * - 'height' the thumbnail height
     *
     * @param int|string $id the object id or object nickname
     * @return void
     */
    protected function getPosters($id = null) {
        $thumbConf = $this->posterThumbConf();
        if (!empty($id)) {
            if (func_num_args() != 1) {
                throw new BeditaBadRequestException();
            }
            $id = is_numeric($id) ? $id : $this->BEObject->getIdFromNickname($id);
            if (empty($id)) {
                throw new BeditaNotFoundException();
            }
            try {
                $poster = $this->posterData($id, $thumbConf);
                $this->setData($poster);
            } catch (Exception $ex) {
                $this->setData();
            }
        } else {
            $urlParams = $this->ApiFormatter->formatUrlParams();
            if (empty($urlParams['id'])) {
                throw new BeditaBadRequestException('GET /posters requires at least one id');
            }
            $ids = is_array($urlParams['id']) ? $urlParams['id'] : array($urlParams['id']);
            if (count($ids) > $this->paginationOptions['maxPageSize']) {
                throw new BeditaBadRequestException(
                    'Too many ids requested. Max is ' . $this->paginationOptions['maxPageSize']
                );
            }
            $poster = array();
            try {
                foreach ($ids as $id) {
                    $poster[] = $this->posterData($id, $thumbConf);
                }
                $this->setData($poster);
            } catch (Exception $ex) {
                $this->setData();
            }
        }
    }

    /**
     * Returns thumbnail configuration array from URL and general configuration (used in /posters)
     * @return array thumb conf array
     */
    private function posterThumbConf() {
        $thumbConf = array();
        if (!empty($this->params['url'])) {
            $acceptConf = array(
                'width' => true,
                'height' => true,
                'preset' => true
            );
            $thumbConf = array_intersect_key($this->params['url'], $acceptConf);
            if (isset($thumbConf['preset'])) {
                $presetConf = Configure::read('thumbnails.' . $thumbConf['preset']);
                if (!empty($presetConf)) {
                    $thumbConf = $presetConf;
                }
            }
            $thumbConf['URLonly'] = true;
        }
        return $thumbConf;
    }

    /**
     * Returns poster data for a single object (used in /posters)
     *
     * @param int $id
     * @param array $thumbConf
     * @return array poster data array
     */
    protected function posterData($id, array $thumbConf = array()) {
        $objectType = $this->BEObject->getType($id);
        $model = ClassRegistry::init($objectType);

        if ($model && $model instanceof UploadableInterface){
            $poster = $model->apiCreateThumbnail($id, $thumbConf);
            if (!$poster) {
                $poster = array('id' => $id, 'uri' => '');
            }
        } else {
            $poster = $this->BEObject->getPoster($id);
            if (!$poster) {
                $poster['id'] = $id;
            }
            $beThumb = BeLib::getObject('BeThumb');
            $poster['uri'] = $beThumb->image($poster, $thumbConf);
        }

        $poster['id'] = (int)$poster['id'];

        return $poster;
    }

    /**
     * Auth POST actions.
     * Depending from 'grant_type':
     * - if 'grant_type' is 'password' and credentials are good then generate 'access_token' (JWT) and refresh token
     * - if 'grant_type' is 'refresh_token' it expects a 'refresh_token' and if it's valid renew 'access_token'
     *
     * @return void
     */
    protected function postAuth() {
        $params = $this->params['form'];
        $grantType = (!empty($params['grant_type'])) ? $params['grant_type'] : 'password';
        if ($grantType == 'password') {
            if (empty($params['username']) || empty($params['password'])) {
                throw new BeditaBadRequestException();
            }
            // authenticate user
            if (Configure::read('staging') === true) {
                $authorizedGroups = array(); // only backend authorized groups
            } else {
                // frontend only authorized groups (default empty)
                $confGroups = Configure::read('authorizedGroups');
                // which groups? authorized groups if defined, or any group
                $group = ClassRegistry::init('Group');
                $authorizedGroups = (!empty($confGroups))? $confGroups : $group->getList(array('backend_auth' => 0));
            }
            $authResponse = $this->ApiAuth->authenticate($params['username'], $params['password'], $authorizedGroups);
            if (!$authResponse) {
                throw new BeditaUnauthorizedException();
            }

            $token = $this->ApiAuth->generateToken();
            $refreshToken = $this->ApiAuth->generateRefreshToken();
            if (!$token || !$refreshToken) {
                throw new BeditaUnauthorizedException();
            }
            $data = array(
                'access_token' => $token,
                'expires_in' => $this->ApiAuth->config['JWT']['expiresIn'],
                'refresh_token' => $refreshToken
            );
        } elseif ($grantType == 'refresh_token') {
            if (empty($params['refresh_token'])) {
                throw new BeditaBadRequestException();
            }

            $token = $this->ApiAuth->renewToken($params['refresh_token']);
            if (!$token) {
                throw new BeditaUnauthorizedException('invalid refresh token');
            }

            $data = array(
                'access_token' => $token,
                'expires_in' => $this->ApiAuth->config['JWT']['expiresIn'],
                'refresh_token' => $params['refresh_token']
            );
        } else {
            throw new BeditaBadRequestException('invalid grant');
        }

        $this->setData($data);
    }

    /**
     * If user identified it responds with current access_token
     * and the updated time to expiration
     *
     * @return void
     */
    protected function getAuth() {
        $user = $this->ApiAuth->identify();
        if (!$user) {
            throw new BeditaUnauthorizedException();
        }
        $this->setData(array(
            'access_token' => $this->ApiAuth->getToken(),
            'expires_in' => $this->ApiAuth->expiresIn()
        ));
    }

    /**
     * Revoke authentication removing refresh token
     * If refresh token was removed successufully a 204 NO CONTENT status code returns
     *
     * @param string $refreshToken the refresh token to revoke
     * @return void
     */
    protected function deleteAuth($refreshToken) {
        if (!$this->ApiAuth->identify()) {
            throw new BeditaUnauthorizedException();
        }
        if ($this->ApiAuth->revokeRefreshToken($refreshToken)) {
            $this->emptyResponse();
        } else {
            throw new BeditaInternalErrorException();
        }
    }

    /**
     * Upload a file.
     * Respond with an upload_token that it must be used to link a new object to the uploaded file.
     *
     * @param string $objectType The corresponding object type
     * @param string $fileName The file name
     * @return void
     */
    protected function postFiles($objectType = null, $fileName = null) {
        if (!$this->ApiAuth->identify()) {
            throw new BeditaUnauthorizedException();
        }

        if (empty($objectType)) {
            throw new BeditaBadRequestException('Missing object_type in url path');
        }

        if (empty($fileName)) {
            throw new BeditaBadRequestException('Missing file name in url path');
        }

        $uploadToken = $this->ApiUpload->upload($fileName, $objectType);
        $this->setData(array(
            'upload_token' => $uploadToken
        ));
    }

    /**
     * set child priority and update siblings priority.
     *
     * caller's method must handle Transactions
     *
     * @param string $objectId section id that contains $childId
     * @param string $childId object id that will change priority
     * @param int $priority new priority position
     * @param bool $moveSiblings if true it updates siblings priority
     * @return void
     */
    protected function updateSiblingsPriority($objectId, $childId, $priority, $moveSiblings = false) {
        // Increase or decrease priority for any sibling that is between the former and current position.
        $tree = ClassRegistry::init('Tree');
        $row = $tree->find('first', array(
            'conditions' => array(
                'parent_id' => $objectId,
                'id' => $childId,
            ),
        ));
        // if $objectId is not a parent of $childId throw 400
        if (empty($row)) {
            throw new BeditaBadRequestException($childId . ' must be a child of ' . $objectId);
        }

        $oldPriority = $row['Tree']['priority'];
        $row['Tree']['priority'] = $priority;
        if (!$tree->save($row)) {
            throw new BeditaInternalErrorException('Error updating priority');
        }

        $cacheIdsToBeCleared = array();
        if ($moveSiblings && $priority != $oldPriority) {
            $siblingsToMove = $tree->find('all', array(
                'conditions' => array(
                    'parent_id' => $objectId,
                    'priority >=' => min($oldPriority, $priority),
                    'priority <=' => max($oldPriority, $priority),
                    'id <>' => $childId, // We need to exclude the target children, as it has already been updated.
                ),
            ));

            $sign = 1;
            if ($priority > $oldPriority) {
                $sign = -1;
            }

            foreach ($siblingsToMove as $child) {
                $child['Tree']['priority'] += $sign;
                if (!$tree->save($child)) {
                    throw new BeditaInternalErrorException('Error updating priority');
                }
                $cacheIdsToBeCleared[] = $child['Tree']['id'];
            }
        }

        $this->BEObject->clearCacheByIds($cacheIdsToBeCleared);
    }

    /**
     * Build response data for client
     * $options array permits to customize the response.
     * Possible values are:
     * - 'emptyBody' true to send empty body to client (default false)
     * - 'statusCode' the HTTP status code you want to send to client
     * - 'setBase' false to avoid to set base response metadata (default true)
     *
     * self::autoResponse is set to false
     *
     * @param array $options should set generic api response info
     * @return void
     */
    protected function response(array $options = array()) {
        $options += array(
            'emptyBody' => false,
            'statusCode' => null,
            'setBase' => true
        );
        $this->autoResponse = false;
        if ($options['statusCode'] && is_int($options['statusCode'])) {
            $this->ResponseHandler->sendStatus($options['statusCode']);
        }
        if ($options['emptyBody']) {
            $this->set('_serialize', null);
        } else {
            if ($options['setBase']) {
                $this->setBaseResponse();
            }
            ksort($this->responseData);
            $this->set($this->responseData);
            $this->set('_serialize', array_keys($this->responseData));
        }
    }

    /**
     * Send an empty response body to client
     * Optionally it can send an HTTP status code
     *
     * @param int $statusCode a status code to send to client (default 204 No Content)
     *                        set it to null or other empty values to avoid to send status code
     * @return void
     */
    protected function emptyResponse($statusCode = 204) {
        $this->response(array(
            'statusCode' => $statusCode,
            'emptyBody' => true
        ));
    }

    /**
     * Checks if an origin is allowed.
     * Allowed origins are set in `$conf['api']['allowedOrigins']`.
     * Use `*` to allow any origin. Use `http://*.example.com` to allow any third-level subdomain,
     * use `http://**.example.com` to allow any subdomain, sub-subdomain, ...
     *
     * @return bool
     */
    protected function checkOrigin() {
        $allowed = Configure::read('api.allowedOrigins');
        if (!is_array($allowed)) {
            $allowed = (!empty($allowed)) ? array($allowed) : array('*');
        }
        if (in_array('*', $allowed)) {
            $this->ResponseHandler->sendHeader('Access-Control-Allow-Origin', '*');
            return true;
        }

        $parsed = parse_url(array_key_exists('HTTP_ORIGIN', $_SERVER) ? $_SERVER['HTTP_ORIGIN'] : null);
        $origin = isset($parsed['scheme']) ? $parsed['scheme'] . '://' : '';
        $origin .= isset($parsed['host']) ? $parsed['host'] : '';
        $origin .= isset($parsed['port']) ? ':' . $parsed['port'] : '';

        $replace = array(
            '\*\*\.' => '(([a-z0-9_\-]+\.)*[a-z0-9_\-]+\.)?',
            '\*\.' => '([a-z0-9_\-]+\.)?',
        );
        foreach ($allowed as $allow) {
            $regex = '/^' . str_replace(array_keys($replace), array_values($replace), preg_quote($allow, '/')) . '$/i';
            if (preg_match($regex, $origin)) {
                $this->ResponseHandler->sendHeader('Access-Control-Allow-Origin', $origin);
                $this->ResponseHandler->sendHeader('Vary', 'Origin');
                return true;
            }
        }
        return false;
    }
}
BEdita API doc | 4-cactus API documentation generated by ApiGen