Alpha Framework 3.0.0 API Documentation
  • Namespace
  • Class

Namespaces

  • Alpha
    • Controller
      • Front
    • Exception
    • Model
      • Type
    • Task
    • Util
      • Backup
      • Cache
      • Code
        • Highlight
        • Metric
      • Config
      • Convertor
      • Email
      • Extension
      • Feed
      • File
      • Graph
      • Helper
      • Http
        • Filter
        • Session
      • Image
      • Logging
      • Search
      • Security
      • Service
    • View
      • Renderer
        • Html
        • Json
      • Widget

Classes

  • Alpha\Controller\ActiveRecordController
  • Alpha\Controller\ArticleController
  • Alpha\Controller\AttachmentController
  • Alpha\Controller\CacheController
  • Alpha\Controller\Controller
  • Alpha\Controller\DEnumController
  • Alpha\Controller\ExcelController
  • Alpha\Controller\FeedController
  • Alpha\Controller\Front\FrontController
  • Alpha\Controller\GenSecureQueryStringController
  • Alpha\Controller\ImageController
  • Alpha\Controller\IndexController
  • Alpha\Controller\InstallController
  • Alpha\Controller\ListActiveRecordsController
  • Alpha\Controller\LogController
  • Alpha\Controller\LoginController
  • Alpha\Controller\LogoutController
  • Alpha\Controller\MetricController
  • Alpha\Controller\PhpinfoController
  • Alpha\Controller\RecordSelectorController
  • Alpha\Controller\SearchController
  • Alpha\Controller\SequenceController
  • Alpha\Controller\TagController
  • Alpha\Model\ActionLog
  • Alpha\Model\ActiveRecord
  • Alpha\Model\ActiveRecordProviderMySQL
  • Alpha\Model\ActiveRecordProviderSQLite
  • Alpha\Model\Article
  • Alpha\Model\ArticleComment
  • Alpha\Model\ArticleVote
  • Alpha\Model\BadRequest
  • Alpha\Model\BlacklistedClient
  • Alpha\Model\BlacklistedIP
  • Alpha\Model\Person
  • Alpha\Model\Rights
  • Alpha\Model\Tag
  • Alpha\Model\Type\Boolean
  • Alpha\Model\Type\Date
  • Alpha\Model\Type\DEnum
  • Alpha\Model\Type\DEnumItem
  • Alpha\Model\Type\Double
  • Alpha\Model\Type\Enum
  • Alpha\Model\Type\Integer
  • Alpha\Model\Type\Relation
  • Alpha\Model\Type\RelationLookup
  • Alpha\Model\Type\Sequence
  • Alpha\Model\Type\SmallText
  • Alpha\Model\Type\Text
  • Alpha\Model\Type\Timestamp
  • Alpha\Model\Type\Type
  • Alpha\Task\BackupTask
  • Alpha\Task\CronManager
  • Alpha\Util\Backup\BackupUtils
  • Alpha\Util\Cache\CacheProviderAPC
  • Alpha\Util\Cache\CacheProviderArray
  • Alpha\Util\Cache\CacheProviderFile
  • Alpha\Util\Cache\CacheProviderMemcache
  • Alpha\Util\Cache\CacheProviderRedis
  • Alpha\Util\Code\Highlight\HighlightProviderGeshi
  • Alpha\Util\Code\Highlight\HighlightProviderLuminous
  • Alpha\Util\Code\Metric\Inspector
  • Alpha\Util\Config\ConfigProvider
  • Alpha\Util\Convertor\ActiveRecord2Excel
  • Alpha\Util\Email\EmailProviderPHP
  • Alpha\Util\ErrorHandlers
  • Alpha\Util\Extension\Markdown
  • Alpha\Util\Extension\MarkdownFacade
  • Alpha\Util\Extension\TCPDF
  • Alpha\Util\Extension\TCPDFFacade
  • Alpha\Util\Feed\Atom
  • Alpha\Util\Feed\Feed
  • Alpha\Util\Feed\RSS
  • Alpha\Util\Feed\RSS2
  • Alpha\Util\File\FileUtils
  • Alpha\Util\Graph\GraphNode
  • Alpha\Util\Graph\TreeGraph
  • Alpha\Util\Helper\Validator
  • Alpha\Util\Http\AgentUtils
  • Alpha\Util\Http\Filter\ClientBlacklistFilter
  • Alpha\Util\Http\Filter\ClientTempBlacklistFilter
  • Alpha\Util\Http\Filter\IPBlacklistFilter
  • Alpha\Util\Http\PHPServerUtils
  • Alpha\Util\Http\Request
  • Alpha\Util\Http\Response
  • Alpha\Util\Http\Session\SessionProviderArray
  • Alpha\Util\Http\Session\SessionProviderPHP
  • Alpha\Util\Image\ImageUtils
  • Alpha\Util\InputFilter
  • Alpha\Util\Logging\KPI
  • Alpha\Util\Logging\Logger
  • Alpha\Util\Logging\LogProviderFile
  • Alpha\Util\Search\SearchProviderTags
  • Alpha\Util\Security\SecurityUtils
  • Alpha\Util\Service\ServiceFactory
  • Alpha\View\ArticleCommentView
  • Alpha\View\ArticleView
  • Alpha\View\DEnumView
  • Alpha\View\PersonView
  • Alpha\View\Renderer\Html\RendererProviderHTML
  • Alpha\View\Renderer\Json\RendererProviderJSON
  • Alpha\View\SequenceView
  • Alpha\View\View
  • Alpha\View\ViewState
  • Alpha\View\Widget\Button
  • Alpha\View\Widget\DateBox
  • Alpha\View\Widget\Image
  • Alpha\View\Widget\RecordSelector
  • Alpha\View\Widget\SmallTextBox
  • Alpha\View\Widget\TagCloud
  • Alpha\View\Widget\TextBox

Interfaces

  • Alpha\Controller\ControllerInterface
  • Alpha\Model\ActiveRecordProviderInterface
  • Alpha\Model\Type\TypeInterface
  • Alpha\Task\TaskInterface
  • Alpha\Util\Cache\CacheProviderInterface
  • Alpha\Util\Code\Highlight\HighlightProviderInterface
  • Alpha\Util\Email\EmailProviderInterface
  • Alpha\Util\Http\Filter\FilterInterface
  • Alpha\Util\Http\Session\SessionProviderInterface
  • Alpha\Util\Logging\LogProviderInterface
  • Alpha\Util\Search\SearchProviderInterface
  • Alpha\View\Renderer\RendererProviderInterface

