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 
<?php
/*-----8<--------------------------------------------------------------------
 *
 * BEdita - a semantic content management framework
 *
 * Copyright 2009-2014 ChannelWeb Srl, Chialab Srl
 *
 * This file is part of BEdita: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * BEdita is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with BEdita (see LICENSE.LGPL).
 * If not, see <http://gnu.org/licenses/lgpl-3.0.html>.
 *
 *------------------------------------------------------------------->8-----
 */

/**
 * BEdita base model classes
 */
class AppModel extends Model {

    public $actsAs = array('Containable');

    /**
     * Options used by default from self::apiTransformer()
     * @var array
     */
    protected $apiTransformerOptions = array(
        'castable' => array('integer', 'float', 'double', 'date', 'datetime', 'boolean')
    );

    /**
     * Return an array of column types to transform (cast)
     * Used to build consistent REST APIs
     *
     * Possible options are:
     * - 'castable' an array of fields that the REST APIs should cast to
     *
     * @param array $options
     * @return array
     */
    public function apiTransformer($options = array()) {
        $options = array_merge($this->apiTransformerOptions, $options);
        $columnTypes = $this->getColumnTypes();
        return array_intersect($columnTypes, $options['castable']);
    }

}

/**
 * Bedita model base class
 */
class BEAppModel extends AppModel {

    protected $modelBindings = array();
    protected $sQ = ''; // internal use: start quote
    protected $eQ = ''; // internal use: end quote
    protected $driver = ''; // internal use: database driver

    public $actsAs = array();

    /**
     * Merge record result array to top level, skipping specified keys.
     *
     * @param array $record Record data.
     * @param array $skipKeys Keys to be skipped even if their value is an array.
     * @return array Record merged to single array.
     */
    function am($record, array $skipKeys = array()) {
        $tmp = array();
        foreach ($record as $key => $val) {
            if (is_array($val) && !in_array($key, $skipKeys)) {
                // #639 - Associated models merged to main object results.
                foreach ($val as $k => $v) {
                    if (empty($tmp[$k]) || !empty($v)) {
                        $tmp[$k] = $v;
                    }
                }
            } else {
                $tmp[$key] = $val;
            }
        }

        return $tmp;
    }

    protected function setupDbParams() {
        if(empty($this->driver)) {
            $db = ConnectionManager::getDataSource($this->useDbConfig);
            $this->driver = $db->config['driver'];
            $this->sQ = $db->startQuote;
            $this->eQ = $db->endQuote;
        }
    }

    public function getStartQuote() {
        $this->setupDbParams();
        return $this->sQ;
    }

    public function getEndQuote() {
        $this->setupDbParams();
        return $this->eQ;
    }

    public function getDriver() {
        $this->setupDbParams();
        return $this->driver;
    }

    /**
     * Get SQL date format
     *
     * @param unknown_type $value
     * @return unknown
     */
    public function getDefaultDateFormat($value = null, $throwOnError = false) {
        if(is_integer($value)) {
            return date("Y-m-d", $value) ;
        }

        $result = null;
        if(is_string($value) && !empty($value)) {
            $dateFormatValidation = Configure::read("dateFormatValidation");
            if(!$dateFormatValidation) {
                // if config "dateFormatValidation" not set, expect valid SQL date format
                $pattern = "/^[0-9]{4}-[0-9]{2}-[0-9]{2}$|^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/";
                if (preg_match($pattern, $value)) {
                    $result = $value;
                } else {
                    if($throwOnError) {
                        throw new BeditaException(__("Error parsing date. Wrong format", true), array("date" => $value));
                    } else {
                        $this->log("Date not recognized: " . $value . " - field left blank");
                    }
                }
            } else {
                $d_pos = strpos($dateFormatValidation,'dd');
                $m_pos = strpos($dateFormatValidation,'mm');
                $y_pos = strpos($dateFormatValidation,'yyyy');
    
                $dateType = "little-endian"; // default dd/mm/yyyy
                if($y_pos < $m_pos && $y_pos < $d_pos) {
                    $dateType = "big-endian"; // yyyy/mm/dd
                } elseif ($m_pos < $d_pos) {
                    $dateType = "middle-endian"; // mm/dd/yyyy
                }
                try {
                    $result = BeLib::sqlDateFormat($value, $dateType);
                } catch (Exception $ex) {
                    if($throwOnError) {
                        throw new BeditaException(__("Error parsing date. Wrong format", true), array("date" => $value));
                    } else {
                        $this->log("Date not recognized: " . $value . " - field left blank");
                    }
                }
            }
        }

        return $result ;
    }

    /**
     * Check date field in $this->data[ModelName][$key] -> set to null if empty or call getDefaultDateFormat
     *
     * @param string $key
     * @param bool $throwOnError, throw exception on error, default false
     */
    protected function checkDate($key, $throwOnError = false) {
        $data = &$this->data[$this->name];
        if(empty($data[$key])) {
            $data[$key] = null;
        } else {
            $data[$key] = $this->getDefaultDateFormat($data[$key], $throwOnError);
        }
    }

    /**
     * Check float/double field in $this->data[ModelName][$key] -> set to null if empty
     *
     * @param string $key
     */
    protected function checkFloat($key) {
        $data = &$this->data[$this->name];
        if(empty($data[$key])) {
            $data[$key] = null;
        }
    }

    /**
     * Check integer/generic number in $this->data[ModelName][$key] -> set to null if empty
     *
     * @param string $key
     */
    protected function checkNumber($key) {
        $data = &$this->data[$this->name];
        if(empty($data[$key])) {
            $data[$key] = null;
        }
    }

    /**
     * Check duration format in $this->data[ModelName][$key] -> set to null if empty/invalid.
     * 
     * @param string key
     */
    protected function checkDuration($key) {
        $data = &$this->data[$this->name];

        if (!array_key_exists($key, $data)) {
            // Avoid E_NOTICE if PHP's error_reporting & 8 == true.
            $data[$key] = null;
            return;
        }
        $data[$key] = preg_replace("/[^a-z0-9\:\.]/i", "", $data[$key]);  // cleans string.
        $matches = array();
        if (!empty($data[$key]) && preg_match("/^(?:(?P<y>\d+)y)?(?:(?P<w>\d+)w)?(?:(?P<d>\d+)d)?(?:(?P<h>\d+)h)?(?:(?P<m>\d+)m)?(?:(?P<s>\d+)s)?$/i", $data[$key], $matches)) {
            // y w d h m s
            $matches = array_merge(array('y' => 0, 'w' => 0, 'd' => 0, 'h' => 0, 'm' => 0, 's' => 0), $matches);
            $data[$key] = ((($matches['y'] * 365 + $matches['w'] * 7 + $matches['d']) * 24 + $matches['h']) * 60 + $matches['m']) * 60 + $matches['s'];
        } elseif (!empty($data[$key]) && preg_match("/^(?:(?:(?P<h>\d+)?\:)?(?P<m>\d+)?\:)?(?P<s>\d+)?$/", $data[$key], $matches)) {
            // hh:mm:ss
            $matches = array_merge(array('h' => 0, 'm' => 0, 's' => 0), $matches);
            $data[$key] = ($matches['h'] * 60 + $matches['m']) * 60 + $matches['s'];
        } else {
            $data[$key] = null;
        }
    }

