Пример #1
0
 /**
  * Testing the doGET method.
  */
 public function testDoGET()
 {
     $front = new FrontController();
     $request = new Request(array('method' => 'GET', 'URI' => '/'));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('text/html', $response->getHeader('Content-Type'), 'Testing the doGET method');
 }
Пример #2
0
 /**
  * Testing the doGET method.
  */
 public function testDoGET()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $request = new Request(array('method' => 'GET', 'URI' => '/log/' . urlencode($config->get('app.file.store.dir') . 'logs/alpha.log')));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('text/html', $response->getHeader('Content-Type'), 'Testing the doGET method');
 }
Пример #3
0
 /**
  * Testing the doGET method.
  */
 public function testDoGET()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $request = new Request(array('method' => 'GET', 'URI' => '/metric', 'params' => array('dir' => 'Alpha')));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('text/html', $response->getHeader('Content-Type'), 'Testing the doGET method');
 }
 /**
  * Testing the doPOST method.
  */
 public function testDoPOST()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $controller = new GenSecureQueryStringController();
     $securityParams = $controller->generateSecurityFields();
     $params = array('QS' => 'act=ViewArticle&oid=00000000001', 'var1' => $securityParams[0], 'var2' => $securityParams[1]);
     $request = new Request(array('method' => 'POST', 'URI' => '/gensecure', 'params' => $params));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doPOST method');
     $this->assertEquals('text/html', $response->getHeader('Content-Type'), 'Testing the doPOST method');
 }
Пример #5
0
 /**
  * Testing the doGET method.
  */
 public function testDoGET()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $request = new Request(array('method' => 'GET', 'URI' => '/image/' . urlencode($config->get('app.root') . 'public/images/icons/accept.png') . '/16/16/png/0.75/false/false'));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('image/jpeg', $response->getHeader('Content-Type'), 'Testing the doGET method');
     $request = new Request(array('method' => 'GET', 'URI' => '/image/' . urlencode($config->get('app.root') . 'public/images/icons/accept.png') . '/16/16/png/0.75/false/true'));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('image/jpeg', $response->getHeader('Content-Type'), 'Testing the doGET method with secure image and no tokens');
     $tokens = Controller::generateSecurityFields();
     $request = new Request(array('method' => 'GET', 'URI' => '/image/' . urlencode($config->get('app.root') . 'public/images/icons/accept.png') . '/16/16/png/0.75/false/true/' . urlencode($tokens[0]) . '/' . urlencode($tokens[1])));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('image/jpeg', $response->getHeader('Content-Type'), 'Testing the doGET method with secure image and valid tokens');
 }
Пример #6
0
 /**
  * Testing the doDELETE method.
  */
 public function testDoDELETE()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $controller = new TagController();
     $securityParams = $controller->generateSecurityFields();
     $article = $this->createArticle('testing');
     $article->save();
     $tags = $article->getPropObject('tags')->getRelatedObjects();
     $existingTags = array();
     foreach ($tags as $tag) {
         $existingTags['content_' . $tag->getOID()] = $tag->get('content');
     }
     $params = array('saveBut' => true, 'NewTagValue' => 'somenewtag', 'var1' => $securityParams[0], 'var2' => $securityParams[1]);
     $params = array_merge($params, $existingTags);
     $request = new Request(array('method' => 'POST', 'URI' => '/tag/' . urlencode('Alpha\\Model\\Article') . '/' . $article->getOID(), 'params' => $params));
     $response = $front->process($request);
     $tags = $article->getPropObject('tags')->getRelatedObjects();
     $found = false;
     $tagOID = '';
     foreach ($tags as $tag) {
         if ($tag->get('content') == 'somenewtag') {
             $found = true;
             $tagOID = $tag->getOID();
             break;
         }
     }
     $this->assertTrue($found, 'Checking that the new tag added was actually saved');
     $params = array('ActiveRecordOID' => $tagOID, 'var1' => $securityParams[0], 'var2' => $securityParams[1]);
     $request = new Request(array('method' => 'DELETE', 'URI' => '/tag/' . urlencode('Alpha\\Model\\Article') . '/' . $article->getOID(), 'params' => $params));
     $response = $front->process($request);
     $this->assertEquals(301, $response->getStatus(), 'Testing the doDELETE method');
     $this->assertTrue(strpos($response->getHeader('Location'), '/tag/' . urlencode('Alpha\\Model\\Article') . '/' . $article->getOID()) !== false, 'Testing the doDELETE method');
     $tags = $article->getPropObject('tags')->getRelatedObjects();
     $notFound = true;
     foreach ($tags as $tag) {
         if ($tag->get('content') == 'somenewtag') {
             $notFound = false;
             break;
         }
     }
     $this->assertTrue($notFound, 'Checking that a deleted tag was actually removed');
 }
 /**
  * Testing the doDELETE method.
  */
 public function testDoDELETE()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $controller = new ActiveRecordController();
     $securityParams = $controller->generateSecurityFields();
     $person = $this->createPersonObject('test');
     $person->save();
     $params = array('var1' => $securityParams[0], 'var2' => $securityParams[1]);
     $request = new Request(array('method' => 'DELETE', 'URI' => '/record/' . urlencode('Alpha\\Model\\Person') . '/' . $person->getOID(), 'params' => $params));
     $response = $front->process($request);
     $this->assertEquals(301, $response->getStatus(), 'Testing the doDELETE method');
     $this->assertTrue(strpos($response->getHeader('Location'), '/records/' . urlencode('Alpha\\Model\\Person')) !== false, 'Testing the doDELETE method');
     $person = $this->createPersonObject('test');
     $person->save();
     $params = array('var1' => $securityParams[0], 'var2' => $securityParams[1]);
     $request = new Request(array('method' => 'DELETE', 'URI' => '/tk/' . FrontController::encodeQuery('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=Alpha\\Model\\Person&ActiveRecordOID=' . $person->getOID()), 'params' => $params));
     $response = $front->process($request);
     $this->assertEquals(301, $response->getStatus(), 'Testing the doDELETE method');
     $this->assertTrue(strpos($response->getHeader('Location'), '/tk/') !== false, 'Testing the doDELETE method');
     $person = $this->createPersonObject('test');
     $person->save();
     $request = new Request(array('method' => 'DELETE', 'URI' => '/record/' . urlencode('Alpha\\Model\\Person') . '/' . $person->getOID(), 'params' => $params, 'headers' => array('Accept' => 'application/json')));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doDELETE method');
     $this->assertEquals('application/json', $response->getHeader('Content-Type'), 'Testing the doDELETE method');
     $this->assertEquals('deleted', json_decode($response->getBody())->message, 'Testing the doDELETE method');
 }