Exceptions

  • Alpha\Exception\AlphaException
  • Alpha\Exception\BadTableNameException
  • Alpha\Exception\CustomQueryException
  • Alpha\Exception\FailedDeleteException
  • Alpha\Exception\FailedIndexCreateException
  • Alpha\Exception\FailedLookupCreateException
  • Alpha\Exception\FailedSaveException
  • Alpha\Exception\FailedUnitCommitException
  • Alpha\Exception\FileNotFoundException
  • Alpha\Exception\IllegalArguementException
  • Alpha\Exception\LockingException
  • Alpha\Exception\MailNotSentException
  • Alpha\Exception\NotImplementedException
  • Alpha\Exception\PHPException
  • Alpha\Exception\RecordNotFoundException
  • Alpha\Exception\ResourceNotAllowedException
  • Alpha\Exception\ResourceNotFoundException
  • Alpha\Exception\SearchIndexWriteException
  • Alpha\Exception\SecurityException
  • Alpha\Exception\ValidationException
   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 
<?php

namespace Alpha\Controller;

use Alpha\Model\Type\Timestamp;
use Alpha\Model\Type\Integer;
use Alpha\Model\ActiveRecord;
use Alpha\Util\Config\ConfigProvider;
use Alpha\Util\Security\SecurityUtils;
use Alpha\Util\Helper\Validator;
use Alpha\Util\Service\ServiceFactory;
use Alpha\Util\Http\Request;
use Alpha\Util\Http\Response;
use Alpha\Util\Logging\Logger;
use Alpha\Exception\IllegalArguementException;
use Alpha\Exception\FailedUnitCommitException;
use Alpha\Exception\FailedSaveException;
use Alpha\Exception\LockingException;
use Alpha\Exception\AlphaException;
use Alpha\Exception\NotImplementedException;
use Alpha\View\View;
use Alpha\View\ViewState;
use ReflectionClass;
use Exception;

/**
 * The master controller class for the Alpha Framework.
 *
 * @since 1.0
 *
 * @author John Collins <dev@alphaframework.org>
 * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
 * @copyright Copyright (c) 2018, John Collins (founder of Alpha Framework).
 * All rights reserved.
 *
 * <pre>
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the
 * following conditions are met:
 *
 * * Redistributions of source code must retain the above
 *   copyright notice, this list of conditions and the
 *   following disclaimer.
 * * Redistributions in binary form must reproduce the above
 *   copyright notice, this list of conditions and the
 *   following disclaimer in the documentation and/or other
 *   materials provided with the distribution.
 * * Neither the name of the Alpha Framework nor the names
 *   of its contributors may be used to endorse or promote
 *   products derived from this software without specific
 *   prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * </pre>
 */
abstract class Controller
{
    /**
     * The name of the controller.
     *
     * @var string
     *
     * @since 1.0
     */
    protected $name;

    /**
     * Used to set access privileages for the controller to the name of the rights group
     * allowed to access it.  'Public' by default.
     *
     * @var string
     *
     * @since 1.0
     */
    protected $visibility = 'Public';

    /**
     * Optionally, the main record object that this controller is currently working with.
     *
     * @var \Alpha\Model\ActiveRecord
     *
     * @since 1.0
     */
    protected $record = null;

    /**
     * Used to determine if the controller is part of a unit of work sequence
     * (either empty or the name of the unit).
     *
     * @var string
     *
     * @since 1.0
     */
    protected $unitOfWork;

    /**
     * Stores the start time of a unit of work transaction.
     *
     * @var \Alpha\Model\Type\Timestamp
     *
     * @since 1.0
     */
    protected $unitStartTime;

    /**
     * Stores the end time of a unit of work transaction.
     *
     * @var \Alpha\Model\Type\Timestamp
     *
     * @since 1.0
     */
    protected $unitEndTime;

    /**
     * Stores the maximum allowed time duration (in seconds) of the unit of work.
     *
     * @var \Alpha\Model\Type\Integer
     *
     * @since 1.0
     */
    protected $unitMAXDuration;

    /**
     * The name of the first controller that is used in this unit of work.
     *
     * @var string
     *
     * @since 1.0
     */
    protected $firstJob;

    /**
     * The name of the next controller that is used in this unit of work.
     *
     * @var string
     *
     * @since 1.0
     */
    protected $nextJob;

    /**
     * The name of the previous controller that is used in this unit of work.
     *
     * @var string
     *
     * @since 1.0
     */
    protected $previousJob;

    /**
     * The name of the last controller that is used in this unit of work.
     *
     * @var string
     *
     * @since 1.0
     */
    protected $lastJob;

    /**
     * An array for storing dirty record objects in a session (i.e. persistent business
     * objects that have not been updated in the database yet).
     *
     * @var array
     *
     * @since 1.0
     */
    protected $dirtyObjects = array();

    /**
     * An array for storing new reord objects in a session (transient business objects that
     * have no ID yet).
     *
     * @var array
     *
     * @since 1.0
     */
    protected $newObjects = array();

    /**
     * The title to be displayed on the controller page.
     *
     * @var string
     *
     * @since 1.0
     */
    protected $title;

    /**
     * Meta keywords for the controller page, generally populated from tags.
     *
     * @var string
     *
     * @since 1.0
     */
    protected $keywords;

    /**
     * Meta description for the controller page.
     *
     * @var string
     *
     * @since 1.0
     */
    protected $description;

    /**
     * Used to set status update messages to display to the user (messages stored between requests
     * in session).  Useful for when you want to display a message to a user after POSTing a request,
     * or when moving from one page to the next.
     *
     * @var string
     *
     * @since 1.0
     */
    protected $statusMessage;

    /**
     * The request that has been passed to this controller for processing.
     *
     * @var \Alpha\Util\Http\Request
     *
     * @since 2.0
     */
    protected $request;

    /**
     * Trace logger.
     *
     * @var \Alpha\Util\Logging\Logger
     *
     * @since 1.0
     */
    private static $logger = null;