    /**
     * Object search Toolbar
     *
     * @param integer $page
     * @param integer $dimPage page dimension (limit sql)
     * @param integer $size count of all records
     *
     * @return array for pagination
     *          "first" => first page; if there is only one page its value is 0 else 1
     *          "prev" => previous page; 0 if there isn't previous page
     *          "next" => next page; 0 if there isn't next page
     *          "last" => last page; 0 if it's the last page
     *          "size" => number of all records
     *          "pages" => total number of pages
     *          "page" => number of current page
     *          "dim" => number of records per page
     *          "start" => number of the record with which the page begins counting from the first page
     *          "end" => number of the record with which the page ends counting from the first page
     *
     */
    function toolbar($page, $dimPage, $size) {

        $toolbar = array("first" => 0, "prev" => 0, "next" => 0, "last" => 0, "size" => 0, "pages" => 0, "page" => 0, "dim" => 0, "start" => 0, "end" => 0) ;

        if (empty($size)) {
            $size = 0;
        }

        if (empty($dimPage)) {
            $dimPage = 0;
            $pageCount = 1;
        } else {
            $pageCount = $size / $dimPage;
            settype($pageCount,"integer");
            if($size % $dimPage) {
                $pageCount++;
            }
        }

        $toolbar["pages"]   = $pageCount;
        $toolbar["page"]    = $page;
        $toolbar["dim"]     = $dimPage;

        if ($page == 1) {
            if($page < $pageCount) {
                // first page
                $toolbar["next"] = $page + 1;
                $toolbar["last"] = $pageCount;
            }
        } else {
            if ($page >= $pageCount) {
                // last page
                $toolbar["first"] = 1;
                $toolbar["prev"] = $page - 1;
            } else {
                // generic page
                $toolbar["next"] = $page + 1;
                $toolbar["last"] = $pageCount;
                $toolbar["first"] = 1;
                $toolbar["prev"] = $page - 1;
            }
        }

        if ($page <= $pageCount) {
            $toolbar["start"] = (($page - 1) * $dimPage) + 1;
            $toolbar["end"] = $page * $dimPage ;
            if ($toolbar["end"] > $size) {
                $toolbar["end"] = $size;
            }
        }
        $toolbar["size"] = $size;

        return $toolbar;
    }

    /**
     * SQL limit clausole
     *
     * @param int $dim, global size/count
     * @param int $page, page num
     * @return string
     */
    protected function getLimitClausole($dim , $page = 1) {
        $dataSource = ConnectionManager::getDataSource($this->useDbConfig);
        $offset = ($page > 1) ? (($page -1) * $dim) : null;
        return $dataSource->limit($dim, $offset);
    }

    public function containLevel($level = "minimum") {
        $fallbacks = array(
            'api' => 'frontend',
            'frontend' => 'minimum'
        );
        if (!isset($this->modelBindings[$level])) {
            // search fallback
            $end = false;
            while (!$end) {
                if (!isset($fallbacks[$level])) {
                    $end = true;
                } else {
                    $level = $fallbacks[$level];
                    if (isset($this->modelBindings[$level])) {
                        $end = true;
                    }
                }
            }
        }

        if (!isset($this->modelBindings[$level])) {
            throw new BeditaException("Contain level not found: $level");
        }
        $this->contain($this->modelBindings[$level]);
        return $this->modelBindings[$level];
    }

    /**
     * Return self::modelBindings level
     *
     * @param string $level define the level to return. Leave empty to return all bindings level
     * @return array|false return false if $level is not set
     */
    public function getBindingsLevel($level = null) {
        if (empty($level)) {
            return $this->modelBindings;
        }
        if (!isset($this->modelBindings[$level])) {
            return false;
        }
        return $this->modelBindings[$level];
    }

    /**
     * Set self::modelBindings level
     *
     * @param string $level the level name
     * @param array $bindings array of model bindings
     */
    public function setBindingsLevel($level, array $bindings = array()) {
        $this->modelBindings[$level] = $bindings;
    }

    public function fieldsString($modelName, $alias = null, $excludeFields = array()) {
        $s = $this->getStartQuote();
        $e = $this->getEndQuote();
        $model = ClassRegistry::init($modelName);
        $kTmp = array_keys($model->schema());
        $k = array_diff($kTmp, $excludeFields);
        if(empty($alias)) {
            $alias = $modelName;
        }
        $res = $s . $alias . $e ."." . $s . implode("{$e},{$s}$alias{$e}.{$s}", $k) . $e;
        return $res;
    }

    /**
     * perform an objects search
     *
     * @param integer $id       root id, if it's set perform search on the tree
     * @param string $userid    user: null (default) => no permission check. ' ' => guest/anonymous user,
     * @param string $status    object status
     * @param array  $filter    example of filter:
     *                          parent_id => used if $id is empty as root id
     *                          "object_type_id" => array(21,22,...),
     *                          "ModelName.fieldname => "value",
     *                          "query" => "text to search"
     *                          ....
     *
     *                          reserved filter words:
     *                          "category" => "val" search by category id or category name
     *                          "relation" => "val" search by object_relations swicth
     *                          "rel_object_id" => "val" search object relateds to a particular object (object_relation object_id)
     *                          ...
     *                          see all in BuildFilter behavior
     *
     *                          "afterFilter" => array() define some operations executed after the objects search
     *                                           to spec on array params see BEAppModel::findObjectsAfterFilter()
     *
     * @param string $order     field to order result (id, status, modified..)
     * @param boolean $dir      true (default), ascending, otherwise descending.
     * @param integer $page     Page number (for pagination)
     * @param integer $dim      Page dim (for pagination). Default get all
     * @param boolean $all      true: all tree levels (discendents), false: only first level (children)
     * @param array $excludeIds Array of id's to exclude
     */
    public function findObjects($id = null, $userid = null, $status = null, $filter = array(), $order = null, $dir = true, $page = 1, $dim = null, $all = false, $excludeIds = array()) {

        if (!$this->Behaviors->attached('BuildFilter')) {
            $this->Behaviors->attach('BuildFilter');
        }

        $excludeFromTreeIds = Configure::read('excludeFromTreeIds');
        if (!empty($excludeFromTreeIds)) {
            if (isset($filter['exclude_branch']) && $filter['exclude_branch'] === false) {
                unset($filter['exclude_branch']);
            } else {
                $filter['exclude_branch'] = $excludeFromTreeIds;
            }
        }

        $afterFilter = $this->Behaviors->BuildFilter->prepareAfterFilter($filter, $order);

        $size = null;
        $rankOrder = null;

        // listen if search engine was used and eventually update $size and $rankOrder
        BeLib::eventManager()->bind(
            'buildFindObjects.searchEngineResult',
            function ($data) use (&$size, &$rankOrder) {
                $size = $data['count'];
                $rankOrder = $data['order'];
                return $data;
            }
        );

        $clauses = $this->findObjectsClauses(compact(
            'id',
            'userid',
            'status',
            'filter',
            'order',
            'dir',
            'page',
            'dim',
            'all',
            'excludeIds'
        ));

        $query = $this->buildQueryStatement($clauses);

        $tmp = $this->query($query);
        if ($tmp === false) {
            throw new BeditaException(__('Error finding objects', true));
        }

        if ($size === null) {
            $size = $this->findObjectsCount(array(
                'joins' => $clauses['joins'],
                'conditions' => $clauses['conditions']
            ));
        }

        $recordset = array(
            'items' => array(),
            'toolbar' => $this->toolbar($page, $dim, $size)
        );

        // Keys to be skipped when merging results. #639 - Associated models merged to main object results.
        $skipKeys = array('RelatedObject', 'ReferenceObject', 'DateItem', 'ObjectProperty');
        foreach ($tmp as $item) {
            // #639 - Associated models merged to main object results.
            array_push($recordset['items'], $this->am($item, $skipKeys));
        }

        // reorder array using search engine rank
        if (!empty($rankOrder)) {
            $tmpOrder = array();
            foreach ($recordset['items'] as $item) {
                $id = $item['id'];
                $tmpOrder[$rankOrder[$id]] = $item;
            }
            ksort($tmpOrder);
            $recordset['items'] = array_values($tmpOrder);
        }

        // after filter callbacks
        if (!empty($afterFilter)) {
            $this->findObjectsAfterFilter($recordset['items'], $afterFilter);
        }

        return $recordset;
    }