Пример #8
0
 /**
  * {@inheritdoc}
  */
 public function adminView($fields = array())
 {
     self::$logger->debug('>>adminView(fields=[' . var_export($fields, true) . '])');
     $config = ConfigProvider::getInstance();
     // the class name of the BO
     $fields['fullClassName'] = stripslashes(get_class($this->BO));
     // the table name in the DB for the BO
     $fields['tableName'] = $this->BO->getTableName();
     // record count for the BO in the DB
     $fields['count'] = $this->BO->checkTableExists() ? $this->BO->getCount() : '<span class="warning">unavailable</span>';
     // table exists in the DB?
     $fields['tableExists'] = $this->BO->checkTableExists() ? '<span class="success">Yes</span>' : '<span class="warning">No</span>';
     if ($this->BO->getMaintainHistory()) {
         $fields['tableExists'] = $this->BO->checkTableExists(true) ? '<span class="success">Yes</span>' : '<span class="warning">No history table</span>';
     }
     // table schema needs to be updated in the DB?
     $fields['tableNeedsUpdate'] = $this->BO->checkTableNeedsUpdate() ? '<span class="warning">Yes</span>' : '<span class="success">No</span>';
     // create button
     if ($this->BO->checkTableExists()) {
         if (isset($fields['createButtonURL'])) {
             $button = new Button("document.location = '" . $fields['createButtonURL'] . "'", 'Create New', 'create' . stripslashes(get_class($this->BO)) . 'But');
         } else {
             $button = new Button("document.location = '" . FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . get_class($this->BO)) . "'", 'Create New', 'create' . stripslashes(get_class($this->BO)) . 'But');
         }
         $fields['createButton'] = $button->render();
     } else {
         $fields['createButton'] = '';
     }
     // list all button
     if ($this->BO->checkTableExists()) {
         $button = new Button("document.location = '" . FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . get_class($this->BO) . '&start=0&limit=' . $config->get('app.list.page.amount')) . "'", 'List All', 'list' . stripslashes(get_class($this->BO)) . 'But');
         $fields['listButton'] = $button->render();
     } else {
         $fields['listButton'] = '';
     }
     // the create table button (if required)
     $html = '';
     if (!$this->BO->checkTableExists()) {
         $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('createTableBut')) : 'createTableBut';
         $button = new Button('submit', 'Create Table', $fieldname);
         $html .= $button->render();
         // hidden field so that we know which class to create the table for
         $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('createTableClass')) : 'createTableClass';
         $html .= '<input type="hidden" name="' . $fieldname . '" value="' . get_class($this->BO) . '"/>';
     }
     if ($html == '' && $this->BO->getMaintainHistory() && !$this->BO->checkTableExists(true)) {
         $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('createHistoryTableBut')) : 'createHistoryTableBut';
         $button = new Button('submit', 'Create History Table', $fieldname);
         $html .= $button->render();
         // hidden field so that we know which class to create the table for
         $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('createTableClass')) : 'createTableClass';
         $html .= '<input type="hidden" name="' . $fieldname . '" value="' . get_class($this->BO) . '"/>';
     }
     $fields['createTableButton'] = $html;
     // recreate and update table buttons (if required)
     $html = '';
     if ($this->BO->checkTableNeedsUpdate() && $this->BO->checkTableExists()) {
         $js = "if(window.jQuery) {\n                    BootstrapDialog.show({\n                        title: 'Confirmation',\n                        message: 'Are you sure you wish to recreate this class table (all data will be lost)?',\n                        buttons: [\n                            {\n                                icon: 'glyphicon glyphicon-remove',\n                                label: 'Cancel',\n                                cssClass: 'btn btn-default btn-xs',\n                                action: function(dialogItself){\n                                    dialogItself.close();\n                                }\n                            },\n                            {\n                                icon: 'glyphicon glyphicon-ok',\n                                label: 'Okay',\n                                cssClass: 'btn btn-default btn-xs',\n                                action: function(dialogItself) {\n                                    \$('[Id=\"" . ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('admin_' . stripslashes(get_class($this->BO)) . '_button_pressed')) : 'admin_' . stripslashes(get_class($this->BO)) . '_button_pressed') . "\"]').attr('value', 'recreateTableBut');\n                                    \$('#admin_" . stripslashes(get_class($this->BO)) . "').submit();\n                                    dialogItself.close();\n                                }\n                            }\n                        ]\n                    });\n                }";
         $button = new Button($js, 'Recreate Table', 'recreateTableBut');
         $html .= $button->render();
         // hidden field so that we know which class to recreate the table for
         $html .= '<input type="hidden" name="recreateTableClass" value="' . get_class($this->BO) . '"/>';
         $html .= '&nbsp;&nbsp;';
         $js = "if(window.jQuery) {\n                    BootstrapDialog.show({\n                        title: 'Confirmation',\n                        message: 'Are you sure you wish to attempt to modify this class table by adding new attributes?',\n                        buttons: [\n                            {\n                                icon: 'glyphicon glyphicon-remove',\n                                label: 'Cancel',\n                                cssClass: 'btn btn-default btn-xs',\n                                action: function(dialogItself){\n                                    dialogItself.close();\n                                }\n                            },\n                            {\n                                icon: 'glyphicon glyphicon-ok',\n                                label: 'Okay',\n                                cssClass: 'btn btn-default btn-xs',\n                                action: function(dialogItself) {\n                                    \$('[Id=\"" . ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('admin_' . stripslashes(get_class($this->BO)) . '_button_pressed')) : 'admin_' . stripslashes(get_class($this->BO)) . '_button_pressed') . "\"]').attr('value', 'updateTableBut');\n                                    \$('#admin_" . stripslashes(get_class($this->BO)) . "').submit();\n                                    dialogItself.close();\n                                }\n                            }\n                        ]\n                    });\n                }";
         $button = new Button($js, 'Update Table', 'updateTableBut');
         $html .= $button->render();
         // hidden field so that we know which class to update the table for
         $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('updateTableClass')) : 'updateTableClass';
         $html .= '<input type="hidden" name="' . $fieldname . '" value="' . get_class($this->BO) . '"/>';
         // hidden field to tell us which button was pressed
         $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('admin_' . stripslashes(get_class($this->BO)) . '_button_pressed')) : 'admin_' . stripslashes(get_class($this->BO)) . '_button_pressed';
         $html .= '<input type="hidden" id="' . $fieldname . '" name="' . $fieldname . '" value=""/>';
     }
     $fields['recreateOrUpdateButtons'] = $html;
     // buffer security fields to $formSecurityFields variable
     $fields['formSecurityFields'] = self::renderSecurityFields();
     self::$logger->debug('<<adminView [HTML]');
     return View::loadTemplate($this->BO, 'admin', $fields);
 }