    /**
     * Constructor for the Controller that starts a new session if required, and handles
     * the population of new/dirty objects from the session when available.  Accepts the name
     * of the rights group that has access to this controller, 'Public' by default.
     *
     * @param string $visibility The name of the rights group that can access this controller.
     *
     * @since 1.0
     */
    public function __construct($visibility = 'Public')
    {
        self::$logger = new Logger('Controller');
        self::$logger->debug('>>__construct(visibility=['.$visibility.'])');

        $config = ConfigProvider::getInstance();

        // set the access rights to the group name indicated
        $this->visibility = $visibility;

        $this->unitStartTime = new Timestamp(date('Y-m-d H:i:s'));
        $this->unitEndTime = new Timestamp();
        $this->unitMAXDuration = new Integer();

        // uses controller class name as the job name
        if ($this->name == '') {
            $this->setName(get_class($this));
        }

        $sessionProvider = $config->get('session.provider.name');
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');

        if ($session->get('unitOfWork') !== false && is_array($session->get('unitOfWork'))) {
            $this->setUnitOfWork($session->get('unitOfWork'));
        }

        if ($session->get('dirtyObjects') !== false && is_array($session->get('dirtyObjects'))) {
            $this->dirtyObjects = $session->get('dirtyObjects');
        }

        if ($session->get('newObjects') && is_array($session->get('newObjects'))) {
            $this->newObjects = $session->get('newObjects');
        }

        if ($session->get('statusMessage') !== false) {
            $this->setStatusMessage($session->get('statusMessage'));
        }

        self::$logger->debug('<<__construct');
    }

    /**
     * Get the record for this controller (if any).
     *
     * @return ActiveRecord
     *
     * @since 1.0
     */
    public function getRecord()
    {
        self::$logger->debug('>>getRecord()');
        self::$logger->debug('<<getRecord ['.var_export($this->record, true).']');

        return $this->record;
    }

    /**
     * Setter for the record for this controller.
     *
     * @param \Alpha\Model\ActiveRecord $record
     *
     * @since 1.0
     */
    public function setRecord($record)
    {
        self::$logger->debug('>>setRecord(record=['.var_export($record, true).'])');
        $this->record = $record;

        // if the record has tags, use these as the meta keywords for this controller
        if ($this->record->isTagged()) {
            $tags = $this->record->getPropObject('tags')->getRelated();

            $keywords = '';

            if (count($tags) > 0) {
                foreach ($tags as $tag) {
                    $keywords .= ','.$tag->get('content');
                }
            }

            $this->setKeywords(mb_substr($keywords, 1));
        }

        self::$logger->debug('<<setRecord');
    }

    /**
     * Get the name of the unit of work job.
     *
     * @return string
     *
     * @since 1.0
     */
    public function getName()
    {
        self::$logger->debug('>>getName()');
        self::$logger->debug('<<getName ['.$this->name.']');

        return $this->name;
    }

    /**
     * Setter for the unit of work job name.
     *
     * @param string $name The fully-qualified controller class name, or an absolute URL.
     *
     * @since 1.0
     */
    public function setName($name)
    {
        self::$logger->debug('>>setName(name=['.$name.'])');
        $this->name = $name;
        self::$logger->debug('<<setName');
    }

    /**
     * Get the name of the rights group that has access to this controller.
     *
     * @return string
     *
     * @since 1.0
     */
    public function getVisibility()
    {
        self::$logger->debug('>>getVisibility()');
        self::$logger->debug('<<getVisibility ['.$this->visibility.']');

        return $this->visibility;
    }

    /**
     * Setter for the name of the rights group that has access to this controller.
     *
     * @param string $visibility
     *
     * @since 1.0
     */
    public function setVisibility($visibility)
    {
        self::$logger->debug('>>setVisibility(visibility=['.$visibility.'])');
        $this->visibility = $visibility;
        self::$logger->debug('<<setVisibility');
    }

    /**
     * Gets the name of the first job in this unit of work.
     *
     * @return string The fully-qualified controller class name, or an absolute URL.
     *
     * @since 1.0
     */
    public function getFirstJob()
    {
        self::$logger->debug('>>getFirstJob()');
        self::$logger->debug('<<getFirstJob ['.$this->firstJob.']');

        return $this->firstJob;
    }

    /**
     * Gets the name of the next job in this unit of work.
     *
     * @return string The fully-qualified controller class name, or an absolute URL.
     *
     * @since 1.0
     */
    public function getNextJob()
    {
        self::$logger->debug('>>getNextJob()');
        self::$logger->debug('<<getNextJob ['.$this->nextJob.']');

        return $this->nextJob;
    }

    /**
     * Gets the name of the previous job in this unit of work.
     *
     * @return string The fully-qualified controller class name, or an absolute URL.
     *
     * @since 1.0
     */
    public function getPreviousJob()
    {
        self::$logger->debug('>>getPreviousJob()');
        self::$logger->debug('<<getPreviousJob ['.$this->previousJob.']');

        return $this->previousJob;
    }

    /**
     * Gets the name of the last job in this unit of work.
     *
     * @return string The fully-qualified controller class name, or an absolute URL.
     *
     * @since 1.0
     */
    public function getLastJob()
    {
        self::$logger->debug('>>getLastJob()');
        self::$logger->debug('<<getLastJob ['.$this->lastJob.']');

        return $this->lastJob;
    }

    /**
     * Sets the name of the controller job sequence to the values in the supplied
     * array (and stores the array in the session).
     *
     * @param array $jobs The names of the controllers in this unit of work sequence.  Will accept fully-qualified controller class name, or an absolute URL.
     *
     * @throws \Alpha\Exception\IllegalArguementException
     *
     * @since 1.0
     */
    public function setUnitOfWork($jobs)
    {
        self::$logger->debug('>>setUnitOfWork(jobs=['.var_export($jobs, true).'])');

        if (method_exists($this, 'before_setUnitOfWork_callback')) {
            $this->{'before_setUnitOfWork_callback'}();
        }

        if (!is_array($jobs)) {
            self::$logger->debug('<<setUnitOfWork');
            throw new IllegalArguementException('Bad $jobs array ['.var_export($jobs, true).'] passed to setUnitOfWork method!');
        }

        // validate that each controller name in the array actually exists
        foreach ($jobs as $job) {
            if (!Validator::isURL($job) && !class_exists($job)) {
                throw new IllegalArguementException('The controller name ['.$job.'] provided in the jobs array is not defined anywhere!');
            }
        }

        // clear out any previous unit of work from the session
        $config = ConfigProvider::getInstance();
        $sessionProvider = $config->get('session.provider.name');
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');
        $session->delete('unitOfWork');
        $this->firstJob = null;
        $this->previousJob = null;
        $this->nextJob = null;
        $this->lastJob = null;
        $this->dirtyObjects = array();
        $this->newObjects = array();

        $numOfJobs = count($jobs);

        for ($i = 0; $i < $numOfJobs; ++$i) {
            // the first job in the sequence
            if ($i == 0) {
                $this->firstJob = $jobs[$i];
                self::$logger->debug('First job ['.$this->firstJob.']');
            }
            // found the current job
            if ($this->name == $jobs[$i]) {
                if (isset($jobs[$i-1])) {
                    // set the previous job if it exists
                    $this->previousJob = $jobs[$i-1];
                    self::$logger->debug('Previous job ['.$this->previousJob.']');
                }
                if (isset($jobs[$i+1])) {
                    // set the next job if it exists
                    $this->nextJob = $jobs[$i+1];
                    self::$logger->debug('Next job ['.$this->nextJob.']');
                }
            }
            // the last job in the sequence
            if ($i == ($numOfJobs-1)) {
                $this->lastJob = $jobs[$i];
            }
        }

        if ($this->previousJob == null) {
            $this->previousJob = $this->firstJob;
        }

        if ($this->nextJob == null) {
            $this->nextJob = $this->lastJob;
        }

        $session->set('unitOfWork', $jobs);

        if (method_exists($this, 'after_setUnitOfWork_callback')) {
            $this->{'after_setUnitOfWork_callback'}();
        }

        self::$logger->debug('<<setUnitOfWork');
    }