    /**
     * Return an objects count
     *
     * The count can be customized using $clauses as in `self::buildQueryStatement`
     * Keys `fields`, `table` and `alias` defined in `$clauses` will be overridden.
     * Other keys have to take account that `objects` table is aliased with `BEObject`
     *
     * Setting `executeQuery` to false will return the SQL query as string
     *
     * @param array $clauses The sql clauses
     * @param bool $executeQuery If the query have to executed or returned
     * @return int|string
     */
    public function findObjectsCount(array $clauses, $executeQuery = true) {
        $s = $this->getStartQuote();
        $e = $this->getEndQuote();
        $clauses = array_merge(
            $clauses,
            array(
                'fields' => "COUNT(DISTINCT {$s}BEObject{$e}.{$s}id{$e}) AS count",
                'table' => "{$s}objects{$e}",
                'alias' => "{$s}BEObject{$e}"
            )
        );

        $queryCount = $this->buildQueryStatement($clauses);
        if (!$executeQuery) {
            return $queryCount;
        }

        $count = $this->query($queryCount);
        if ($count === false) {
            throw new BeditaException(__('Error counting objects', true));
        }

        return current(Set::flatten($count));
    }

    /**
     * Return an array of query clauses starting from some options
     * and applying some filters.
     *
     * Possible options are the arguments passed to self::findObjects()
     *
     * @see self::findObjects() to see the meaning of $options keys
     * @see BuildFilterBehavior to see how to the filter is used to build the query clauses
     * @param array $options An array of options
     * @return array
     */
    public function findObjectsClauses(array $options) {
        $options += array(
            'id' => null,
            'userid' => null,
            'status' => null,
            'filter' => array(),
            'order' => null,
            'dir' => true,
            'page' => 1,
            'dim' => null,
            'all' => false,
            'excludeIds' => array()
        );
        $clauses = array(
            'fields' => '',
            'table' => '',
            'alias' => '',
            'joins' => '',
            'conditions' => '',
            'group' => '',
            'order' => '',
            'limit' => ''
        );
        $s = $this->getStartQuote();
        $e = $this->getEndQuote();

        extract($options, EXTR_SKIP);

        if (array_key_exists('parent_id', $filter)) {
            $id = (!$id && !empty($filter['parent_id']))? $filter['parent_id'] : $id;
            unset($filter['parent_id']);
        }

        if (isset($filter['descendants'])) {
            $all = true;
            unset($filter['descendants']);
        }

        // if filter 'tree_related_object' is set
        // it filters objects that have some relation with objects located
        // on $id tree branch or on $id tree branch descendants (if $all is true)
        if ($id && isset($filter['tree_related_object'])) {
            $tree = ClassRegistry::init('Tree');
            $filter['ObjectRelation.object_id'] = $tree->findChildrenList($id, $all);
            // avoid to search objects children on $id branch tree
            $id = null;
        }

        if (!$this->Behaviors->attached('BuildFilter')) {
            $this->Behaviors->attach('BuildFilter');
        }
        $this->Behaviors->BuildFilter->prepareCountPermissionFilter($filter, $order);
        $this->Behaviors->BuildFilter->prepareCountAnnotationFilter($filter, $order);
        $this->Behaviors->BuildFilter->prepareObjectTypeFilter($filter);

        $beObjFields = $this->fieldsString('BEObject');
        $clauses['fields'] = 'DISTINCT ' . $beObjFields;
        $clauses['table'] = "{$s}objects{$e}";
        $clauses['alias'] = "as {$s}BEObject{$e}";
        $conditions = array();
        $clauses['group'] = $beObjFields;

        if (!empty($excludeIds)) {
            $conditions['NOT'] = array(array("{$s}BEObject{$e}.{$s}id{$e}" => $excludeIds));
        }

        $filterKeysString = implode('|', array_keys($filter));
        if (strstr($filterKeysString, 'Content.')) {
            $contentFields = $this->fieldsString('Content', null, array('id'));
            $clauses['fields'] .= ', ' . $contentFields;
            $clauses['joins'] .= " LEFT OUTER JOIN {$s}contents{$e} as {$s}Content{$e} ON {$s}BEObject{$e}.{$s}id{$e}={$s}Content{$e}.{$s}id{$e}";
            $clauses['group'] .= ', ' . $contentFields;
        }

        if (!empty($status)) {
            $conditions[] = array("{$s}BEObject{$e}.{$s}status{$e}" => $status);
        }

        // actual SQL limit page (may vary using external searchEngine)
        $limitPage = $page;

        // search filter
        $this->Behaviors->BuildFilter->prepareSearchFilter($filter);
        $searchEngineResult = $this->Behaviors->BuildFilter->searchEngineResult(
            Configure::read('searchEngine'),
            array(
                'id' => $id,
                'userid' => $userid,
                'status' => $status,
                'filter' => $filter,
                'page' => $page,
                'dim' => $dim,
                'all' => $all,
                'order' => $order
            )
        );
        if ($searchEngineResult !== false) {
            unset($filter['query']);
            $limitPage = 1;
            $conditions[] = array("{$s}BEObject{$e}.{$s}id{$e}" => $searchEngineResult['result']['ids']);
            BeLib::eventManager()->trigger('buildFindObjects.searchEngineResult', array($searchEngineResult));
        }

        // setup filter to get only allowed objects
        // exclude backend private objects and object that stay only in private publication/section
        if (BACKEND_APP && $userid) {
            $filter['allowed_to_user'] = $userid;
        }

        // build filter clauses with BuildFilterBehavior::getSqlItems()
        $sqlItems = $this->getSqlItems($filter);
        $otherFields = $sqlItems['fields'];
        $otherFrom = $sqlItems['from'];
        $otherJoins = $sqlItems['joins'];
        $otherConditions = $sqlItems['conditions'];
        $otherGroup = $sqlItems['group'];
        $otherOrder = $sqlItems['order'];
        $useGroupBy = $sqlItems['useGroupBy'];

        if (!empty($otherFields)) {
            $clauses['fields'] = $clauses['fields'] . $otherFields;
        }

        $conditions = array_merge($conditions, $otherConditions);
        $clauses['joins'] .= $otherJoins . $otherFrom;

        if (!empty($id)) {
            $treeFields = $this->fieldsString('Tree');
            $clauses['fields'] .= ',' . $treeFields;
            if ($this->getDriver() == 'mysql') {
                // #MYSQL
                $clauses['group'] .= ", {$s}Tree{$e}.{$s}id{$e}";
            } else {
                // #POSTGRES (@TODO: this clausole do not exclude double results. To fix it)
                $clauses['group'] .= ',' . $this->fieldsString('Tree');
            }
            $clauses['joins'] .= ", {$s}trees{$e} AS {$s}Tree{$e}";
            $conditions[] = " {$s}Tree{$e}.{$s}id{$e}={$s}BEObject{$e}.{$s}id{$e}" ;

            if ($all) {
                $cond = '';
                if ($this->getDriver() == 'mysql') {
                    // #MYSQL
                    $cond = " {$s}Tree{$e}.{$s}object_path{$e} LIKE (CONCAT((SELECT {$s}object_path{$e} FROM {$s}trees{$e} WHERE {$s}id{$e} = {$id}), '/%')) " ;
                } else {
                    // #POSTGRES
                    $cond = " {$s}Tree{$e}.{$s}object_path{$e} LIKE ((SELECT {$s}object_path{$e} FROM {$s}trees{$e} WHERE {$s}id{$e} = {$id}) || '/%') " ;
                }
                $conditions[] = $cond;
            } else {
                $conditions[] = array("{$s}Tree{$e}.{$s}parent_id{$e}" => $id) ;
            }
            if (empty($order) && empty($filter['query'])) {
                $order = "{$s}Tree{$e}.{$s}priority{$e}";
                $section = ClassRegistry::init('Section');
                $priorityOrder = $section->field('priority_order', array('id' => $id));
                if (empty($priorityOrder)) {
                    $priorityOrder = 'asc';
                }
                $dir = ($priorityOrder == 'asc');
            }
        }

        // if $order is empty and not performing search then set a default order
        if ((empty($order) || !preg_match('/^[a-z0-9`., _-]+$/i', trim($order))) && empty($filter['query'])) {
            $order = "{$s}BEObject{$e}.{$s}id{$e}";
            $dir = false;
        }

        // build sql conditions
        $db = ConnectionManager::getDataSource($this->useDbConfig);
        $clauses['conditions'] = $db->conditions($conditions, true, true) ;

        if ($useGroupBy || !empty($otherGroup) || ($id && $all)) {
            $clauses['group'] = 'GROUP BY ' . $clauses['group'] . $otherGroup;
        } else {
            $clauses['group'] = '';
        }

        if (is_string($order) && strlen($order)) {
            $beObject = ClassRegistry::init('BEObject');
            if ($beObject->hasField($order)) {
                $order = "{$s}BEObject{$e}.{$s}{$order}{$e}";
            }
            $ordItem = $order . ((!$dir)? 'DESC ' : '');
            if (!empty($otherOrder)) {
                $clauses['order'] = ' ORDER BY ' . $ordItem . ', ' . $otherOrder;
            } else {
                $clauses['order'] = " ORDER BY {$order} " . ((!$dir)? ' DESC ' : '');
            }
        } elseif (!empty($otherOrder)) {
            $clauses['order'] = "ORDER BY {$otherOrder}";
        }

        $clauses['limit'] = (!empty($dim))? $this->getLimitClausole($dim, $limitPage) : '';

        return $clauses;
    }