Пример #9
0
 /**
  * Method for rendering the pagination links.
  *
  * @return string
  *
  * @since 1.0
  */
 protected function renderPageLinks()
 {
     $config = ConfigProvider::getInstance();
     $params = $this->request->getParams();
     $body = '';
     $end = $this->startPoint + $config->get('app.list.page.amount');
     if ($end > $this->resultCount) {
         $end = $this->resultCount;
     }
     if ($this->resultCount > 0) {
         $body .= '<p align="center">Displaying ' . ($this->startPoint + 1) . ' to ' . $end . ' of <strong>' . $this->resultCount . '</strong>.&nbsp;&nbsp;';
     } else {
         if (!empty($this->query)) {
             $body .= View::displayUpdateMessage('There were no search results for your query.');
         }
     }
     $body .= '<ul class="pagination">';
     if ($this->startPoint > 0) {
         // handle secure URLs
         if (isset($params['tk'])) {
             $body .= '<li><a href="' . FrontController::generateSecureURL('act=Search&q=' . $this->query . '&start=' . ($this->startPoint - $config->get('app.list.page.amount'))) . '">&laquo;</a></li>';
         } else {
             $body .= '<li><a href="' . $config->get('app.url') . '/search/' . $this->query . '/' . ($this->startPoint - $config->get('app.list.page.amount')) . '">&laquo;</a></li>';
         }
     } elseif ($this->resultCount > $config->get('app.list.page.amount')) {
         $body .= '<li class="disabled"><a href="#">&laquo;</a></li>';
     }
     $page = 1;
     for ($i = 0; $i < $this->resultCount; $i += $config->get('app.list.page.amount')) {
         if ($i != $this->startPoint) {
             // handle secure URLs
             if (isset($params['tk'])) {
                 $body .= '<li><a href="' . FrontController::generateSecureURL('act=Search&q=' . $this->query . '&start=' . $i) . '">' . $page . '</a></li>';
             } else {
                 $body .= '<li><a href="' . $config->get('app.url') . '/search/' . $this->query . '/' . $i . '">' . $page . '</a></li>';
             }
         } elseif ($this->resultCount > $config->get('app.list.page.amount')) {
             $body .= '<li class="active"><a href="#">' . $page . '</a></li>';
         }
         ++$page;
     }
     if ($this->resultCount > $end) {
         // handle secure URLs
         if (isset($params['tk'])) {
             $body .= '<li><a href="' . FrontController::generateSecureURL('act=Search&q=' . $this->query . '&start=' . ($this->startPoint + $config->get('app.list.page.amount'))) . '">Next-&gt;&gt;</a></li>';
         } else {
             $body .= '<li><a href="' . $config->get('app.url') . '/search/' . $this->query . '/' . ($this->startPoint + $config->get('app.list.page.amount')) . '">&raquo;</a></li>';
         }
     } elseif ($this->resultCount > $config->get('app.list.page.amount')) {
         $body .= '<li class="disabled"><a href="#">&raquo;</a></li>';
     }
     $body .= '</ul>';
     $body .= '</p>';
     return $body;
 }
Пример #10
0
 /**
  * Testing the doGET method.
  */
 public function testDoGET()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $person = $this->createPersonObject('test');
     $person->save();
     $request = new Request(array('method' => 'GET', 'URI' => '/excel/Person/' . $person->getOID()));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('application/vnd.ms-excel', $response->getHeader('Content-Type'), 'Testing the doGET method');
     $this->assertEquals('attachment; filename=Person-00000000001.xls', $response->getHeader('Content-Disposition'), 'Testing the doGET method');
 }
Пример #11
0
 /**
  * Generates a secure URL for downloading an attachment file via the ViewAttachment controller.
  *
  * @param string $filename
  *
  * @since 1.0
  */
 public function getAttachmentSecureURL($filename)
 {
     $config = ConfigProvider::getInstance();
     return FrontController::generateSecureURL('act=Alpha\\Controller\\AttachmentController&articleOID=' . $this->getOID() . '&filename=' . $filename);
 }
Пример #12
0
 /**
  * Testing the doGET method.
  */
 public function testDoGET()
 {
     $config = ConfigProvider::getInstance();
     $front = new FrontController();
     $article = $this->createArticle('testing');
     $article->save();
     $request = new Request(array('method' => 'GET', 'URI' => '/search/blah'));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('text/html', $response->getHeader('Content-Type'), 'Testing the doGET method');
     $request = new Request(array('method' => 'GET', 'URI' => '/search/blah/0/1'));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method with pagination params');
     $this->assertEquals('text/html', $response->getHeader('Content-Type'), 'Testing the doGET method');
 }