    /**
     * Getter for the unit start time.
     *
     * @return Timestamp
     *
     * @since 1.0
     */
    public function getStartTime()
    {
        self::$logger->debug('>>getStartTime()');
        self::$logger->debug('<<getStartTime ['.$this->unitStartTime.']');

        return $this->unitStartTime;
    }

    /**
     * Setter for the unit start time (value will be stored in the session as key unitStartTime).
     *
     * @param int $year
     * @param int $month
     * @param int $day
     * @param int $hour
     * @param int $minute
     * @param int $second
     *
     * @since 1.0
     */
    public function setUnitStartTime($year, $month, $day, $hour, $minute, $second)
    {
        self::$logger->debug('>>setUnitStartTime(year=['.$year.'], month=['.$month.'], day=['.$day.'], hour=['.$hour.'], minute=['.$minute.'],
            second=['.$second.'])');

        $config = ConfigProvider::getInstance();
        $sessionProvider = $config->get('session.provider.name');
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');

        $this->unitStartTime->setTimestampValue($year, $month, $day, $hour, $minute, $second);
        $session->set('unitStartTime', $this->unitStartTime->getValue());

        self::$logger->debug('<<setUnitStartTime');
    }

    /**
     * Getter for the unit end time.
     *
     * @return \Alpha\Model\Type\Timestamp
     *
     * @since 1.0
     */
    public function getEndTime()
    {
        self::$logger->debug('>>getEndTime()');
        self::$logger->debug('<<getEndTime ['.$this->unitEndTime.']');

        return $this->unitEndTime;
    }

    /**
     * Setter for the unit end time (value will be stored in the session as key unitEndTime).
     *
     * @param int $year
     * @param int $month
     * @param int $day
     * @param int $hour
     * @param int $minute
     * @param int $second
     *
     * @since 1.0
     */
    public function setUnitEndTime($year, $month, $day, $hour, $minute, $second)
    {
        self::$logger->debug('>>setUnitEndTime(year=['.$year.'], month=['.$month.'], day=['.$day.'], hour=['.$hour.'], minute=['.$minute.'],
         second=['.$second.'])');

        $config = ConfigProvider::getInstance();
        $sessionProvider = $config->get('session.provider.name');
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');

        $this->unitEndTime->setTimestampValue($year, $month, $day, $hour, $minute, $second);
        $session->set('unitEndTime', $this->unitEndTime->getValue());

        self::$logger->debug('<<setUnitEndTime');
    }

    /**
     * Getter for the unit of work MAX duration.
     *
     * @return Integer
     *
     * @since 1.0
     */
    public function getMAXDuration()
    {
        self::$logger->debug('>>getMAXDuration()');
        self::$logger->debug('<<getMAXDuration ['.$this->unitMAXDuration.']');

        return $this->unitMAXDuration;
    }

    /**
     * Setter for the unit MAX duration.
     *
     * @param int $duration The desired duration in seconds.
     *
     * @since 1.0
     */
    public function setUnitMAXDuration($duration)
    {
        self::$logger->debug('>>setUnitMAXDuration(duration=['.$duration.'])');
        $this->unitMAXDuration->setValue($duration);
        self::$logger->debug('<<setUnitMAXDuration');
    }

    /**
     * Calculates and returns the unit of work current duration in seconds.
     *
     * @return int
     *
     * @since 1.0
     */
    public function getUnitDuration()
    {
        self::$logger->debug('>>getUnitDuration()');

        $intStartTime = mktime(
            intval($this->unitStartTime->getHour()),
            intval($this->unitStartTime->getMinute()),
            intval($this->unitStartTime->getSecond()),
            intval($this->unitStartTime->getMonth()),
            intval($this->unitStartTime->getDay()),
            intval($this->unitStartTime->getYear())
            );

        $intEndTime = mktime(
            intval($this->unitEndTime->getHour()),
            intval($this->unitEndTime->getMinute()),
            intval($this->unitEndTime->getSecond()),
            intval($this->unitEndTime->getMonth()),
            intval($this->unitEndTime->getDay()),
            intval($this->unitEndTime->getYear())
            );

        self::$logger->debug('<<getUnitDuration ['.($intEndTime-$intStartTime).']');

        return $intEndTime-$intStartTime;
    }

    /**
     * Adds the supplied business object to the dirtyObjects array in the session.
     *
     * @param \Alpha\Model\ActiveRecord $object
     *
     * @since 1.0
     */
    public function markDirty($object)
    {
        self::$logger->debug('>>markDirty(object=['.var_export($object, true).'])');

        if (method_exists($this, 'before_markDirty_callback')) {
            $this->{'before_markDirty_callback'}();
        }

        $this->dirtyObjects[count($this->dirtyObjects)] = $object;

        $config = ConfigProvider::getInstance();
        $sessionProvider = $config->get('session.provider.name');
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');

        $session->set('dirtyObjects', $this->dirtyObjects);

        if (method_exists($this, 'after_markDirty_callback')) {
            $this->{'after_markDirty_callback'}();
        }

        self::$logger->debug('<<markDirty');
    }

    /**
     * Getter for the dirty objects array.
     *
     * @return array
     *
     * @since 1.0
     */
    public function getDirtyObjects()
    {
        self::$logger->debug('>>getDirtyObjects()');
        self::$logger->debug('<<getDirtyObjects ['.var_export($this->dirtyObjects, true).']');

        return $this->dirtyObjects;
    }