    /**
     * Given an array of clauses build a SQL SELECT query
     *
     * @param array $clauses The SQL clauses
     * @return string
     */
    public function buildQueryStatement(array $clauses) {
        $clauses += array(
            'fields' => '',
            'table' => '',
            'alias' => '',
            'joins' => '',
            'conditions' => '',
            'group' => '',
            'order' => '',
            'limit' => ''
        );
        $db = ConnectionManager::getDataSource($this->useDbConfig);
        return $db->renderStatement('select', $clauses);
    }

    /**
     * callback called by BEAppModel::findObjects() to work on list of BEdita objects
     *
     * @param  array $items  list of BEdita objects filtered by BEAppModel::findObjects()
     * @param  array $params it's an array of configurable parameters to launch callbacks on Models or Behaviors.
     *                       Every callback has to return the array of BEdita objects passed to it.
     *
     *                       It can be a plain array:
     *
     *                       array(
     *                           'type' => 'Model' or 'Behavior' default to 'Model'
     *                           'className' => 'ClassName' for Behavior it's the class name without Behavior suffix
     *                           'methodName' => 'methodName' the method name of ClassName
     *                           'options' => array() array of options to pass to ClassName::methodName()
     *                       )
     *
     *                       or it can be a multidimensional array, for example
     *
     *                       array(
     *                           array(
     *                               'type' => 'Model',
     *                               'className' => 'ModelClassName',
     *                               'methodName' => 'modelMethodName',
     *                               'options' => array()
     *                           ),
     *                           array(
     *                               'type' => 'Behavior',
     *                               'className' => 'BehaviorClassName',
     *                               'methodName' => 'behaviorMethodName',
     *                               'options' => array()
     *                           )
     *                       )
     *
     *                       If type is 'Model' the 'modelMethodName' method of 'ModelClassName' should be defined as
     *
     *                       public function modelMethodName($items, $options) {
     *                           ....
     *                           return $items;
     *                       }
     *
     *                       If type is 'Behavior' the 'behaviorMethodName' method 'BehaviorClassName' should be defined as
     *
     *                       public function behaviorMethodName(&$model, $items, $options) {
     *                           ....
     *                           return $items;
     *                       }
     */
    protected function findObjectsAfterFilter(array &$items, array $params) {
        // multidimensional array two or more callbacks
        if (isset($params[0])) {
            foreach ($params as $value) {
                if (!empty($value['className'])) {
                    $this->findObjectsAfterFilter($items, $value);
                }
            }
        // only one callback
        } else {
            $default = array('type' => 'Model', 'className' => '', 'methodName' => '', 'options' => array());
            $params = array_merge($default, $params);
            if (!empty($params['className']) && !empty($params['methodName'])) {
                if ($params['type'] == 'Model') {
                    $modelClass = ClassRegistry::init($params['className']);
                    if (method_exists($modelClass, $params['methodName'])) {
                        $items = $modelClass->{$params['methodName']}($items, $params['options']);
                    }
                } elseif ($params['type'] == 'Behavior') {
                    if (App::import('Behavior', $params['className'])) {
                        $behaviorClass = $params['className'];
                        if (method_exists($behaviorClass . 'Behavior', $params['methodName'])) {
                            if (!$this->Behaviors->attached($behaviorClass)) {
                                $this->Behaviors->attach($behaviorClass);
                            }
                            $items = $this->{$params['methodName']}($items, $params['options']);
                            $this->Behaviors->detach($behaviorClass);
                        }
                    }
                }
            }
        }
    }