Пример #13
0
require_once __DIR__ . '/../vendor/autoload.php';
use Alpha\Controller\Front\FrontController;
use Alpha\Util\Config\ConfigProvider;
use Alpha\Util\Http\Filter\ClientBlacklistFilter;
use Alpha\Util\Http\Filter\IPBlacklistFilter;
use Alpha\Util\Http\Filter\ClientTempBlacklistFilter;
use Alpha\Util\Http\Request;
use Alpha\Util\Http\Response;
use Alpha\Exception\ResourceNotFoundException;
use Alpha\Exception\ResourceNotAllowedException;
use Alpha\View\View;
try {
    $config = ConfigProvider::getInstance();
    set_exception_handler('Alpha\\Util\\ErrorHandlers::catchException');
    set_error_handler('Alpha\\Util\\ErrorHandlers::catchError', $config->get('php.error.log.level'));
    $front = new FrontController();
    if ($config->get('security.client.blacklist.filter.enabled')) {
        $front->registerFilter(new ClientBlacklistFilter());
    }
    if ($config->get('security.ip.blacklist.filter.enabled')) {
        $front->registerFilter(new IPBlacklistFilter());
    }
    if ($config->get('security.client.temp.blacklist.filter.enabled')) {
        $front->registerFilter(new ClientTempBlacklistFilter());
    }
    $request = new Request();
    $response = $front->process($request);
} catch (ResourceNotFoundException $rnfe) {
    $response = new Response(404, View::renderErrorPage(404, $rnfe->getMessage(), array('Content-Type' => 'text/html')));
} catch (ResourceNotAllowedException $rnae) {
    $response = new Response(403, View::renderErrorPage(403, $rnae->getMessage(), array('Content-Type' => 'text/html')));
Пример #14
0
 /**
  * Custom list view.
  *
  * @param array $fields Hash array of HTML fields to pass to the template.
  *
  * @since 1.0
  */
 public function listView($fields = array())
 {
     self::$logger->debug('>>listView(fields=[' . var_export($fields, true) . '])');
     if (method_exists($this, 'before_listView_callback')) {
         $this->before_listView_callback();
     }
     $config = ConfigProvider::getInstance();
     // the form action
     $fields['formAction'] = $fields['URI'];
     // work out how many columns will be in the table
     $reflection = new \ReflectionClass(get_class($this->BO));
     $properties = array_keys($reflection->getDefaultProperties());
     $fields['colCount'] = 1 + count(array_diff($properties, $this->BO->getDefaultAttributes(), $this->BO->getTransientAttributes()));
     // get the class attributes
     $properties = $reflection->getProperties();
     $html = '';
     $html .= '<tr>';
     foreach ($properties as $propObj) {
         $propName = $propObj->name;
         // skip over password fields
         $property = $this->BO->getPropObject($propName);
         if (!($property instanceof String && $property->checkIsPassword())) {
             if (!in_array($propName, $this->BO->getDefaultAttributes()) && !in_array($propName, $this->BO->getTransientAttributes())) {
                 $html .= '  <th>' . $this->BO->getDataLabel($propName) . '</th>';
             }
             if ($propName == 'OID') {
                 $html .= '  <th>' . $this->BO->getDataLabel($propName) . '</th>';
             }
         } else {
             $fields['colCount'] = $fields['colCount'] - 1;
         }
     }
     $html .= '</tr><tr>';
     $fields['formHeadings'] = $html;
     $html = '';
     // and now the values
     foreach ($properties as $propObj) {
         $propName = $propObj->name;
         $property = $this->BO->getPropObject($propName);
         if (!($property instanceof String && $property->checkIsPassword())) {
             if (!in_array($propName, $this->BO->getDefaultAttributes()) && !in_array($propName, $this->BO->getTransientAttributes())) {
                 $propClass = get_class($this->BO->getPropObject($propName));
                 if ($propClass == 'Alpha\\Model\\Type\\Text') {
                     $text = htmlentities($this->BO->get($propName), ENT_COMPAT, 'utf-8');
                     if (mb_strlen($text) > 70) {
                         $html .= '  <td>&nbsp;' . mb_substr($text, 0, 70) . '...</td>';
                     } else {
                         $html .= '  <td>&nbsp;' . $text . '</td>';
                     }
                 } elseif ($propClass == 'Alpha\\Model\\Type\\DEnum') {
                     $html .= '  <td>&nbsp;' . $this->BO->getPropObject($propName)->getDisplayValue() . '</td>';
                 } else {
                     $html .= '  <td>&nbsp;' . $this->BO->get($propName) . '</td>';
                 }
             }
             if ($propName == 'OID') {
                 $html .= '  <td>&nbsp;' . $this->BO->getOID() . '</td>';
             }
         }
     }
     $html .= '</tr>';
     $fields['formFields'] = $html;
     $button = new Button("document.location = '" . FrontController::generateSecureURL('act=Detail&bo=' . get_class($this->BO) . '&oid=' . $this->BO->getOID()) . "';", 'View', 'viewBut');
     $fields['viewButton'] = $button->render();
     // supressing the edit/delete buttons for Sequences
     $fields['adminButtons'] = '';
     // buffer security fields to $formSecurityFields variable
     $fields['formSecurityFields'] = $this->renderSecurityFields();
     $html = $this->loadTemplate($this->BO, 'list', $fields);
     if (method_exists($this, 'after_listView_callback')) {
         $this->after_listView_callback();
     }
     self::$logger->debug('<<listView');
     return $html;
 }
Пример #15
0
 /**
  * Custom edit view.
  *
  * @param array $fields Hash array of HTML fields to pass to the template.
  *
  * @since 1.0
  *
  * @return string
  */
 public function editView($fields = array())
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $html = '<table cols="2" class="edit_view" style="width:100%; margin:0px">';
     $html .= '<form action="' . $fields['formAction'] . '" method="POST" accept-charset="UTF-8">';
     $textBox = new TextBox($this->BO->getPropObject('content'), $this->BO->getDataLabel('content'), 'content', '', 5, $this->BO->getID());
     $html .= $textBox->render();
     $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('version_num')) : 'version_num';
     $html .= '<input type="hidden" name="' . $fieldname . '" value="' . $this->BO->getVersion() . '"/>';
     $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('ActiveRecordOID')) : 'ActiveRecordOID';
     $html .= '<input type="hidden" name="' . $fieldname . '" value="' . $this->BO->getID() . '"/>';
     // render special buttons for admins only
     if ($session->get('currentUser')->inGroup('Admin') && strpos($fields['formAction'], '/tk/') !== false) {
         $html .= '<tr><td colspan="2">';
         $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('saveBut')) : 'saveBut';
         $temp = new Button('submit', 'Save', $fieldname);
         $html .= $temp->render();
         $html .= '&nbsp;&nbsp;';
         $js = "\$('#dialogDiv').text('Are you sure you wish to delete this item?');\n                \$('#dialogDiv').dialog({\n                buttons: {\n                    'OK': function(event, ui) {\n                        \$('[id=\"" . ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('ActiveRecordOID')) : 'ActiveRecordOID') . "\"]').attr('value', '" . $this->BO->getOID() . "');\n                        \$('#deleteForm').submit();\n                    },\n                    'Cancel': function(event, ui) {\n                        \$(this).dialog('close');\n                    }\n                }\n            })\n            \$('#dialogDiv').dialog('open');\n            return false;";
         $temp = new Button($js, 'Delete', 'deleteBut');
         $html .= $temp->render();
         $html .= '&nbsp;&nbsp;';
         $temp = new Button("document.location = '" . FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . get_class($this->BO)) . "'", 'Back to List', 'cancelBut');
         $html .= $temp->render();
         $html .= '</td></tr>';
         $html .= View::renderSecurityFields();
         $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('_METHOD')) : '_METHOD';
         $html .= '<input type="hidden" name="' . $fieldname . '" id="' . $fieldname . '" value="PUT"/>';
         $html .= '</form></table>';
     } else {
         $html .= '</table>';
         $html .= '<div align="center">';
         $temp = new Button('submit', 'Update Your Comment', 'saveBut' . $this->BO->getID());
         $html .= $temp->render();
         $html .= '</div>';
         $html .= View::renderSecurityFields();
         $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('_METHOD')) : '_METHOD';
         $html .= '<input type="hidden" name="' . $fieldname . '" id="' . $fieldname . '" value="PUT"/>';
         $html .= '</form>';
     }
     return $html;
 }
Пример #16
0
 /**
  * Renders the HTML <img> tag to the ViewImage controller, with all of the correct params to render the source
  * image in the desired resolution.
  *
  * @param $altText Set this value to render alternate text as part of the HTML link (defaults to no alternate text)
  *
  * @return string
  *
  * @since 1.0
  */
 public function renderHTMLLink($altText = '')
 {
     $config = ConfigProvider::getInstance();
     if ($this->secure->getBooleanValue()) {
         $params = Controller::generateSecurityFields();
         return '<img src="' . FrontController::generateSecureURL('act=Alpha\\Controller\\ImageController&source=' . $this->source . '&width=' . $this->width->getValue() . '&height=' . $this->height->getValue() . '&type=' . $this->sourceType->getValue() . '&quality=' . $this->quality->getValue() . '&scale=' . $this->scale->getValue() . '&secure=' . $this->secure->getValue() . '&var1=' . $params[0] . '&var2=' . $params[1]) . '"' . (empty($altText) ? '' : ' alt="' . $altText . '"') . ($config->get('cms.images.widget.bootstrap.responsive') ? ' class="img-responsive"' : '') . '/>';
     } else {
         return '<img src="' . FrontController::generateSecureURL('act=Alpha\\Controller\\ImageController&source=' . $this->source . '&width=' . $this->width->getValue() . '&height=' . $this->height->getValue() . '&type=' . $this->sourceType->getValue() . '&quality=' . $this->quality->getValue() . '&scale=' . $this->scale->getValue() . '&secure=' . $this->secure->getValue()) . '"' . (empty($altText) ? '' : ' alt="' . $altText . '"') . ($config->get('cms.images.widget.bootstrap.responsive') ? ' class="img-responsive"' : '') . '/>';
     }
 }