    /**
     * Adds a newly created business object to the newObjects array in the session.
     *
     * @param \Alpha\Model\ActiveRecord $object
     *
     * @since 1.0
     */
    public function markNew($object)
    {
        self::$logger->debug('>>markNew(object=['.var_export($object, true).'])');

        if (method_exists($this, 'before_markNew_callback')) {
            $this->{'before_markNew_callback'}();
        }

        $this->newObjects[count($this->newObjects)] = $object;

        $config = ConfigProvider::getInstance();
        $sessionProvider = $config->get('session.provider.name');
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');

        $session->set('newObjects', $this->newObjects);

        if (method_exists($this, 'after_markNew_callback')) {
            $this->{'after_markNew_callback'}();
        }

        self::$logger->debug('<<markNew');
    }

    /**
     * Getter for the new objects array.
     *
     * @return array
     *
     * @since 1.0
     */
    public function getNewObjects()
    {
        self::$logger->debug('>>getNewObjects()');
        self::$logger->debug('<<getNewObjects ['.var_export($this->newObjects, true).']');

        return $this->newObjects;
    }

    /**
     * Commits (saves) all of the new and modified (dirty) objects in the unit of work to the database.
     *
     * @throws \Alpha\Exception\FailedUnitCommitException
     *
     * @since 1.0
     */
    public function commit()
    {
        self::$logger->debug('>>commit()');

        if (method_exists($this, 'before_commit_callback')) {
            $this->{'before_commit_callback'}();
        }

        ActiveRecord::begin();

        $newObjects = $this->getNewObjects();

        $count = count($newObjects);

        for ($i = 0; $i < $count; ++$i) {
            try {
                $newObjects[$i]->save();
            } catch (FailedSaveException $e) {
                self::$logger->error('Failed to save new object of type ['.get_class($newObjects[$i]).'], aborting...');
                $this->abort();

                throw new FailedUnitCommitException($e->getMessage());
            } catch (LockingException $e) {
                self::$logger->error('Failed to save new object of type ['.get_class($newObjects[$i]).'], aborting...');
                $this->abort();

                throw new FailedUnitCommitException($e->getMessage());
            }
        }

        $dirtyObjects = $this->getDirtyObjects();

        $count = count($dirtyObjects);

        for ($i = 0; $i < $count; ++$i) {
            try {
                $dirtyObjects[$i]->save();
            } catch (FailedSaveException $e) {
                self::$logger->error('Failed to save ID ['.$dirtyObjects[$i]->getID().'] of type ['.get_class($dirtyObjects[$i]).'], aborting...');
                $this->abort();

                throw new FailedUnitCommitException($e->getMessage());
            } catch (LockingException $e) {
                self::$logger->error('Failed to save ID ['.$dirtyObjects[$i]->getID().'] of type ['.get_class($dirtyObjects[$i]).'], aborting...');
                $this->abort();

                throw new FailedUnitCommitException($e->getMessage());
            }
        }

        try {
            ActiveRecord::commit();

            $this->clearUnitOfWorkAttributes();

            if (method_exists($this, 'after_commit_callback')) {
                $this->{'after_commit_callback'}();
            }

            self::$logger->debug('<<commit');
        } catch (FailedSaveException $e) {
            self::$logger->debug('<<commit');
            throw new FailedUnitCommitException('Failed to commit the transaction, error is ['.$e->getMessage().']');
        }
    }

    /**
     * Method to clearup a cancelled unit of work.
     *
     * @throws \Alpha\Exception\AlphaException
     *
     * @since 1.0
     */
    public function abort()
    {
        self::$logger->debug('>>abort()');

        if (method_exists($this, 'before_abort_callback')) {
            $this->{'before_abort_callback'}();
        }

        try {
            ActiveRecord::rollback();

            $this->clearUnitOfWorkAttributes();

            if (method_exists($this, 'after_abort_callback')) {
                $this->{'after_abort_callback'}();
            }

            self::$logger->debug('<<abort');
        } catch (AlphaException $e) {
            self::$logger->debug('<<abort');
            throw new AlphaException('Failed to rollback the transaction, error is ['.$e->getMessage().']');
        }
    }

    /**
     * Clears the session and object attributes related to unit of work sessions.
     *
     * @since 1.0
     */
    public function clearUnitOfWorkAttributes()
    {
        $config = ConfigProvider::getInstance();
        $sessionProvider = $config->get('session.provider.name');
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');

        $session->delete('unitOfWork');
        $this->unitOfWork = null;
        $session->delete('dirtyObjects');
        $this->dirtyObjects = array();
        $session->delete('newObjects');
        $this->newObjects = array();
    }

    /**
     * Getter for the page title.
     *
     * @return string
     *
     * @since 1.0
     */
    public function getTitle()
    {
        self::$logger->debug('>>getTitle()');
        self::$logger->debug('<<getTitle ['.$this->title.']');

        return $this->title;
    }

    /**
     * Setter for the page title.
     *
     * @param string $title
     *
     * @since 1.0
     */
    public function setTitle($title)
    {
        self::$logger->debug('>>setTitle(title=['.$title.'])');
        self::$logger->debug('<<setTitle');
        $this->title = $title;
    }

    /**
     * Getter for the page description.
     *
     * @return string
     *
     * @since 1.0
     */
    public function getDescription()
    {
        self::$logger->debug('>>getDescription()');
        self::$logger->debug('<<getDescription ['.$this->description.']');

        return $this->description;
    }

    /**
     * Setter for the page description.
     *
     * @param string $description
     *
     * @since 1.0
     */
    public function setDescription($description)
    {
        self::$logger->debug('>>setDescription(description=['.$description.'])');
        self::$logger->debug('<<setDescription');
        $this->description = $description;
    }

    /**
     * Getter for the page keywords.
     *
     * @return string
     *
     * @since 1.0
     */
    public function getKeywords()
    {
        self::$logger->debug('>>getKeywords()');
        self::$logger->debug('<<getKeywords ['.$this->keywords.']');

        return $this->keywords;
    }

    /**
     * Setter for the page keywords, should pass a comma-seperated list as a string.
     *
     * @param string $keywords
     *
     * @since 1.0
     */
    public function setKeywords($keywords)
    {
        self::$logger->debug('>>setKeywords(keywords=['.$keywords.'])');
        self::$logger->debug('<<setKeywords');
        $this->keywords = $keywords;
    }