    /**
     * Validate email with an up-to-date regex.
     * 
     * @param array $rule - An array with rule name as key (email) and value to validate
     * @return bool
     */
    public function email(array $rule)
    {
        $Validation =& Validation::getInstance();
        $hostnameRegex = "(?:[_\p{L}0-9][-_\p{L}0-9]*\.)*(?:[\p{L}0-9][-\p{L}0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,})";
        $emailRegex = "/^[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+)*@" . $hostnameRegex . "$/i";

        return $Validation->email($rule['email'], false, $emailRegex);
    }
}

///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////

/**
 * BEdita base app object class. BEdita objects should extend BEAppObjectModel
 */
class BEAppObjectModel extends BEAppModel {
    var $recursive  = 2 ;

    public $actsAs = array(
        'Callback',
        'CompactResult' => array(),
        'SearchTextSave',
        'RevisionObject',
        'ForeignDependenceSave' => array('BEObject'),
        'DeleteObject' => 'objects',
        'Notify'
    );

    var $hasOne= array(
            'BEObject' =>
            array(
                'className'     => 'BEObject',
                'conditions'   => '',
                'foreignKey'    => 'id',
                'dependent'     => true
            )
        );

    public $objectTypesGroups = array();

    /**
     * Overrides field, don't use CompactResult in field()
     *
     * @param string $name
     * @param array $conditions
     * @param string $order
     */
    public function field($name, $conditions = null, $order = null) {

        $compactEnabled = $this->Behaviors->enabled('CompactResult');
        if ($compactEnabled) {
            $this->Behaviors->disable('CompactResult');
        }
        $res = parent::field($name, $conditions, $order);
        if ($compactEnabled) {
            $this->Behaviors->enable('CompactResult');
        }
        return $res;
    }

    /**
     * Overrides saveField, don't use CompactResult in saveField()
     *
     * @param string $name
     * @param array $conditions
     * @param string $order
     */
    public function saveField($name, $value, $validate = false) {

        $dependanceEnabled = $this->Behaviors->enabled('ForeignDependenceSave');
        if ($dependanceEnabled) {
            $this->Behaviors->disable('ForeignDependenceSave');
        }
        $res = parent::saveField($name, $value, $validate);
        if ($dependanceEnabled) {
            $this->Behaviors->enable('ForeignDependenceSave');
        }
        return $res;
    }

    function save($data = null, $validate = true, $fieldList = array()) {
        if(isset($data['BEObject']) && empty($data['BEObject']['object_type_id'])) {
            $data['BEObject']['object_type_id'] = BeLib::getObject('BeConfigure')->getObjectTypeId($this->name);
        } else if(!isset($data['object_type_id']) || empty($data['object_type_id'])) {
            $data['object_type_id'] = BeLib::getObject('BeConfigure')->getObjectTypeId($this->name);
        }

        // Se c'e' la chiave primaria vuota la toglie
        if(isset($data[$this->primaryKey]) && empty($data[$this->primaryKey])) {
            unset($data[$this->primaryKey]) ;
        }

        $data = (!empty($data[$this->alias]))? $data : array($this->alias => $data);

        // format data array for HABTM relations in cake way
        if (!empty($this->hasAndBelongsToMany)) {
            foreach ($this->hasAndBelongsToMany as $key => $val) {
                if (!empty($data[$this->alias][$key][$key])) {
                    $data[$key][$key] = $data[$this->alias][$key][$key];
                    unset($data[$this->alias][$key]);
                } elseif (!empty($data[$this->alias][$key])) {
                    $data[$key][$key] = $data[$this->alias][$key];
                    unset($data[$this->alias][$key]);
                } elseif ( (isset($data[$this->alias][$key]) && is_array($data[$this->alias][$key]))
                            || (isset($data[$this->alias][$key][$key]) && is_array($data[$this->alias][$key][$key])) ) {
                    $data[$key][$key] = array();
                }
            }
        }

        $result = parent::save($data, $validate, $fieldList) ;

        return $result ;
    }

    /**
     * Clone a BEdita object starting from object id
     * It should be called from a BEdita object model as Document, Section, etc...
     *
     * @param int $id, the BEdita object id
     * @param array $options, see BEAppObjectModel::arrangeDataForClone
     * @return type
     */
    public function cloneObject($id, array $options = array()) {
        $this->containLevel("detailed");
        $data = $this->findById($id);
        $this->arrangeDataForClone($data, $options);
        $this->create();
        return $this->save($data);
    }

    /**
     * Arrange an array to cloning a BEdita object
     *
     * @param array $data, should come from a find
     * @param array $options, default values are:
     *              "nicknameSuffix" => "", suffix to append at the original object nickname
     *              "keepTitle" => false, true to keep the original object title
     *              "keepUserCreated" => false, true to keep the original user created
     */
    public function arrangeDataForClone(array &$data, array $options = array()) {
        $defaultOptions = array("nicknameSuffix" => false, "keepTitle" => false, "keepUserCreated" => false);
        $options = array_merge($defaultOptions, $options);
        $toUnset = array("id", "ObjectType", "SearchText", "UserCreated", "UserModified", "Version");
        if (isset($data["nickname"])) {
            if ($options["nicknameSuffix"]) {
                $data["nickname"] .= $options["nicknameSuffix"];
            } else {
                $toUnset[] = "nickname";
            }
        }
        if (!$options["keepUserCreated"]) {
            $toUnset[] = "user_created";
        }
        foreach ($toUnset as $label) {
            if (isset($data[$label])) {
                unset($data[$label]);
            }
        }
        if (!$options["keepTitle"]) {
            $data["title"] .= " - " . __("copy", true);
        }
        if (!empty($data["Permission"]) && is_array($data["Permission"])) {
            foreach ($data["Permission"] as &$perm) {
                if (isset($perm["object_id"])) {
                    unset($perm["object_id"]);
                }
                unset($perm["ugid"]);
                unset($perm["id"]);
            }
        }
        if (!empty($data["ObjectProperty"])) {
            $objectProperty = array();
            foreach ($data["ObjectProperty"] as $op) {
                if (!empty($op["value"]["property_value"])) {
                    $objectProperty[] = array(
                        "property_type" => $op["property_type"],
                        "property_id" => $op["id"],
                        "property_value" => $op["value"]["property_value"]
                    );
                }
            }
            $data["ObjectProperty"] = $objectProperty;
        }
        if (!empty($data["RelatedObject"])) {
            $relatedObject = array();
            foreach ($data["RelatedObject"] as $key => $value) {
                $relatedObject[$value["switch"]][] = array(
                    "id" => $value["object_id"],
                    "switch" => $value["switch"],
                    "priority" => $value["priority"]
                );
            }
            $data["RelatedObject"] = $relatedObject;
        }
        if (!empty($data['Category'])) {
            $cat = array();
            foreach ($data['Category'] as $k => $value) {
                $cat[] = $value['id'];
            }
            $data['Category'] = $cat;
        }
    }