Пример #17
0
 /**
  * Testing the doGET method.
  */
 public function testDoGET()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $controller = new LogoutController();
     $securityParams = $controller->generateSecurityFields();
     $person = $this->createPersonObject('logintest');
     $person->save();
     $params = array('loginBut' => true, 'var1' => $securityParams[0], 'var2' => $securityParams[1], 'email' => '*****@*****.**', 'password' => 'passwordTest');
     $request = new Request(array('method' => 'POST', 'URI' => '/login', 'params' => $params));
     $response = $front->process($request);
     $this->assertEquals(301, $response->getStatus(), 'Testing the doPOST with correct password');
     $this->assertTrue($session->get('currentUser') instanceof Person, 'Testing that the user is logged in');
     $request = new Request(array('method' => 'GET', 'URI' => '/logout'));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('text/html', $response->getHeader('Content-Type'), 'Testing the doGET method');
     $this->assertFalse($session->get('currentUser'), 'Testing that the user is no longer logged in');
 }
Пример #18
0
 /**
  * Handle GET requests.
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @return Alpha\Util\Http\Response
  *
  * @since 2.0.3
  */
 public function doGET($request)
 {
     self::$logger->debug('>>doGET($request=[' . var_export($request, true) . '])');
     if ($request->getParam('displayphpinfo') != null) {
         ob_start();
         phpinfo();
         $body = ob_get_contents();
     } else {
         $body = View::displayPageHead($this);
         $url = FrontController::generateSecureURL('act=Alpha\\Controller\\PhpinfoController&displayphpinfo=true');
         $body .= '<iframe src="' . $url . '" style="border:none; overflow-x: scroll; overflow-y: scroll; width:100%; height:100vh;"></iframe>';
         $body .= View::displayPageFoot($this);
     }
     self::$logger->debug('<<doGET');
     return new Response(200, $body, array('Content-Type' => 'text/html', 'X-Frame-Options' => 'SAMEORIGIN'));
 }
Пример #19
0
 /**
  * Testing that a blacklisted IP cannot pass the IPBlacklistFilter filter.
  *
  * @since 1.2.3
  */
 public function testIPBlacklistFilter()
 {
     $_SERVER['REMOTE_ADDR'] = $this->badIP;
     $_SERVER['REQUEST_URI'] = '/';
     $request = new Request(array('method' => 'GET'));
     try {
         $front = new FrontController();
         $front->registerFilter(new IPBlacklistFilter());
         $front->process($request);
         $this->fail('Testing that a blacklisted IP cannot pass the IPBlacklistFilter filter');
     } catch (ResourceNotAllowedException $e) {
         $this->assertEquals('Not allowed!', $e->getMessage(), 'Testing that a blacklisted IP cannot pass the IPBlacklistFilter filter');
     }
 }
Пример #20
0
 /**
  * Login the user and re-direct to the defined destination.
  *
  * @param string $password The password supplied by the user logging in
  *
  * @throws Alpha\Exception\ValidationException
  *
  * @return Alpha\Util\Http\Response
  *
  * @since 1.0
  */
 protected function doLoginAndRedirect($password)
 {
     self::$logger->debug('>>doLoginAndRedirect(password=[' . $password . '])');
     $config = ConfigProvider::getInstance();
     if (!$this->personObject->isTransient() && $this->personObject->get('state') == 'Active') {
         if (password_verify($password, $this->personObject->get('password'))) {
             $sessionProvider = $config->get('session.provider.name');
             $session = SessionProviderFactory::getInstance($sessionProvider);
             $session->set('currentUser', $this->personObject);
             self::$logger->debug('Logging in [' . $this->personObject->get('email') . '] at [' . date('Y-m-d H:i:s') . ']');
             self::$logger->action('Login');
             $response = new Response(301);
             if ($this->getNextJob() != '') {
                 $response->redirect(FrontController::generateSecureURL('act=' . $this->getNextJob()));
                 $this->clearUnitOfWorkAttributes();
             } else {
                 $response->redirect($config->get('app.url'));
             }
             return $response;
         } else {
             throw new ValidationException('Failed to login user ' . $this->personObject->get('email') . ', the password is incorrect!');
             self::$logger->debug('<<doLoginAndRedirect');
         }
     }
 }
Пример #21
0
 /**
  * Method to render the reset password HTML form.
  *
  * @return string
  *
  * @since 1.0
  */
 public function displayResetForm()
 {
     $config = ConfigProvider::getInstance();
     $html = '<div class="bordered padded">';
     $html .= '<h1>Password reset</h1>';
     $html .= '<p>If you have forgotten your password, you can use this form to have a new password automatically generated and sent to your e-mail address.</p>';
     $html .= '<form action="' . FrontController::generateSecureURL('act=Alpha\\Controller\\LoginController&reset=true') . '" method="POST" id="resetForm" accept-charset="UTF-8">';
     $request = new Request(array('method' => 'GET'));
     $email = new String($request->getParam('email', ''));
     $email->setRule(Validator::REQUIRED_EMAIL);
     $email->setSize(70);
     $email->setHelper('Please provide a valid e-mail address!');
     $stringBox = new StringBox($email, $this->BO->getDataLabel('email'), 'email', 'resetForm', '50');
     $html .= $stringBox->render();
     $html .= '<div class="form-group lower spread">';
     $temp = new Button('submit', 'Reset Password', 'resetBut');
     $html .= $temp->render();
     $temp = new Button("document.location.replace('" . $config->get('app.url') . "')", 'Cancel', 'cancelBut');
     $html .= $temp->render();
     $html .= '</div>';
     $html .= $this->renderSecurityFields();
     $html .= '</form>';
     $html .= '</div>';
     return $html;
 }