    /**
     * Method to return an access error for trespassing users.  HTTP response header code will be 403.
     *
     * @return \Alpha\Util\Http\Response
     *
     * @since 1.0
     */
    public function accessError()
    {
        self::$logger->debug('>>accessError()');

        if (method_exists($this, 'before_accessError_callback')) {
            $this->{'before_accessError_callback'}();
        }

        $config = ConfigProvider::getInstance();

        $sessionProvider = $config->get('session.provider.name');
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');

        if ($session->get('currentUser') !== false) {
            self::$logger->warn('The user ['.$session->get('currentUser')->get('email').'] attempted to access the resource ['.$this->request->getURI().'] but was denied due to insufficient rights');
        } else {
            self::$logger->warn('An unknown user attempted to access the resource ['.$this->request->getURI().'] but was denied due to insufficient rights');
        }

        $response = new Response(403);
        $response->setBody(View::renderErrorPage(403, 'You do not have the correct access rights to view this page.  If you have not logged in yet, try going back to the home page and logging in from there.'));

        if (method_exists($this, 'after_accessError_callback')) {
            $this->{'after_accessError_callback'}();
        }

        self::$logger->debug('<<accessError');

        return $response;
    }

    /**
     * Checks the user rights of the currently logged-in person against the page
     * visibility set for this controller.  Will return false if the user has
     * not got the correct rights.
     *
     * @return bool
     *
     * @since 1.0
     */
    public function checkRights()
    {
        self::$logger->debug('>>checkRights()');

        $config = ConfigProvider::getInstance();

        $sessionProvider = $config->get('session.provider.name');
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');

        if (method_exists($this, 'before_checkRights_callback')) {
            $this->{'before_checkRights_callback'}();
        }

        // firstly if the page is Public then there is no issue
        if ($this->getVisibility() == 'Public') {
            if (method_exists($this, 'after_checkRights_callback')) {
                $this->{'after_checkRights_callback'}();
            }

            self::$logger->debug('<<checkRights [true]');

            return true;
        } else {
            // the person is logged in?
            if ($session->get('currentUser') !== false) {

                // if the visibility is 'Session', just being logged in enough
                if ($this->getVisibility() == 'Session') {
                    if (method_exists($this, 'after_checkRights_callback')) {
                        $this->{'after_checkRights_callback'}();
                    }

                    self::$logger->debug('<<checkRights [true]');

                    return true;
                }

                // checking for admins (can access everything)
                if ($session->get('currentUser')->inGroup('Admin')) {
                    if (method_exists($this, 'after_checkRights_callback')) {
                        $this->{'after_checkRights_callback'}();
                    }

                    self::$logger->debug('<<checkRights [true]');

                    return true;
                } elseif ($session->get('currentUser')->inGroup($this->getVisibility())) {
                    if (method_exists($this, 'after_checkRights_callback')) {
                        $this->{'after_checkRights_callback'}();
                    }

                    self::$logger->debug('<<checkRights [true]');

                    return true;
                // the person is editing their own profile which is allowed
                } elseif ((isset($this->record) && get_class($this->record) == 'Alpha\Model\Person') && $session->get('currentUser')->getUsername() == $this->record->getUsername()) {
                    if (method_exists($this, 'after_checkRights_callback')) {
                        $this->{'after_checkRights_callback'}();
                    }

                    self::$logger->debug('<<checkRights [true]');

                    return true;
                } else {
                    self::$logger->debug('<<checkRights [false]');

                    return false;
                }
            } else { // the person is NOT logged in
                self::$logger->debug('<<checkRights [false]');

                return false;
            }
        }
    }

    /**
     * Method to check the validity of the two hidden form security
     * fields which aim to ensure that a post to the controller is being sent from
     * the same server that is hosting it.
     *
     * @return bool
     *
     * @since 1.0
     */
    public function checkSecurityFields()
    {
        self::$logger->debug('>>checkSecurityFields()');

        $host = $this->request->getHost();
        $ip = $this->request->getIP();

        // the server hostname + today's date
        $var1 = rtrim(strtr(base64_encode(SecurityUtils::encrypt($host.date('Ymd'))), '+/', '-_'), '=');
        // the server's IP plus $var1
        $var2 = rtrim(strtr(base64_encode(SecurityUtils::encrypt($ip.$var1)), '+/', '-_'), '=');

        if ($this->request->getParam('var1') === null || $this->request->getParam('var2') === null) {
            self::$logger->warn('The required var1/var2 params where not provided on the HTTP request');
            self::$logger->debug('<<checkSecurityFields [false]');

            return false;
        }

        if ($var1 == $this->request->getParam('var1') && $var2 == $this->request->getParam('var2')) {
            self::$logger->debug('<<checkSecurityFields [true]');

            return true;
        } else {
            /*
             * Here we are implementing a "grace period" of one hour if the time is < 1:00AM, we will accept
             * a match for yesterday's date in the security fields
             *
             */

            // the server hostname + today's date less 1 hour (i.e. yesterday where time is < 1:00AM)
            $var1 = rtrim(strtr(base64_encode(SecurityUtils::encrypt($host.date('Ymd', (time()-3600)))), '+/', '-_'), '=');
            // the server's IP plus $var1
            $var2 = rtrim(strtr(base64_encode(SecurityUtils::encrypt($ip.$var1)), '+/', '-_'), '=');

            if ($var1 == $this->request->getParam('var1') && $var2 == $this->request->getParam('var2')) {
                self::$logger->debug('<<checkSecurityFields [true]');

                return true;
            } else {
                self::$logger->warn('The var1/var2 params provided are invalid, values: var1=['.$this->request->getParam('var1').'] var2=['.$this->request->getParam('var2').']');
                self::$logger->debug('<<checkSecurityFields [false]');

                return false;
            }
        }
    }

    /**
     * Generates the two security fields to prevent remote form processing.
     *
     * @return string[] An array containing the two fields
     *
     * @since 1.0
     */
    public static function generateSecurityFields()
    {
        if (self::$logger == null) {
            self::$logger = new Logger('Controller');
        }
        self::$logger->debug('>>generateSecurityFields()');

        $request = new Request(array('method' => 'GET'));

        $host = $request->getHost();
        $ip = $request->getIP();

        // the server hostname + today's date
        $var1 = rtrim(strtr(base64_encode(SecurityUtils::encrypt($host.date('Ymd'))), '+/', '-_'), '=');
        // the server's IP plus $var1
        $var2 = rtrim(strtr(base64_encode(SecurityUtils::encrypt($ip.$var1)), '+/', '-_'), '=');

        self::$logger->debug('<<generateSecurityFields [array('.$var1.', '.$var2.')]');

        return array($var1, $var2);
    }