    /**
     * Updates hasMany model rows:
     *   * delete all rows of hasMany models except ones with "id" set in $data array
     *   * saves/updates all hasMany data rows from $data array
     * 
     * @throws BeditaException
     * @return boolean
     */
    protected function updateHasManyAssoc() {

        foreach ($this->hasMany as $name => $assoc) {

            if (isset($this->data[$this->name][$name])) {
                $model      = ClassRegistry::init($assoc['className']) ;

                // delete previous associations
                $id = (isset($this->data[$this->name]['id'])) ? $this->data[$this->name]['id'] : $this->getInsertID() ;
                $foreignK = $assoc['foreignKey'] ;
                
                $exclude = array();
                foreach ($this->data[$this->name][$name] as $hasManyObj){
                    if(!empty($hasManyObj["id"])){
                        $exclude[] = $hasManyObj["id"];
                    }
                }
                $conditions = array($foreignK => $id, "NOT" => array("id" => $exclude));
                $model->deleteAll($conditions);

                // if there isn't data to save then exit
                if (!isset($this->data[$this->name][$name]) || !(is_array($this->data[$this->name][$name]) && count($this->data[$this->name][$name])))
                    continue ;

                // save new associations
                $size = count($this->data[$this->name][$name]) ;
                for ($i=0; $i < $size ; $i++) {
                    $model->create();
                    $data            = &$this->data[$this->name][$name][$i] ;
                    $data[$foreignK] = $id ;
                    if(!$model->save($data)) {
                        throw new BeditaException(__("Error saving associated data", true), $data);
                    }
                }
            }
        }

        return true ;
    }

    /**
     * default values for Contents
     */
    protected function validateContent() {
        $this->checkDate('start_date');
        $this->checkDate('end_date');
        $this->checkDuration('duration');
        return true ;
    }

    public function checkType($objTypeId) {
        return ($objTypeId == Configure::read("objectTypes.".Inflector::underscore($this->name).".id"));
    }

    public function getTypeId() {
        return Configure::read("objectTypes.".Inflector::underscore($this->name).".id");
    }