Пример #22
0
 /**
  * Method for rendering the pagination links.
  *
  * @return string
  *
  * @since 2.0
  */
 protected function renderPageLinks()
 {
     $config = ConfigProvider::getInstance();
     $body = '';
     // the index of the last record displayed on this page
     $last = $this->start + $config->get('app.list.page.amount');
     // ensure that the last index never overruns the total record count
     if ($last > $this->recordCount) {
         $last = $this->recordCount;
     }
     // render a message for an empty list
     if ($this->recordCount > 0) {
         $body .= '<ul class="pagination">';
     } else {
         $body .= '<p align="center">The list is empty.&nbsp;&nbsp;</p>';
         return $body;
     }
     // render "Previous" link
     if ($this->start > 0) {
         // handle secure URLs
         if ($this->request->getParam('token', null) != null) {
             $body .= '<li><a href="' . FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . $this->request->getParam('ActiveRecordType') . '&start=' . ($this->start - $this->limit) . '&limit=' . $this->limit) . '">&lt;&lt;-Previous</a></li>';
         } else {
             $body .= '<li><a href="/records/' . urlencode($this->request->getParam('ActiveRecordType')) . '/' . ($this->start - $this->limit) . '/' . $this->limit . '">&lt;&lt;-Previous</a></li>';
         }
     } elseif ($this->recordCount > $this->limit) {
         $body .= '<li class="disabled"><a href="#">&lt;&lt;-Previous</a></li>';
     }
     // render the page index links
     if ($this->recordCount > $this->limit) {
         $page = 1;
         for ($i = 0; $i < $this->recordCount; $i += $this->limit) {
             if ($i != $this->start) {
                 // handle secure URLs
                 if ($this->request->getParam('token', null) != null) {
                     $body .= '<li><a href="' . FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . $this->request->getParam('ActiveRecordType') . '&start=' . $i . '&limit=' . $this->limit) . '">' . $page . '</a></li>';
                 } else {
                     $body .= '<li><a href="/records/' . urlencode($this->request->getParam('ActiveRecordType')) . '/' . $i . '/' . $this->limit . '">' . $page . '</a></li>';
                 }
             } elseif ($this->recordCount > $this->limit) {
                 // render an anchor for the current page
                 $body .= '<li class="active"><a href="#">' . $page . '</a></li>';
             }
             ++$page;
         }
     }
     // render "Next" link
     if ($this->recordCount > $last) {
         // handle secure URLs
         if ($this->request->getParam('token', null) != null) {
             $body .= '<li><a href="' . FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . $this->request->getParam('ActiveRecordType') . '&start=' . ($this->start + $this->limit) . '&limit=' . $this->limit) . '">Next-&gt;&gt;</a></li>';
         } else {
             $body .= '<li><a href="/records/' . urlencode($this->request->getParam('ActiveRecordType')) . '/' . ($this->start + $this->limit . '/' . $this->limit) . '">Next-&gt;&gt;</a></li>';
         }
     } elseif ($this->recordCount > $this->limit) {
         $body .= '<li class="disabled"><a href="#">Next-&gt;&gt;</a></li>';
     }
     $body .= '</ul>';
     return $body;
 }
 /**
  * Handle POST requests.
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @return Alpha\Util\Http\Response
  *
  * @since 1.0
  */
 public function doPOST($request)
 {
     self::$logger->debug('>>doPOST($request=[' . var_export($request, true) . '])');
     $config = ConfigProvider::getInstance();
     $params = $request->getParams();
     $body = View::displayPageHead($this);
     $body .= '<p class="alert alert-success">';
     if (isset($params['QS'])) {
         $body .= FrontController::generateSecureURL($params['QS']);
         self::$logger->action('Generated the secure URL in admin: ' . FrontController::generateSecureURL($params['QS']));
     }
     $body .= '</p>';
     $body .= $this->renderForm();
     $body .= View::displayPageFoot($this);
     self::$logger->debug('<<doPOST');
     return new Response(200, $body, array('Content-Type' => 'text/html'));
 }
Пример #24
0
 /**
  * Testing the doGET method.
  */
 public function testDoGET()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $article = $this->createArticleObject('test article');
     $article->save();
     $request = new Request(array('method' => 'GET', 'URI' => '/feed/' . urlencode('Alpha\\Model\\Article')));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('application/atom+xml', $response->getHeader('Content-Type'), 'Testing the doGET method');
     $request = new Request(array('method' => 'GET', 'URI' => '/feed/' . urlencode('Alpha\\Model\\Article') . '/RSS'));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('application/rss+xml', $response->getHeader('Content-Type'), 'Testing the doGET method');
     $request = new Request(array('method' => 'GET', 'URI' => '/feed/' . urlencode('Alpha\\Model\\Article') . '/RSS2'));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method');
     $this->assertEquals('application/rss+xml', $response->getHeader('Content-Type'), 'Testing the doGET method');
 }
Пример #25
0
 /**
  * Overrides the TCPDF::Image method to decrypt encrypted $file paths from the Image widget, then pass
  * them to the normal TCPDF::Image along with all of the other (unmodified) parameters.
  *
  * @param string $file    Name of the file containing the image.
  * @param float  $x       Abscissa of the upper-left corner.
  * @param float  $y       Ordinate of the upper-left corner.
  * @param float  $w       Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  * @param float  $h       Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  * @param string $type    Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
  * @param mixed  $link    URL or identifier returned by AddLink().
  * @param string $align   Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
  * @param bool   $resize  If true resize (reduce) the image to fit $w and $h (requires GD library).
  * @param int    $dpi     dot-per-inch resolution used on resize
  * @param string $palign  Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
  * @param bool   $ismask  true if this image is a mask, false otherwise
  * @param mixed  $imgmask image object returned by this function or false
  * @param mixed  $border  Indicates if borders must be drawn around the image. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
  *
  * @since 1.0
  */
 public function Image($file, $x = '', $y = '', $w = 0, $h = 0, $type = '', $link = '', $align = '', $resize = false, $dpi = 300, $palign = '', $ismask = false, $imgmask = false, $border = 0)
 {
     if (self::$logger == null) {
         self::$logger = new Logger('TCPDF');
     }
     $config = ConfigProvider::getInstance();
     self::$logger->debug('Processing image file URL [' . $file . ']');
     try {
         if (mb_strpos($file, '/tk/') !== false) {
             $start = mb_strpos($file, '/tk/') + 3;
             $end = mb_strlen($file);
             $tk = mb_substr($file, $start + 1, $end - ($start + 1));
             $decoded = FrontController::getDecodeQueryParams($tk);
             parent::Image($decoded['source'], $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $ismask, $imgmask, $border);
         } else {
             // it has no query string, so threat as a regular image URL
             if (Validator::isURL($file)) {
                 parent::Image($config->get('app.root') . '/' . Image::convertImageURLToPath($file), $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $ismask, $imgmask, $border);
             } else {
                 parent::Image($file, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $ismask, $imgmask, $border);
             }
         }
     } catch (\Exception $e) {
         self::$logger->error('Error processing image file URL [' . $file . '], error [' . $e->getMessage() . ']');
         throw $e;
     }
 }