    /**
     * Returns the name of a custom controller if one is found, otherwise returns null.
     *
     * @param string $ActiveRecordType The classname of the active record
     *
     * @return string
     *
     * @since 1.0
     */
    public static function getCustomControllerName($ActiveRecordType)
    {
        if (self::$logger == null) {
            self::$logger = new Logger('Controller');
        }
        self::$logger->debug('>>getCustomControllerName(ActiveRecordType=['.$ActiveRecordType.']');

        $config = ConfigProvider::getInstance();

        try {
            $class = new ReflectionClass($ActiveRecordType);
            $controllerName = $class->getShortname().'Controller';
        } catch (Exception $e) {
            self::$logger->warn('Bad active record name ['.$ActiveRecordType.'] passed to getCustomControllerName()');

            return;
        }

        self::$logger->debug('Custom controller name is ['.$controllerName.']');

        if (file_exists($config->get('app.root').'Controller/'.$controllerName.'.php')) {
            $controllerName = 'Controller\\'.$controllerName;
            self::$logger->debug('<<getCustomControllerName ['.$controllerName.']');

            return $controllerName;
        } elseif (file_exists($config->get('app.root').'Alpha/Controller/'.$controllerName.'.php')) {
            $controllerName = 'Alpha\Controller\\'.$controllerName;
            self::$logger->debug('<<getCustomControllerName ['.$controllerName.']');

            return $controllerName;
        } else {
            self::$logger->debug('<<getCustomControllerName');

            return;
        }
    }

    /**
     * Set the status message in the session to the value provided.
     *
     * @param string $message
     *
     * @since 1.0
     */
    public function setStatusMessage($message)
    {
        $config = ConfigProvider::getInstance();
        $sessionProvider = $config->get('session.provider.name');
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');

        $this->statusMessage = $message;
        $session->set('statusMessage', $message);
    }

    /**
     * Gets the current status message for this controller.  Note that by getting the current
     * status message, you clear out the value stored in the session so this method can only be used
     * to get the status message once for display purposes.
     *
     * @return string
     *
     * @since 1.0
     */
    public function getStatusMessage()
    {
        $config = ConfigProvider::getInstance();
        $sessionProvider = $config->get('session.provider.name');
        $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');

        $session->delete('statusMessage');

        return $this->statusMessage;
    }

    /**
     * Checks that the definition for the controller classname provided exists.  Will also return true
     * if you pass "/" for the root of the web application.
     *
     * @param string $controllerName
     *
     * @return bool
     *
     * @since 1.0
     * @deprecated
     */
    public static function checkControllerDefExists($controllerName)
    {
        if (self::$logger == null) {
            self::$logger = new Logger('Controller');
        }
        self::$logger->debug('>>checkControllerDefExists(controllerName=['.$controllerName.'])');

        $config = ConfigProvider::getInstance();

        $exists = false;

        if ($controllerName == '/') {
            $exists = true;
        }
        if (file_exists($config->get('app.root').'Controller/'.$controllerName.'.php')) {
            $exists = true;
        }
        if (file_exists($config->get('app.root').'Alpha/Controller/'.$controllerName.'.php')) {
            $exists = true;
        }

        self::$logger->debug('<<checkControllerDefExists ['.$exists.']');

        return $exists;
    }

    /**
     * Loads the definition for the controller classname provided.
     *
     * @param string $controllerName
     *
     * @throws \Alpha\Exception\IllegalArguementException
     *
     * @since 1.0
     */
    public static function loadControllerDef($controllerName)
    {
        if (self::$logger == null) {
            self::$logger = new Logger('Controller');
        }
        self::$logger->debug('>>loadControllerDef(controllerName=['.$controllerName.'])');

        $config = ConfigProvider::getInstance();

        if (file_exists($config->get('app.root').'Controller/'.$controllerName.'.php')) {
            require_once $config->get('app.root').'Controller/'.$controllerName.'.php';
        } elseif (file_exists($config->get('app.root').'Alpha/Controller/'.$controllerName.'.php')) {
            require_once $config->get('app.root').'Alpha/Controller/'.$controllerName.'.php';
        } else {
            throw new IllegalArguementException('The class ['.$controllerName.'] is not defined anywhere!');
        }

        self::$logger->debug('<<loadControllerDef');
    }

    /**
     * Method for determining if the current request URL is a secure one (has a tk string or not).
     *
     * @return bool True if the current URL contains a tk value, false otherwise
     *
     * @since 1.0
     */
    public function checkIfAccessingFromSecureURL()
    {
        if ($this->request->getParam('tk') != null || mb_strpos($this->request->getURI(), '/tk/') !== false) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Descrypts the HTTP param fieldnames in the array provided and returns the plain version.
     *
     * @param $params array
     *
     * @return array
     *
     * @since 1.2.2
     */
    private function decryptFieldNames($params)
    {
        $decrypted = array();

        foreach (array_keys($params) as $fieldname) {

            // set request params where fieldnames provided are based64 encoded and encrypted
            if (Validator::isBase64($fieldname)) {
                $decrypted[SecurityUtils::decrypt(base64_decode($fieldname))] = $params[$fieldname];
            }
        }

        return $decrypted;
    }

    /**
     * Converts the supplied string to a "slug" that is URL safe and suitable for SEO.
     *
     * @param string $URLPart     The part of the URL to use as the slug
     * @param string $seperator   The URL seperator to use (default is -)
     * @param array  $filter      An optional array of charactors to filter out
     * @param bool   $crc32Prefix Set to true if you want to prefix the slug with the CRC32 hash of the URLPart supplied
     *
     * @return string A URL slug
     *
     * @since 1.2.4
     */
    public static function generateURLSlug($URLPart, $seperator = '-', $filter = array(), $crc32Prefix = false)
    {
        $URLPart = trim($URLPart);

        if (count($filter) > 0) {
            $URLPart = str_replace($filter, ' ', $URLPart);
        }

        $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $URLPart);
        $clean = preg_replace("/[^a-zA-Z0-9\/\._|+ -]/", '', $clean);
        $clean = strtolower(trim($clean, '-'));
        $clean = preg_replace("/[\.\/_|+ -]+/", $seperator, $clean);

        if ($crc32Prefix) {
            $clean = hexdec(hash('crc32b', $URLPart)).$seperator.$clean;
        }

        return $clean;
    }

    /**
     * {@inheritdoc}
     *
     * @since 2.0
     *
     * @throws \Alpha\Exception\NotImplementedException
     * @param Request $request
     */
    public function doHEAD($request)
    {
        self::$logger->debug('doHEAD() called but not implement in child class, request URI ['.$request->getURI().']');
        throw new NotImplementedException('The HEAD method is not supported by this controller');
    }

    /**
     * {@inheritdoc}
     *
     * @since 2.0
     *
     * @throws \Alpha\Exception\NotImplementedException
     * @param Request $request
     */
    public function doGET($request)
    {
        self::$logger->debug('doGET() called but not implement in child class, request URI ['.$request->getURI().']');
        throw new NotImplementedException('The GET method is not supported by this controller');
    }