    /**
     * Return an array of column types to transform (cast) for generic BEdita object type
     * Used to build consistent REST APIs
     *
     * In general it returns all castable fields from:
     * - main Model table
     * - tables that extend the object (ForeignDependenceSave)
     * - GetTag, Category, Tag
     *
     * Possible options are:
     * - 'castable' an array of fields that the REST APIs should cast to
     *
     * @param array $options
     * @return array
     */
    public function apiTransformer(array $options = array()) {
        $options = array_merge($this->apiTransformerOptions, $options);
        $transformer = parent::apiTransformer($options);
        if (!empty($this->actsAs['ForeignDependenceSave'])) {
            foreach ($this->actsAs['ForeignDependenceSave'] as $modelName) {
                $object = array_intersect($this->$modelName->getColumnTypes(), $options['castable']);
                $transformer = array_merge($transformer, $object);
            }
        }
        $transformer['GeoTag'] = $this->BEObject->GeoTag->apiTransformer();
        $transformer['Category'] = $transformer['Tag'] = $this->BEObject->Category->apiTransformer();
        return $transformer;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * Bedita simple object
**/

class BeditaSimpleObjectModel extends BEAppObjectModel {

    public $searchFields = array(
        "title" => 10,
        "nickname" => 8,
        "description" => 6,
        "note" => 2
    );

    public $useTable = 'objects';

    public $actsAs  = array(
        'Callback',
        'CompactResult' => array(),
        'SearchTextSave',
        'Notify'
    );

    public $hasOne= array();
}

class BeditaObjectModel extends BeditaSimpleObjectModel {

    public $actsAs = array(
        'Callback',
        'CompactResult' => array(),
        'SearchTextSave',
        'DeleteObject' => 'objects',
        'Notify'
    );

    public $hasOne = array(
        'BEObject' =>
            array(
                'className'     => 'BEObject',
                'foreignKey'    => 'id'
            )
    );

    protected $modelBindings = array(
        'detailed' => array(
            'BEObject' => array(
                'ObjectType',
                'UserCreated',
                'UserModified',
                'Permission',
                'ObjectProperty',
                'LangText',
                'RelatedObject',
                'Annotation',
                'Category'
            )
        ),
        'default' => array(
            'BEObject' => array(
                'ObjectProperty',
                'LangText',
                'ObjectType',
                'Annotation',
                'Category',
                'RelatedObject'
            )
        ),
        'minimum' => array('BEObject' => array('ObjectType')),
        'frontend' => array(
            'BEObject' => array(
                'ObjectProperty',
                'LangText',
                'ObjectType',
                'Annotation',
                'Category',
                'RelatedObject'
            )
        ),
        'api' => array(
            'BEObject' => array(
                'ObjectProperty',
                'LangText',
                'Category'
            )
        )
    );

    public function save($data = null, $validate = true, $fieldList = array()) {
        $data2 = $data;

        foreach($data2 as $key => $value) {
            if (!is_array($value)){
                unset($data2[$key]);
            }
        }

        if(isset($data['BEObject']) && empty($data['BEObject']['object_type_id'])) {
            $data['BEObject']['object_type_id'] = BeLib::getObject('BeConfigure')->getObjectTypeId($this->name);
        } else if(!isset($data['object_type_id']) || empty($data['object_type_id'])) {
            $data['object_type_id'] = BeLib::getObject('BeConfigure')->getObjectTypeId($this->name);
        }

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

        $data = (!empty($data[$this->alias]))? array("BEObject" => $data[$this->alias]) : array("BEObject" => $data);

        $beObject = ClassRegistry::init("BEObject");

        // format data array for HABTM relations in cake way
        if (!empty($beObject->hasAndBelongsToMany)) {
            foreach ($beObject->hasAndBelongsToMany as $key => $val) {
                if (!empty($data[$beObject->alias][$key][$key])) {
                    $data[$key][$key] = $data[$beObject->alias][$key][$key];
                    unset($data[$beObject->alias][$key]);
                } elseif (!empty($data[$beObject->alias][$key])) {
                    $data[$key][$key] = $data[$beObject->alias][$key];
                    unset($data[$beObject->alias][$key]);
                } elseif ( (isset($data[$beObject->alias][$key]) && is_array($data[$beObject->alias][$key]))
                            || (isset($data[$beObject->alias][$key][$key]) && is_array($data[$beObject->alias][$key][$key])) ) {
                    $data[$key][$key] = array();
                }
            }
        }

        if (empty($data['id']) && empty($data['BEObject']['id']) && empty($data[$this->name]['id'])) {
            $beObject->create();
        } else {
            $beObject->create(null);
        }
        if (!$res = $beObject->save($data, $validate, $fieldList)) {
            return $res;
        }

        $data2["id"] = $beObject->id;
        $this->create(null);
        $res = parent::save($data2, $validate, $fieldList);
        //$res = Model::save($data, $validate, $fieldList) ;
        //$res = ClassRegistry::init("Model")->save($data2, $validate, $fieldList);

        return $res;
    }

}

/**
 * Bedita content model relations
**/

class BeditaContentModel extends BEAppObjectModel {

    public $searchFields = array(
        "title" => 10,
        "nickname" => 8,
        "creator" => 6,
        "description" => 6,
        "subject" => 4,
        "abstract" => 4,
        "body" => 4,
        "note" => 2
    );

    function beforeValidate() {
        return $this->validateContent();
    }

}

/**
 * Bedita annotation model
**/

class BeditaAnnotationModel extends BEAppObjectModel {

    public $searchFields = array(
        "title" => 10,
        "nickname" => 8,
        "description" => 6,
        "body" => 4,
        "author" => 3,
        "note" => 2
    );

    var $belongsTo = array(
        "ReferenceObject" =>
            array(
                'className'     => 'BEObject',
                'foreignKey'    => 'object_id',
            ),
    );

    public $actsAs = array(
        'Callback',
        'CompactResult' => array("ReferenceObject"),
        'SearchTextSave',
        'ForeignDependenceSave' => array('BEObject'),
        'DeleteObject' => 'objects',
        'Notify'
    );

    protected $modelBindings = array(
        'detailed' => array(
            'BEObject' => array(
                'ObjectType',
                'UserCreated',
                'Version' => array('User.realname', 'User.userid')
            ),
            'ReferenceObject'
        ),
        'default' => array(
            'BEObject' => array(
                'ObjectType',
                'UserCreated'
            ),
            'ReferenceObject'),
        'minimum' => array('BEObject' => array('ObjectType')),
        'frontend' => array('BEObject', 'ReferenceObject'),
        'api' => array('BEObject')
    );

}


/**
 * Base model for simple stream objects.
 */
class BeditaSimpleStreamModel extends BEAppObjectModel {

    public $searchFields = array(
        "title" => 10,
        "nickname" => 8,
        "description" => 6,
        "subject" => 4,
        "abstract" => 4,
        "body" => 4,
        "name" => 6,
        "original_name" => 8,
        "note" => 2
    );

    protected $modelBindings = array(
        'detailed' => array(
            'BEObject' => array(
                'ObjectType',
                'Permission',
                'UserCreated',
                'UserModified',
                'RelatedObject',
                'Annotation',
                'Category',
                'LangText',
                'ObjectProperty',
                'Alias',
                'Version' => array('User.realname', 'User.userid')
            ),
            'Content'
        ),
        'default' => array(
            'BEObject' => array(
                'ObjectProperty',
                'LangText',
                'ObjectType',
                'RelatedObject',
                'Annotation',
                'Category'
            ),
            'Content'
        ),
        'minimum' => array(
            'BEObject' => array('ObjectType', 'Category'),
            'Content'
        ),
        'frontend' => array(
            'BEObject' => array(
                'LangText',
                'ObjectProperty',
                'Category',
                'RelatedObject'
            ),
            'Content'
        ),
        'api' => array(
            'BEObject' => array(
                'LangText',
                'ObjectProperty',
                'Category'
            ),
            'Content'
        )
    );

    public $actsAs = array(
        'Callback',
        'CompactResult' => array(),
        'SearchTextSave' => array(),
        'RevisionObject',
        'ForeignDependenceSave' => array('BEObject', 'Content'),
        'DeleteObject' => 'objects',
        'Notify'
    );

    var $hasOne= array(
            'BEObject' =>
                array(
                    'className'     => 'BEObject',
                    'conditions'   => '',
                    'foreignKey'    => 'id',
                    'dependent'     => true
                ),
            'Content' =>
                array(
                    'className'     => 'Content',
                    'conditions'   => '',
                    'foreignKey'    => 'id',
                    'dependent'     => true
                ),
    );

    function beforeValidate() {
        return $this->validateContent();
    }

}

/**
 * Base model for stream objects.
 */
class BeditaStreamModel extends BEAppObjectModel {

    public $searchFields = array(
        "title" => 10,
        "nickname" => 8,
        "description" => 6,
        "subject" => 4,
        "abstract" => 4,
        "body" => 4,
        "name" => 6,
        "original_name" => 8,
        "note" => 2
    );

    protected $modelBindings = array(
        'detailed' => array(
            'BEObject' => array(
                'ObjectType',
                'Permission',
                'UserCreated',
                'UserModified',
                'RelatedObject',
                'Category',
                'ObjectProperty',
                'LangText',
                'Annotation',
                'Alias',
                'Version' => array('User.realname', 'User.userid')
            ),
            'Content',
            'Stream'
        ),
        'default' => array(
            'BEObject' => array(
                'ObjectProperty',
                'LangText',
                'ObjectType',
                'RelatedObject',
                'Category',
                'Annotation'
            ),
            'Content',
            'Stream'
        ),
        'minimum' => array(
            'BEObject' => array('ObjectType', 'Category'),
            'Content',
            'Stream'
        ),
        'frontend' => array(
            'BEObject' => array(
                'LangText',
                'ObjectProperty',
                'Category',
                'RelatedObject'
            ),
            'Content',
            'Stream'
        ),
        'api' => array(
            'BEObject' => array(
                'LangText',
                'ObjectProperty',
                'Category'
            ),
            'Content',
            'Stream'
        )
    );


    public $actsAs = array(
        'Callback',
        'CompactResult' => array(),
        'SearchTextSave' => array(),
        'RevisionObject',
        'ForeignDependenceSave' => array('BEObject', 'Content', 'Stream'),
        'DeleteObject' => 'objects',
        'Notify'
    );

    var $hasOne= array(
            'BEObject' =>
                array(
                    'className'     => 'BEObject',
                    'conditions'   => '',
                    'foreignKey'    => 'id',
                    'dependent'     => true
                ),
            'Content' =>
                array(
                    'className'     => 'Content',
                    'conditions'   => '',
                    'foreignKey'    => 'id',
                    'dependent'     => true
                ),
            'Stream' =>
                array(
                    'className'     => 'Stream',
                    'conditions'   => '',
                    'foreignKey'    => 'id',
                    'dependent'     => true
                ),
    );

    function beforeValidate() {
        return $this->validateContent();
    }

}

/**
 * Base class for products
 *
 */
class BeditaProductModel extends BEAppObjectModel {

    public $searchFields = array(
        "title" => 10,
        "nickname" => 8,
        "description" => 6,
        "abstract" => 4,
        "body" => 4,
        "note" => 2
    );

    protected $modelBindings = array(
        'detailed' => array(
            'BEObject' => array(
                'ObjectType',
                'Permission',
                'UserCreated',
                'UserModified',
                'RelatedObject',
                'ObjectProperty',
                'LangText',
                'Category',
                'Annotation',
                'Alias',
                'Version' => array('User.realname', 'User.userid')
            ),
            'Product'
        ),
        'default' => array(
            'BEObject' => array(
                'ObjectProperty',
                'LangText',
                'ObjectType'
            ),
            'Product'
        ),
        'minimum' => array(
            'BEObject' => array('ObjectType'),
            'Product'
        ),
        'frontend' => array(
            'BEObject' => array(
                'LangText',
                'ObjectProperty',
                'RelatedObject',
                'Category',
                'Annotation',
                'GeoTag'
            ),
            'Product'
        ),
        'api' => array(
            'BEObject' => array(
                'LangText',
                'ObjectProperty',
                'Category',
                'GeoTag'
            ),
            'Product'
        )
    );

    public $actsAs = array(
        'Callback',
        'CompactResult' => array(),
        'SearchTextSave' => array(),
        'ForeignDependenceSave' => array('BEObject', 'Product'),
        'DeleteObject' => 'objects',
        'Notify'
    );

    var $hasOne= array(
            'BEObject' =>
                array(
                    'className'     => 'BEObject',
                    'conditions'   => '',
                    'foreignKey'    => 'id',
                    'dependent'     => true
                ),
            'Product' =>
                array(
                    'className'     => 'Product',
                    'conditions'   => '',
                    'foreignKey'    => 'id',
                    'dependent'     => true
                )
    );
}


////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * Base model for collection objects.
 */
class BeditaCollectionModel extends BEAppObjectModel {

    public $actsAs = array(
        'Callback',
        'CompactResult' => array(),
        'SearchTextSave',
        'RevisionObject',
        'ForeignDependenceSave' => array('BEObject'),
        'DeleteDependentObject' => array('section'),
        'DeleteObject' => 'objects',
        'Notify'
    );

    var $recursive  = 2;

    var $hasOne = array(
            'BEObject' =>
                array(
                    'className'     => 'BEObject',
                    'conditions'   => '',
                    'foreignKey'    => 'id',
                    'dependent'     => true
                ),
            'Tree' =>
                array(
                    'foreignKey'    => 'id',
                )
    );
    
    public function deleteCollection($id) {
        return ClassRegistry::init('Tree')->removeBranch($id);
    }
}

/**
 * Base model for import filters.
 */
abstract class BeditaImportFilter extends BEAppModel {

    public $useTable = false;

    protected $typeName = "";
    protected $mimeTypes = array();

    /**
     * Import BE objects from XML source string
     *
     * @param string $sourcePath, path to source to import, e.g. path to local files, urls...
     * @param array $options, import options: "sectionId" => import objects in this section
     * @return array , result array containing
     *  "objects" => number of imported objects
     *  "message" => generic message (optional)
     *  "error" => error message (optional)
     * @throws BeditaException
     */
    public function import($sourcePath, array $options = array())  {
        throw new BeditaException(__("Missing method", true));
    }

    /**
     * Supported mime types
     *
     * @return array , array of supported mime types like
     *  "text/xml", "application/xml"
     */
    public function mimeTypes() {
        return $this->mimeTypes;
    }

    /**
     * Filter logical name
     */
    public function name() {
        return $this->typeName;
    }

};

/**
 * Base model for export filters.
 */
abstract class BeditaExportFilter extends BEAppModel {

    public $useTable = false;

    protected $typeName = "";
    protected $mimeTypes = array();

    /**
     * Export objects in XML format
     *
     * @param array $objects, object to export array
     * @param array $options, export options
     * @return array containing
     *  "content" - export content
     *  "contentType" - content mime type
     *  "size" - content length
     * @throws BeditaException
     */
    public function export(array &$objects, array $options = array()) {
        throw new BeditaException(__("Missing method", true));
    }

    /**
     * Supported mime types
     *
     * @return array , result array containing supported mime types in the form
     *  "xml" => "text/xml", "zip" => "application/zip",....
     */
    public function mimeTypes() {
        return $this->mimeTypes;
    }

    /**
     * Filter logical name
     */
    public function name() {
        return $this->typeName;
    }

    /**
     * Validate resource (after export)
     */
    public function validate($resource, array $options = array()){
        return __("No 'validate' method found");
    }

};

/**
 * Uploadable Model Interface
 *
 * Define the methods that a Model must implement
 * if it should support file upload through API and want to handle it
 */
interface UploadableInterface {

    /**
     * Called during the upload action it receives the temporary file
     * and move it to the wanted location.
     *
     * `$options` contains:
     *
     * - 'fileName' the safe file name that should be used saving file
     * - 'hashFile' the file hash (md5) that can be used to know if file is already in the system
     * - 'user' the user is doing upload
     *
     * @param File $file File object instance of temporary file.
     * @param array $options Additional info about the upload request.
     * @return string|false Path of uploaded file relative to base directory, or `false` on failure.
     */
    public function apiUpload(File $file, array $options = array());

    /**
     * Transform data for uploaded object.
     * Called from the API when the upload is finalized creating the object type
     * with file uploaded associated to it.
     *
     * `$data` contains info about a file previously uploaded:
     *
     * - 'uri' the file url
     * - 'name' the file name
     * - 'mime_type' the file mime type
     * - 'file_size' the file dimension
     * - 'original_name' the original file name
     * - 'hash_file' the file hash
     *
     * It must return an array of object's fields to save
     *
     * @param array $data Uploaded file data.
     * @return array
     */
    public function apiUploadTransformData(array $data);

    /**
     * Find quota usage.
     *
     * Given an array of uploadable object types and a user
     * it calculates the quota usage and the total amount of
     * uploaded objects for that user.
     *
     * The result must be merged with `$event->result` and returned in the form:
     *
     * ```
     * array(
     *     'object_type_name' => array(
     *         'size' => 12345678,
     *         'number' => 256
     *      ),
     * )
     * ```
     *
     * This method is intended to be bound to `Api.uploadQuota` event
     * triggered for example by `ApiUploadComponent`.
     *
     * @param array $uploadableObjects Array of uploadable object types.
     * @param array $user User data.
     * @param object $event Dispatched event.
     * @return array
     */
    public function apiUploadQuota(array $uploadableObjects, array $user, $event);

    /**
     * Create the thumbnail for the requested resource (if necessary)
     * and returns an array containing the the uri of the thumb and the object id refered from thumb.
     *
     * @param int $id The id of the object you want to create the thumbnail for.
     * @param array $thumbConf The thumb configuration
     * @return array|false It must return `false` if the thumb creation fails
     *                     else the array must contain the keys `id` and `uri`
     */
    public function apiCreateThumbnail($id, $thumbConf = array());
}

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