Пример #26
0
 /**
  * Handle GET requests.
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @return Alpha\Util\Http\Response
  *
  * @since 1.0
  */
 public function doGET($request)
 {
     self::$logger->debug('>>doGET($request=[' . var_export($request, true) . '])');
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     // if there is nobody logged in, we will send them off to the Login controller to do so before coming back here
     if ($session->get('currentUser') === false) {
         self::$logger->info('Nobody logged in, invoking Login controller...');
         $controller = new LoginController();
         $controller->setName('LoginController');
         $controller->setRequest($request);
         $controller->setUnitOfWork(array('Alpha\\Controller\\LoginController', 'Alpha\\Controller\\InstallController'));
         self::$logger->debug('<<__construct');
         return $controller->doGET($request);
     }
     $params = $request->getParams();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $body = View::displayPageHead($this);
     $body .= '<h1>Installing the ' . $config->get('app.title') . ' application</h1>';
     try {
         $body .= $this->createApplicationDirs();
     } catch (\Exception $e) {
         $body .= View::displayErrorMessage($e->getMessage());
         $body .= View::displayErrorMessage('Aborting.');
         return new Response(500, $body, array('Content-Type' => 'text/html'));
     }
     // start a new database transaction
     ActiveRecord::begin();
     /*
      * Create DEnum tables
      */
     $DEnum = new DEnum();
     $DEnumItem = new DEnumItem();
     try {
         $body .= '<p>Attempting to create the DEnum tables...';
         if (!$DEnum->checkTableExists()) {
             $DEnum->makeTable();
         }
         self::$logger->info('Created the [' . $DEnum->getTableName() . '] table successfully');
         if (!$DEnumItem->checkTableExists()) {
             $DEnumItem->makeTable();
         }
         self::$logger->info('Created the [' . $DEnumItem->getTableName() . '] table successfully');
         // create a default article DEnum category
         $DEnum = new DEnum('Alpha\\Model\\Article::section');
         $DEnumItem = new DEnumItem();
         $DEnumItem->set('value', 'Main');
         $DEnumItem->set('DEnumID', $DEnum->getID());
         $DEnumItem->save();
         $body .= View::displayUpdateMessage('DEnums set up successfully.');
     } catch (\Exception $e) {
         $body .= View::displayErrorMessage($e->getMessage());
         $body .= View::displayErrorMessage('Aborting.');
         self::$logger->error($e->getMessage());
         ActiveRecord::rollback();
         return new Response(500, $body, array('Content-Type' => 'text/html'));
     }
     /*
      * Loop over each business object in the system, and create a table for it
      */
     $classNames = ActiveRecord::getBOClassNames();
     $loadedClasses = array();
     foreach ($classNames as $classname) {
         array_push($loadedClasses, $classname);
     }
     foreach ($loadedClasses as $classname) {
         try {
             $body .= '<p>Attempting to create the table for the class [' . $classname . ']...';
             try {
                 $BO = new $classname();
                 if (!$BO->checkTableExists()) {
                     $BO->makeTable();
                 } else {
                     if ($BO->checkTableNeedsUpdate()) {
                         $missingFields = $BO->findMissingFields();
                         $count = count($missingFields);
                         for ($i = 0; $i < $count; ++$i) {
                             $BO->addProperty($missingFields[$i]);
                         }
                     }
                 }
             } catch (FailedIndexCreateException $eice) {
                 // this are safe to ignore for now as they will be auto-created later once all of the tables are in place
                 self::$logger->warn($eice->getMessage());
             } catch (FailedLookupCreateException $elce) {
                 // this are safe to ignore for now as they will be auto-created later once all of the tables are in place
                 self::$logger->warn($elce->getMessage());
             }
             self::$logger->info('Created the [' . $BO->getTableName() . '] table successfully');
             $body .= View::displayUpdateMessage('Created the [' . $BO->getTableName() . '] table successfully');
         } catch (\Exception $e) {
             $body .= View::displayErrorMessage($e->getMessage());
             $body .= View::displayErrorMessage('Aborting.');
             self::$logger->error($e->getMessage());
             ActiveRecord::rollback();
             return new Response(500, $body, array('Content-Type' => 'text/html'));
         }
     }
     $body .= View::displayUpdateMessage('All business object tables created successfully!');
     /*
      * Create the Admin and Standard groups
      */
     $adminGroup = new Rights();
     $adminGroup->set('name', 'Admin');
     $standardGroup = new Rights();
     $standardGroup->set('name', 'Standard');
     try {
         try {
             $body .= '<p>Attempting to create the Admin and Standard groups...';
             $adminGroup->save();
             $standardGroup->save();
             self::$logger->info('Created the Admin and Standard rights groups successfully');
             $body .= View::displayUpdateMessage('Created the Admin and Standard rights groups successfully');
         } catch (FailedIndexCreateException $eice) {
             // this are safe to ignore for now as they will be auto-created later once all of the tables are in place
             self::$logger->warn($eice->getMessage());
         } catch (FailedLookupCreateException $elce) {
             // this are safe to ignore for now as they will be auto-created later once all of the tables are in place
             self::$logger->warn($elce->getMessage());
         }
     } catch (\Exception $e) {
         $body .= View::displayErrorMessage($e->getMessage());
         $body .= View::displayErrorMessage('Aborting.');
         self::$logger->error($e->getMessage());
         ActiveRecord::rollback();
         return new Response(500, $body, array('Content-Type' => 'text/html'));
     }
     /*
      * Save the admin user to the database in the right group
      */
     try {
         try {
             $body .= '<p>Attempting to save the Admin account...';
             $admin = new Person();
             $admin->set('displayName', 'Admin');
             $admin->set('email', $session->get('currentUser')->get('email'));
             $admin->set('password', $session->get('currentUser')->get('password'));
             $admin->save();
             self::$logger->info('Created the admin user account [' . $session->get('currentUser')->get('email') . '] successfully');
             $adminGroup->loadByAttribute('name', 'Admin');
             $lookup = $adminGroup->getMembers()->getLookup();
             $lookup->setValue(array($admin->getID(), $adminGroup->getID()));
             $lookup->save();
             self::$logger->info('Added the admin account to the Admin group successfully');
             $body .= View::displayUpdateMessage('Added the admin account to the Admin group successfully');
         } catch (FailedIndexCreateException $eice) {
             // this are safe to ignore for now as they will be auto-created later once all of the tables are in place
             self::$logger->warn($eice->getMessage());
         } catch (FailedLookupCreateException $elce) {
             // this are safe to ignore for now as they will be auto-created later once all of the tables are in place
             self::$logger->warn($elce->getMessage());
         }
     } catch (\Exception $e) {
         $body .= View::displayErrorMessage($e->getMessage());
         $body .= View::displayErrorMessage('Aborting.');
         self::$logger->error($e->getMessage());
         ActiveRecord::rollback();
         return new Response(500, $body, array('Content-Type' => 'text/html'));
     }
     $body .= '<br><p align="center"><a href="' . FrontController::generateSecureURL('act=Alpha\\Controller\\ListActiveRecordsController') . '">Administration Home Page</a></p><br>';
     $body .= View::displayPageFoot($this);
     // commit
     ActiveRecord::commit();
     self::$logger->info('Finished installation!');
     self::$logger->action('Installed the application');
     self::$logger->debug('<<doGET');
     return new Response(200, $body, array('Content-Type' => 'text/html'));
 }
 /**
  * Testing the doGET method.
  */
 public function testDoGET()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $uri = '/recordselector/m2m/1/hiddenformfield/' . urlencode('Alpha\\Model\\Person') . '/email/' . urlencode('Alpha\\Model\\Rights') . '/name/' . urlencode('Alpha\\Model\\Person') . '/1';
     $request = new Request(array('method' => 'GET', 'URI' => $uri));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method for MANY-TO-MANY relation');
     $this->assertEquals('text/html', $response->getHeader('Content-Type'), 'Testing the doGET method');
     $uri = '/recordselector/12m/1/hiddenformfield/' . urlencode('Alpha\\Model\\ArticleComment') . '/articleOID/content';
     $request = new Request(array('method' => 'GET', 'URI' => $uri));
     $response = $front->process($request);
     $this->assertEquals(200, $response->getStatus(), 'Testing the doGET method for ONE-TO-MANY relation');
     $this->assertEquals('text/html', $response->getHeader('Content-Type'), 'Testing the doGET method');
 }