    /**
     * {@inheritdoc}
     *
     * @since 2.0
     *
     * @throws \Alpha\Exception\NotImplementedException
     * @param Request $request
     */
    public function doPOST($request)
    {
        self::$logger->debug('doPOST() called but not implement in child class, request URI ['.$request->getURI().']');
        throw new NotImplementedException('The POST method is not supported by this controller');
    }

    /**
     * {@inheritdoc}
     *
     * @since 2.0
     *
     * @throws \Alpha\Exception\NotImplementedException
     * @param Request $request
     */
    public function doPUT($request)
    {
        self::$logger->debug('doPUT() called but not implement in child class, request URI ['.$request->getURI().']');
        throw new NotImplementedException('The PUT method is not supported by this controller');
    }

    /**
     * {@inheritdoc}
     *
     * @since 2.0
     *
     * @throws \Alpha\Exception\NotImplementedException
     * @param Request $request
     */
    public function doPATCH($request)
    {
        self::$logger->debug('doPATCH() called but not implement in child class, request URI ['.$request->getURI().']');
        throw new NotImplementedException('The PATCH method is not supported by this controller');
    }

    /**
     * {@inheritdoc}
     *
     * @since 2.0
     *
     * @throws \Alpha\Exception\NotImplementedException
     * @param Request $request
     */
    public function doDELETE($request)
    {
        self::$logger->debug('doDELETE() called but not implement in child class, request URI ['.$request->getURI().']');
        throw new NotImplementedException('The DELETE method is not supported by this controller');
    }

    /**
     * {@inheritdoc}
     *
     * @since 2.0
     * @param Request $request
     */
    public function doOPTIONS($request)
    {
        $HTTPMethods = array('HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
        $supported = array();

        foreach ($HTTPMethods as $HTTPMethod) {
            $reflector = new \ReflectionMethod($this, 'do'.$HTTPMethod);
            $isOverridden = ($reflector->getDeclaringClass()->getName() === get_class($this));

            if ($isOverridden) {
                $supported[] = $HTTPMethod;
            }
        }

        $supported = implode(',', $supported);

        $response = new Response(200);
        $response->setHeader('Allow', $supported);

        return $response;
    }

    /**
     * {@inheritdoc}
     *
     * @since 2.0.2
     * @param Request $request
     */
    public function doTRACE($request)
    {
        $HTTPMethods = array('HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
        $supported = array();

        foreach ($HTTPMethods as $HTTPMethod) {
            $reflector = new \ReflectionMethod($this, 'do'.$HTTPMethod);
            $isOverridden = ($reflector->getDeclaringClass()->getName() === get_class($this));

            if ($isOverridden) {
                $supported[] = $HTTPMethod;
            }
        }

        $supported = implode(',', $supported);

        $response = new Response(405);
        $response->setHeader('Allow', $supported);

        return $response;
    }

    /**
     * Maps the supplied request with the appropiate method to run on this controller, for example
     * GET to doGET(), POST to doPOST() etc.  Returns the response generated by the method called.
     *
     * @param \Alpha\Util\Http\Request $request
     *
     * @return \Alpha\Util\Http\Response
     *
     * @since 2.0
     */
    public function process($request)
    {
        if (!$request instanceof Request) {
            throw new IllegalArguementException('The request passed to process is not a valid Request object');
        }

        $config = ConfigProvider::getInstance();

        $method = $request->getMethod();

        if (in_array($method, array('POST', 'PUT', 'PATCH'))) {
            if ($config->get('security.encrypt.http.fieldnames')) {
                $decryptedParams = $this->decryptFieldNames($request->getParams());
                $request->addParams($decryptedParams);

                if ($request->getParam('_METHOD') != null) {
                    $request->setMethod($request->getParam('_METHOD'));
                    $method = $request->getMethod();
                }
            }
        }

        $ProviderClassName = $config->get('app.renderer.provider.name');

        if ($ProviderClassName == 'auto' && $request->getAccept() != null) {
            View::setProvider('auto', $request->getAccept());
        }

        $this->request = $request;

        // check the current user's rights on access to the page controller
        if (!$this->checkRights()) {
            return $this->accessError();
        }

        switch ($method) {
            case 'HEAD':
                $response = $this->doHEAD($request);
            break;
            case 'GET':
                $response = $this->doGET($request);
            break;
            case 'POST':
                $response = $this->doPOST($request);
            break;
            case 'PUT':
                $response = $this->doPUT($request);
            break;
            case 'PATCH':
                $response = $this->doPATCH($request);
            break;
            case 'DELETE':
                $response = $this->doDELETE($request);
            break;
            case 'OPTIONS':
                $response = $this->doOPTIONS($request);
            break;
            case 'TRACE':
                $response = $this->doTRACE($request);
            break;
            default:
                $response = $this->doGET($request);
        }

        return $response;
    }

    /**
     * Get the request this controller is processing (if any).
     *
     * @return \Alpha\Util\Http\Request
     *
     * @since 2.0
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * Set the request this controller is processing.
     *
     * @param \Alpha\Util\Http\Request $request
     *
     * @since 2.0
     */
    public function setRequest($request)
    {
        if ($request instanceof Request) {
            $this->request = $request;
        } else {
            throw new IllegalArguementException('Invalid request object ['.print_r($request, true).'] passed');
        }
    }

    /**
     * Use this callback to inject in the admin menu template fragment.
     *
     * @return string
     *
     * @since 1.2
     */
    public function after_displayPageHead_callback()
    {
        $accept = $this->request->getAccept();

        if ($accept != 'application/json' && $this->checkIfAccessingFromSecureURL()) {
            $viewState = ViewState::getInstance();
            if ($viewState->get('renderAdminMenu') === true) {
                $config = ConfigProvider::getInstance();

                $sessionProvider = $config->get('session.provider.name');
                $session = ServiceFactory::getInstance($sessionProvider, 'Alpha\Util\Http\Session\SessionProviderInterface');

                if ($session->get('currentUser') !== false) {
                    $passwordResetRequired = SecurityUtils::checkAdminPasswordIsDefault($session->get('currentUser')->get('password'));
                    $menu = View::loadTemplateFragment('html', 'adminmenu.phtml', array('passwordResetRequired' => $passwordResetRequired));
                } else {
                    $menu = '';
                }

                return $menu;
            }
        } else {
            return '';
        }
    }
}
Alpha Framework 3.0.0 API Documentation API documentation generated by ApiGen