Пример #28
0
 public function testDoPUT()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $controller = new ArticleController();
     $article = $this->createArticleObject('test article');
     $article->save();
     if (!file_exists($article->getAttachmentsLocation())) {
         mkdir($article->getAttachmentsLocation(), 0774);
     }
     $person = $this->createPersonObject('test');
     $person->save();
     $session->set('currentUser', $person);
     $securityParams = $controller->generateSecurityFields();
     $attachment = array('name' => 'logo.png', 'type' => 'image/png', 'tmp_name' => $config->get('app.root') . 'public/images/logo-small.png');
     $params = array('uploadBut' => true, 'var1' => $securityParams[0], 'var2' => $securityParams[1]);
     $params = array_merge($params, $article->toArray());
     $request = new Request(array('method' => 'PUT', 'URI' => '/a/test-article', 'params' => $params, 'files' => array('userfile' => $attachment)));
     $response = $front->process($request);
     $this->assertEquals(301, $response->getStatus(), 'Testing the doPUT method');
     $this->assertTrue(strpos($response->getHeader('Location'), '/a/test-article/edit') !== false, 'Testing the doPUT method');
     $this->assertTrue(file_exists($article->getAttachmentsLocation() . '/logo.png'));
     $params = array('deletefile' => 'logo.png', 'var1' => $securityParams[0], 'var2' => $securityParams[1]);
     $params = array_merge($params, $article->toArray());
     $request = new Request(array('method' => 'PUT', 'URI' => '/a/test-article', 'params' => $params));
     $response = $front->process($request);
     $this->assertEquals(301, $response->getStatus(), 'Testing the doPUT method');
     $this->assertTrue(strpos($response->getHeader('Location'), '/a/test-article/edit') !== false, 'Testing the doPUT method');
     $this->assertFalse(file_exists($article->getAttachmentsLocation() . '/logo.png'));
 }
Пример #29
0
 /**
  * Renders a form to enable article editing with attachments options.
  *
  * @param array $fields hash array of HTML fields to pass to the template
  *
  * @since 1.0
  *
  * @return string
  */
 public function editView($fields = array())
 {
     if (method_exists($this, 'before_editView_callback')) {
         $this->before_editView_callback();
     }
     $config = ConfigProvider::getInstance();
     // the form action
     if (isset($fields['URI'])) {
         $fields['formAction'] = $fields['URI'];
     }
     // the form ID
     $fields['formID'] = stripslashes(get_class($this->BO)) . '_' . $this->BO->getID();
     // buffer form fields to $formFields
     $fields['formFields'] = $this->renderAllFields('edit');
     // buffer HTML output for Create and Cancel buttons
     $button = new Button('submit', 'Save', 'saveBut');
     $fields['saveButton'] = $button->render();
     $js = "if(window.jQuery) {\n                    BootstrapDialog.show({\n                        title: 'Confirmation',\n                        message: 'Are you sure you wish to delete this item?',\n                        buttons: [\n                            {\n                                icon: 'glyphicon glyphicon-remove',\n                                label: 'Cancel',\n                                cssClass: 'btn btn-default btn-xs',\n                                action: function(dialogItself){\n                                    dialogItself.close();\n                                }\n                            },\n                            {\n                                icon: 'glyphicon glyphicon-ok',\n                                label: 'Okay',\n                                cssClass: 'btn btn-default btn-xs',\n                                action: function(dialogItself) {\n                                    \$('[id=\"" . ($config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('ActiveRecordOID')) : 'ActiveRecordOID') . "\"]').attr('value', '" . $this->BO->getOID() . "');\n                                    \$('#deleteForm').submit();\n                                    dialogItself.close();\n                                }\n                            }\n                        ]\n                    });\n                }";
     $button = new Button($js, 'Delete', 'deleteBut');
     $fields['deleteButton'] = $button->render();
     $button = new Button("document.location = '" . FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . get_class($this->BO) . '&start=0&limit=' . $config->get('app.list.page.amount')) . "'", 'Back to List', 'cancelBut');
     $fields['cancelButton'] = $button->render();
     $tags = array();
     if (is_object($this->BO->getPropObject('tags'))) {
         $tags = $this->BO->getPropObject('tags')->getRelatedObjects();
     }
     if (count($tags) > 0) {
         $button = new Button("document.location = '" . FrontController::generateSecureURL('act=Alpha\\Controller\\TagController&ActiveRecordType=' . get_class($this->BO) . '&ActiveRecordOID=' . $this->BO->getOID()) . "'", 'Edit Tags', 'tagsBut');
         $fields['tagsButton'] = $button->render();
     }
     // buffer security fields to $formSecurityFields variable
     $fields['formSecurityFields'] = $this->renderSecurityFields();
     // OID will need to be posted for optimistic lock checking
     $fields['version_num'] = $this->BO->getVersionNumber();
     // file attachments section
     $fields['fileAttachments'] = $this->renderFileUploadSection();
     if (method_exists($this, 'after_editView_callback')) {
         $this->after_editView_callback();
     }
     return $this->loadTemplate($this->BO, 'edit', $fields);
 }
Пример #30
0
 /**
  * Testing default param values are handled correctly.
  */
 public function testDefaultParamValues()
 {
     $_SERVER['REQUEST_URI'] = '/';
     $front = new FrontController();
     $front->addRoute('/one/{param}', function ($request) {
         return new Response(200, $request->getParam('param'));
     })->value('param', 'blah');
     $request = new Request(array('method' => 'GET', 'URI' => '/one'));
     $response = $front->process($request);
     $this->assertEquals('blah', $response->getBody(), 'Testing default param values are handled correctly');
     $front->addRoute('/two/{param1}/{param2}', function ($request) {
         return new Response(200, $request->getParam('param1') . ' ' . $request->getParam('param2'));
     })->value('param1', 'two')->value('param2', 'params');
     $request = new Request(array('method' => 'GET', 'URI' => '/two'));
     $response = $front->process($request);
     $this->assertEquals('two params', $response->getBody(), 'Testing default param values are handled correctly');
     $request = new Request(array('method' => 'GET', 'URI' => '/two/two'));
     $response = $front->process($request);
     $this->assertEquals('two params', $response->getBody(), 'Testing default param values are handled correctly');
     $front->addRoute('/three/{param1}/params/{param2}/{param3}', function ($request) {
         return new Response(200, $request->getParam('param1') . ' ' . $request->getParam('param2'));
     })->value('param1', 'has')->value('param2', 'three')->value('param3', 'params');
     $request = new Request(array('method' => 'GET', 'URI' => '/three/has/params'));
     $response = $front->process($request);
     $this->assertEquals('has three', $response->getBody(), 'Testing default param values are handled correctly');
 }