Пример #1
0
 /**
  * Constructor.
  *
  * @param Alpha\Model\ActiveRecord $BO
  *
  * @throws Alpha\Exception\IllegalArguementException
  *
  * @since 1.0
  */
 protected function __construct($BO)
 {
     self::$logger = new Logger('SequenceView');
     self::$logger->debug('>>__construct(BO=[' . var_export($BO, true) . '])');
     parent::__construct($BO);
     self::$logger->debug('<<__construct');
 }
Пример #2
0
 /**
  * Testing the renderAllFields() method.
  *
  * @since 2.0
  */
 public function testRenderAllFields()
 {
     $article = new Article();
     $article->set('title', 'Test Article');
     $this->view = View::getInstance($article);
     $this->assertNotEmpty($this->view->renderAllFields('view'), 'Testing the renderAllFields() method');
     $this->assertTrue(strpos($this->view->renderAllFields('view'), 'Test Article') !== false, 'Testing the renderAllFields() method');
 }
 /**
  * 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'));
 }
Пример #4
0
 /**
  * {@inheritdoc}
  */
 public static function renderErrorPage($code, $message)
 {
     $config = ConfigProvider::getInstance();
     $html = View::loadTemplateFragment('html', 'head.phtml', array('title' => $code . ' - ' . $message, 'description' => $message, 'allowCSSOverrides' => false));
     $html .= '</head>';
     $html .= '<body>';
     $html .= '<div class="container">';
     $html .= self::displayErrorMessage('<strong>' . $code . ':</strong> ' . $message);
     $html .= '<div align="center"><a href="' . $config->get('app.url') . '">Home Page</a></div>';
     $html .= '</div></body></html>';
     return $html;
 }
Пример #5
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;
 }
Пример #6
0
 /**
  * Custom edit view.
  *
  * @return string
  *
  * @since 1.0
  */
 public function editView($fields = array())
 {
     $config = ConfigProvider::getInstance();
     $labels = $this->BO->getDataLabels();
     $obj_type = '';
     $html = '<form action="' . $fields['URI'] . '" method="POST" accept-charset="UTF-8">';
     $temp = new StringBox($this->BO->getPropObject('name'), $labels['name'], 'name', '', 0, true, true);
     $html .= $temp->render();
     $html .= '<h3>DEnum display values:</h3>';
     // now get all of the options for the enum and render
     $denum = $this->BO;
     $tmp = new DEnumItem();
     $denumItems = $tmp->loadItems($denum->getID());
     foreach ($denumItems as $item) {
         $labels = $item->getDataLabels();
         $temp = new StringBox($item->getPropObject('value'), $labels['value'], 'value_' . $item->getID(), '');
         $html .= $temp->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() . '"/>';
     $html .= '<h3>Add a new value to the DEnum dropdown list:</h3>';
     $temp = new StringBox(new String(), 'Dropdown value', 'new_value', '');
     $html .= $temp->render();
     $temp = new Button('submit', 'Save', 'saveBut');
     $html .= $temp->render();
     $html .= '&nbsp;&nbsp;';
     $temp = new Button("document.location = '" . FrontController::generateSecureURL('act=Alpha\\Controller\\DEnumController') . "'", 'Back to List', 'cancelBut');
     $html .= $temp->render();
     $html .= '';
     $html .= View::renderSecurityFields();
     $html .= '</form>';
     return $html;
 }
Пример #7
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;
 }
Пример #8
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();
     if ($config->get('app.check.installed') && !ActiveRecord::isInstalled()) {
         $response = new Response(301);
         $response->redirect($config->get('app.url') . '/install');
         self::$logger->warn('App not installed so re-directing to the install controller');
         self::$logger->debug('<<doGET');
         return $response;
     }
     $params = $request->getParams();
     $body = View::loadTemplateFragment('html', 'head.phtml', array('title' => $config->get('app.title'), 'description' => 'Welcome to our site', 'allowCSSOverrides' => true));
     $body .= View::loadTemplateFragment('html', 'index.phtml');
     $body .= View::loadTemplateFragment('html', 'footer.phtml');
     self::$logger->debug('<<doGET');
     return new Response(200, $body, array('Content-Type' => 'text/html'));
 }
Пример #9
0
 /**
  * Renders the detail view for the Article, with edit button pointed to the ArticleController.
  *
  * @param array $fields Hash array of fields to pass to the template
  *
  * @return string
  *
  * @since 2.0.1
  */
 public function detailedView($fields = array())
 {
     $fields['editButtonURL'] = FrontController::generateSecureURL('act=Alpha\\Controller\\ArticleController&ActiveRecordType=' . get_class($this->BO) . '&ActiveRecordOID=' . $this->BO->getOID() . '&view=edit');
     return parent::detailedView($fields);
 }
Пример #10
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) . '])');
     $params = $request->getParams();
     $config = ConfigProvider::getInstance();
     if ($this->record instanceof Person) {
         self::$logger->debug('Logging out [' . $this->record->get('email') . '] at [' . date('Y-m-d H:i:s') . ']');
         self::$logger->action('Logout');
     }
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $session->destroy();
     $body = View::displayPageHead($this);
     $body .= View::displayUpdateMessage('You have successfully logged out of the system.');
     $body .= '<div align="center"><a href="' . $config->get('app.url') . '">Home Page</a></div>';
     $body .= View::displayPageFoot($this);
     self::$logger->debug('<<doGET');
     return new Response(200, $body, array('Content-Type' => 'text/html'));
 }
Пример #11
0
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')));
}
if ($config->get('security.http.header.x.frame.options') != '' && $response->getHeader('X-Frame-Options') == null) {
    $response->setHeader('X-Frame-Options', $config->get('security.http.header.x.frame.options'));
}
echo $response->send();
Пример #12
0
 /**
  * Method to create the DEnum tables if they don't exist.
  *
  * @since 1.0
  *
  * @return string
  */
 private function createDEnumTables()
 {
     $tmpDEnum = new DEnum();
     $body = '<p>Attempting to build table ' . DEnum::TABLE_NAME . ' for class DEnum : </p>';
     try {
         $tmpDEnum->makeTable();
         $body .= View::displayUpdateMessage('Successfully re-created the database table ' . DEnum::TABLE_NAME);
         self::$logger->action('Re-created the table ' . DEnum::TABLE_NAME);
     } catch (AlphaException $e) {
         $body .= View::displayErrorMessage('Failed re-created the database table ' . DEnum::TABLE_NAME . ', check the log');
         self::$logger->error($e->getMessage());
     }
     $tmpDEnumItem = new DEnumItem();
     $body .= '<p>Attempting to build table ' . DEnumItem::TABLE_NAME . ' for class DEnumItem : </p>';
     try {
         $tmpDEnumItem->makeTable();
         $body .= View::displayUpdateMessage('Successfully re-created the database table ' . DEnumItem::TABLE_NAME);
         self::$logger->action('Re-created the table ' . DEnumItem::TABLE_NAME);
     } catch (AlphaException $e) {
         $body .= View::displayErrorMessage('Failed re-created the database table ' . DEnumItem::TABLE_NAME . ', check the log');
         self::$logger->error($e->getMessage());
     }
     return $body;
 }
Пример #13
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'));
 }
Пример #14
0
 /**
  * Handle POST requests (adds $currentUser Person to the session).
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @return Alpha\Util\Http\Response
  *
  * @throws Alpha\Exception\IllegalArguementException
  *
  * @since 1.0
  */
 public function doPOST($request)
 {
     self::$logger->debug('>>doPOST($request=[' . var_export($request, true) . '])');
     $params = $request->getParams();
     if (!is_array($params)) {
         throw new IllegalArguementException('Bad $params [' . var_export($params, true) . '] passed to doPOST method!');
     }
     $config = ConfigProvider::getInstance();
     $body = '';
     try {
         // check the hidden security fields before accepting the form POST data
         if (!$this->checkSecurityFields()) {
             throw new SecurityException('This page cannot accept post data from remote servers!');
         }
         if (isset($params['loginBut'])) {
             // if the database has not been set up yet, accept a login from the config admin username/password
             if (!ActiveRecord::isInstalled()) {
                 if ($params['email'] == $config->get('app.install.username') && password_verify($params['password'], password_hash($config->get('app.install.password'), PASSWORD_DEFAULT, ['cost' => 12]))) {
                     self::$logger->info('Logging in [' . $params['email'] . '] at [' . date('Y-m-d H:i:s') . ']');
                     $admin = new Person();
                     $admin->set('displayName', 'Admin');
                     $admin->set('email', $params['email']);
                     $admin->set('password', password_hash($params['password'], PASSWORD_DEFAULT, ['cost' => 12]));
                     $admin->set('OID', '00000000001');
                     $sessionProvider = $config->get('session.provider.name');
                     $session = SessionProviderFactory::getInstance($sessionProvider);
                     $session->set('currentUser', $admin);
                     $response = new Response(301);
                     if ($this->getNextJob() != '') {
                         $response->redirect(FrontController::generateSecureURL('act=' . $this->getNextJob()));
                         $this->clearUnitOfWorkAttributes();
                     } else {
                         $response->redirect(FrontController::generateSecureURL('act=InstallController'));
                     }
                     return $response;
                 } else {
                     throw new ValidationException('Failed to login user ' . $params['email'] . ', the password is incorrect!');
                 }
             } else {
                 // here we are attempting to load the person from the email address
                 $this->personObject->loadByAttribute('email', $params['email'], true);
                 ActiveRecord::disconnect();
                 // checking to see if the account has been disabled
                 if (!$this->personObject->isTransient() && $this->personObject->get('state') == 'Disabled') {
                     throw new SecurityException('Failed to login user ' . $params['email'] . ', that account has been disabled!');
                 }
                 // check the password
                 return $this->doLoginAndRedirect($params['password']);
             }
             $body .= View::displayPageHead($this);
             $body .= $this->personView->displayLoginForm();
         }
         if (isset($params['resetBut'])) {
             // here we are attempting to load the person from the email address
             $this->personObject->loadByAttribute('email', $params['email']);
             ActiveRecord::disconnect();
             // generate a new random password
             $newPassword = $this->personObject->generatePassword();
             // now encrypt and save the new password, then e-mail the user
             $this->personObject->set('password', password_hash($newPassword, PASSWORD_DEFAULT, ['cost' => 12]));
             $this->personObject->save();
             $message = 'The password for your account has been reset to ' . $newPassword . ' as you requested.  You can now login to the site using your ' . 'e-mail address and this new password as before.';
             $subject = 'Password change request';
             $this->personObject->sendMail($message, $subject);
             $body .= View::displayUpdateMessage('The password for the user <strong>' . $params['email'] . '</strong> has been reset, and the new password ' . 'has been sent to that e-mail address.');
             $body .= '<a href="' . $config->get('app.url') . '">Home Page</a>';
         }
     } catch (ValidationException $e) {
         $body .= View::displayPageHead($this);
         $body .= View::displayErrorMessage($e->getMessage());
         if (isset($params['reset'])) {
             $body .= $this->personView->displayResetForm();
         } else {
             $body .= $this->personView->displayLoginForm();
         }
         self::$logger->warn($e->getMessage());
     } catch (SecurityException $e) {
         $body .= View::displayPageHead($this);
         $body .= View::displayErrorMessage($e->getMessage());
         self::$logger->warn($e->getMessage());
     } catch (RecordNotFoundException $e) {
         $body .= View::displayPageHead($this);
         $body .= View::displayErrorMessage('Failed to find the user \'' . $params['email'] . '\'');
         if (isset($params['reset'])) {
             $body .= $this->personView->displayResetForm();
         } else {
             $body .= $this->personView->displayLoginForm();
         }
         self::$logger->warn($e->getMessage());
     }
     $body .= View::displayPageFoot($this);
     self::$logger->debug('<<doPOST');
     return new Response(200, $body, array('Content-Type' => 'text/html'));
 }
Пример #15
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();
     $body = View::displayPageHead($this);
     if ($request->getParam('dir')) {
         $dir = $request->getParam('dir');
     } else {
         $dir = $config->get('app.root');
     }
     $metrics = new Inspector($dir);
     $metrics->calculateLOC();
     $body .= $metrics->resultsToHTML();
     $body .= View::displayPageFoot($this);
     self::$logger->debug('<<doGET');
     return new Response(200, $body, array('Content-Type' => 'text/html'));
 }
Пример #16
0
 /**
  * Handle POST requests.
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @return Alpha\Util\Http\Response
  *
  * @throws Alpha\Exception\SecurityException
  * @throws Alpha\Exception\IllegalArguementException
  *
  * @since 1.0
  */
 public function doPOST($request)
 {
     self::$logger->debug('>>doPOST($request=[' . var_export($request, true) . '])');
     $params = $request->getParams();
     try {
         // check the hidden security fields before accepting the form POST data
         if (!$this->checkSecurityFields()) {
             throw new SecurityException('This page cannot accept post data from remote servers!');
         }
         if (isset($params['clearTaggedClass']) && $params['clearTaggedClass'] != '') {
             try {
                 self::$logger->info('About to start rebuilding the tags for the class [' . $params['clearTaggedClass'] . ']');
                 $startTime = microtime(true);
                 $record = new $params['clearTaggedClass']();
                 $records = $record->loadAll();
                 self::$logger->info('Loaded all of the active records (elapsed time [' . round(microtime(true) - $startTime, 5) . '] seconds)');
                 ActiveRecord::begin();
                 $tag = new Tag();
                 $tag->deleteAllByAttribute('taggedClass', $params['clearTaggedClass']);
                 self::$logger->info('Deleted all of the old tags (elapsed time [' . round(microtime(true) - $startTime, 5) . '] seconds)');
                 $this->regenerateTagsOnRecords($records);
                 self::$logger->info('Saved all of the new tags (elapsed time [' . round(microtime(true) - $startTime, 5) . '] seconds)');
                 self::$logger->action('Tags recreated on the [' . $params['clearTaggedClass'] . '] class');
                 ActiveRecord::commit();
                 $this->setStatusMessage(View::displayUpdateMessage('Tags recreated on the ' . $record->getFriendlyClassName() . ' class.'));
                 self::$logger->info('Tags recreated on the [' . $params['clearTaggedClass'] . '] class (time taken [' . round(microtime(true) - $startTime, 5) . '] seconds).');
             } catch (AlphaException $e) {
                 self::$logger->error($e->getMessage());
                 ActiveRecord::rollback();
             }
             ActiveRecord::disconnect();
             return $this->doGET($request);
         } elseif (isset($params['ActiveRecordType']) && isset($params['ActiveRecordOID'])) {
             $ActiveRecordType = urldecode($params['ActiveRecordType']);
             $ActiveRecordOID = $params['ActiveRecordOID'];
             if (class_exists($ActiveRecordType)) {
                 $record = new $ActiveRecordType();
             } else {
                 throw new IllegalArguementException('No ActiveRecord available to display tags for!');
             }
             if (isset($params['saveBut'])) {
                 try {
                     $record->load($ActiveRecordOID);
                     $tags = $record->getPropObject('tags')->getRelatedObjects();
                     ActiveRecord::begin();
                     foreach ($tags as $tag) {
                         $tag->set('content', Tag::cleanTagContent($params['content_' . $tag->getID()]));
                         $tag->save();
                         self::$logger->action('Saved tag ' . $tag->get('content') . ' on ' . $ActiveRecordType . ' instance with OID ' . $ActiveRecordOID);
                     }
                     // handle new tag if posted
                     if (isset($params['NewTagValue']) && trim($params['NewTagValue']) != '') {
                         $newTag = new Tag();
                         $newTag->set('content', Tag::cleanTagContent($params['NewTagValue']));
                         $newTag->set('taggedOID', $ActiveRecordOID);
                         $newTag->set('taggedClass', $ActiveRecordType);
                         $newTag->save();
                         self::$logger->action('Created a new tag ' . $newTag->get('content') . ' on ' . $ActiveRecordType . ' instance with OID ' . $ActiveRecordOID);
                     }
                     ActiveRecord::commit();
                     $this->setStatusMessage(View::displayUpdateMessage('Tags on ' . get_class($record) . ' ' . $record->getID() . ' saved successfully.'));
                     return $this->doGET($request);
                 } catch (ValidationException $e) {
                     /*
                      * The unique key has most-likely been violated because this BO is already tagged with this
                      * value.
                      */
                     ActiveRecord::rollback();
                     $this->setStatusMessage(View::displayErrorMessage('Tags on ' . get_class($record) . ' ' . $record->getID() . ' not saved due to duplicate tag values, please try again.'));
                     return $this->doGET($request);
                 } catch (FailedSaveException $e) {
                     self::$logger->error('Unable to save the tags of id [' . $params['ActiveRecordOID'] . '], error was [' . $e->getMessage() . ']');
                     ActiveRecord::rollback();
                     $this->setStatusMessage(View::displayErrorMessage('Tags on ' . get_class($record) . ' ' . $record->getID() . ' not saved, please check the application logs.'));
                     return $this->doGET($request);
                 }
                 ActiveRecord::disconnect();
             }
         } else {
             return parent::doPOST($request);
         }
     } catch (SecurityException $e) {
         $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
         self::$logger->warn($e->getMessage());
     } catch (IllegalArguementException $e) {
         self::$logger->error($e->getMessage());
     } catch (RecordNotFoundException $e) {
         self::$logger->warn($e->getMessage());
         $this->setStatusMessage(View::displayErrorMessage('Failed to load the requested item from the database!'));
     }
     self::$logger->debug('<<doPOST');
 }
Пример #17
0
 /**
  * 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 = SessionProviderFactory::getInstance($sessionProvider);
             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 '';
     }
 }
Пример #18
0
 /**
  * Method for displaying the user comments for the article.
  *
  * @return string
  *
  * @since 1.0
  */
 private function renderComments()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $html = '';
     $comments = $this->record->getArticleComments();
     $commentsCount = count($comments);
     $URL = FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=Alpha\\Model\\ArticleComment');
     $fields = array('formAction' => $URL);
     if ($config->get('cms.display.comments') && $commentsCount > 0) {
         $html .= '<h2>There are [' . $commentsCount . '] user comments for this article</h2>';
         for ($i = 0; $i < $commentsCount; ++$i) {
             $view = View::getInstance($comments[$i]);
             $html .= $view->markdownView($fields);
         }
     }
     if ($session->get('currentUser') != null && $config->get('cms.comments.allowed')) {
         $comment = new ArticleComment();
         $comment->set('articleOID', $this->record->getID());
         $view = View::getInstance($comment);
         $html .= $view->createView($fields);
     }
     return $html;
 }
Пример #19
0
 /**
  * Testing the editView() method.
  *
  * @since 2.0
  */
 public function testEditView()
 {
     $articleComment = new ArticleComment();
     $articleComment->set('content', 'test comment');
     $articleComment->save();
     $view = View::getInstance($articleComment);
     $this->assertNotEmpty($view->editView(array('formAction' => '/')), 'Testing the editView() method');
     $this->assertTrue(strpos($view->editView(array('formAction' => '/')), 'Update Your Comment') !== false, 'Testing the editView() method');
 }
Пример #20
0
 /**
  * Method to handle DELETE requests.
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @throws Alpha\Exception\IllegalArguementException
  * @throws Alpha\Exception\SecurityException
  *
  * @return Alpha\Util\Http\Response
  *
  * @since 2.0
  */
 public function doDELETE($request)
 {
     self::$logger->debug('>>doDELETE(request=[' . var_export($request, true) . '])');
     $config = ConfigProvider::getInstance();
     $params = $request->getParams();
     $accept = $request->getAccept();
     try {
         // check the hidden security fields before accepting the form data
         if (!$this->checkSecurityFields()) {
             throw new SecurityException('This page cannot accept data from remote servers!');
         }
         if (isset($params['ActiveRecordType'])) {
             $ActiveRecordType = urldecode($params['ActiveRecordType']);
         } else {
             throw new IllegalArguementException('No ActiveRecord available to edit!');
         }
         if (class_exists($ActiveRecordType)) {
             $record = new $ActiveRecordType();
         } else {
             throw new IllegalArguementException('No ActiveRecord [' . $ActiveRecordType . '] available to edit!');
         }
         // check the hidden security fields before accepting the form POST data
         if (!$this->checkSecurityFields()) {
             throw new SecurityException('This page cannot accept post data from remote servers!');
         }
         $record->load($params['ActiveRecordOID']);
         ActiveRecord::begin();
         $record->delete();
         ActiveRecord::commit();
         ActiveRecord::disconnect();
         self::$logger->action('Deleted ' . $ActiveRecordType . ' instance with OID ' . $params['ActiveRecordOID']);
         if ($accept == 'application/json') {
             $response = new Response(200);
             $response->setHeader('Content-Type', 'application/json');
             $response->setBody(json_encode(array('message' => 'deleted')));
         } else {
             $response = new Response(301);
             if (isset($params['statusMessage'])) {
                 $this->setStatusMessage(View::displayUpdateMessage($params['statusMessage']));
             } else {
                 $this->setStatusMessage(View::displayUpdateMessage('Deleted'));
             }
             if ($this->getNextJob() != '') {
                 $response->redirect($this->getNextJob());
             } else {
                 if ($this->request->isSecureURI()) {
                     $response->redirect(FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . $ActiveRecordType . '&start=0&limit=' . $config->get('app.list.page.amount')));
                 } else {
                     $response->redirect($config->get('app.url') . '/records/' . $params['ActiveRecordType']);
                 }
             }
         }
     } catch (SecurityException $e) {
         self::$logger->warn($e->getMessage());
         throw new ResourceNotAllowedException($e->getMessage());
     } catch (RecordNotFoundException $e) {
         self::$logger->warn($e->getMessage());
         throw new ResourceNotFoundException('The item that you have requested cannot be found!');
     } catch (AlphaException $e) {
         self::$logger->error($e->getMessage());
         ActiveRecord::rollback();
     }
     self::$logger->debug('<<doDELETE');
     return $response;
 }
Пример #21
0
 /**
  * Handle POST requests.
  *
  * @param Alpha\Util\Http\Response $request
  *
  * @throws Alpha\Exception\SecurityException
  * @throws Alpha\Exception\IllegalArguementException
  *
  * @return Alpha\Util\Http\Response
  *
  * @since 1.0
  */
 public function doPOST($request)
 {
     self::$logger->debug('>>doPOST($request=[' . var_export($request, true) . '])');
     $params = $request->getParams();
     try {
         // check the hidden security fields before accepting the form POST data
         if (!$this->checkSecurityFields()) {
             throw new SecurityException('This page cannot accept post data from remote servers!');
         }
         if (!is_array($params)) {
             throw new IllegalArguementException('Bad $params [' . var_export($params, true) . '] passed to doPOST method!');
         }
         if (isset($params['clearCache']) && $params['clearCache'] == 'true') {
             try {
                 FileUtils::deleteDirectoryContents($this->dataDir, array('.htaccess', 'html', 'images', 'pdf', 'xls'));
                 $this->setStatusMessage(View::displayUpdateMessage('Cache contents deleted successfully.'));
                 $config = ConfigProvider::getInstance();
                 $sessionProvider = $config->get('session.provider.name');
                 $session = SessionProviderFactory::getInstance($sessionProvider);
                 self::$logger->info('Cache contents deleted successfully by user [' . $session->get('currentUser')->get('displayName') . '].');
             } catch (AlphaException $e) {
                 self::$logger->error($e->getMessage());
                 $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
             }
         }
         return $this->doGET($request);
     } catch (SecurityException $e) {
         $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
         self::$logger->warn($e->getMessage());
     } catch (IllegalArguementException $e) {
         self::$logger->error($e->getMessage());
         $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
     }
     $body = View::displayPageHead($this);
     $message = $this->getStatusMessage();
     if (!empty($message)) {
         $body .= $message;
     }
     $body .= View::displayPageFoot($this);
     self::$logger->debug('<<doPOST');
     return new Response(200, $body, array('Content-Type' => 'text/html'));
 }
Пример #22
0
 /**
  * Create the directories required by the application.
  *
  * @return string
  *
  * @since 2.0
  */
 public function createApplicationDirs()
 {
     self::$logger->debug('>>createApplicationDirs()');
     $config = ConfigProvider::getInstance();
     $body = '';
     // set the umask first before attempt mkdir
     umask(0);
     /*
      * Create the logs directory, then instantiate a new logger
      */
     $logsDir = $config->get('app.file.store.dir') . 'logs';
     $body .= '<p>Attempting to create the logs directory <em>' . $logsDir . '</em>...';
     if (!file_exists($logsDir)) {
         var_dump(mkdir($logsDir, 0774));
     }
     self::$logger = new Logger('InstallController');
     self::$logger->info('Started installation process!');
     self::$logger->info('Logs directory [' . $logsDir . '] successfully created');
     $body .= View::displayUpdateMessage('Logs directory [' . $logsDir . '] successfully created');
     /*
      * Create the src directory and sub-directories
      */
     $srcDir = $config->get('app.root') . 'src';
     $body .= '<p>Attempting to create the src directory <em>' . $srcDir . '</em>...';
     if (!file_exists($srcDir)) {
         mkdir($srcDir, 0774);
     }
     self::$logger->info('Source directory [' . $srcDir . '] successfully created');
     $body .= View::displayUpdateMessage('Source directory [' . $srcDir . '] successfully created');
     $srcDir = $config->get('app.root') . 'src/Model';
     if (!file_exists($srcDir)) {
         mkdir($srcDir, 0774);
     }
     self::$logger->info('Source directory [' . $srcDir . '] successfully created');
     $body .= View::displayUpdateMessage('Source directory [' . $srcDir . '] successfully created');
     $srcDir = $config->get('app.root') . 'src/View';
     if (!file_exists($srcDir)) {
         mkdir($srcDir, 0774);
     }
     self::$logger->info('Source directory [' . $srcDir . '] successfully created');
     $body .= View::displayUpdateMessage('Source directory [' . $srcDir . '] successfully created');
     /*
      * Create the attachments directory
      */
     $attachmentsDir = $config->get('app.file.store.dir') . 'attachments';
     $body .= '<p>Attempting to create the attachments directory <em>' . $attachmentsDir . '</em>...';
     if (!file_exists($attachmentsDir)) {
         mkdir($attachmentsDir, 0774);
     }
     self::$logger->info('Attachments directory [' . $attachmentsDir . '] successfully created');
     $body .= View::displayUpdateMessage('Attachments directory [' . $attachmentsDir . '] successfully created');
     /*
      * Create the cache directory and sub-directories
      */
     $cacheDir = $config->get('app.file.store.dir') . 'cache';
     $htmlDir = $config->get('app.file.store.dir') . 'cache/html';
     $imagesDir = $config->get('app.file.store.dir') . 'cache/images';
     $pdfDir = $config->get('app.file.store.dir') . 'cache/pdf';
     $xlsDir = $config->get('app.file.store.dir') . 'cache/xls';
     // cache
     $body .= '<p>Attempting to create the cache directory <em>' . $cacheDir . '</em>...';
     if (!file_exists($cacheDir)) {
         mkdir($cacheDir, 0774);
     }
     self::$logger->info('Cache directory [' . $cacheDir . '] successfully created');
     $body .= View::displayUpdateMessage('Cache directory [' . $cacheDir . '] successfully created');
     // cache/html
     $body .= '<p>Attempting to create the HTML cache directory <em>' . $htmlDir . '</em>...';
     if (!file_exists($htmlDir)) {
         mkdir($htmlDir, 0774);
     }
     self::$logger->info('Cache directory [' . $htmlDir . '] successfully created');
     $body .= View::displayUpdateMessage('Cache directory [' . $htmlDir . '] successfully created');
     // cache/images
     $body .= '<p>Attempting to create the cache directory <em>' . $imagesDir . '</em>...';
     if (!file_exists($imagesDir)) {
         mkdir($imagesDir, 0774);
     }
     self::$logger->info('Cache directory [' . $imagesDir . '] successfully created');
     $body .= View::displayUpdateMessage('Cache directory [' . $imagesDir . '] successfully created');
     // cache/pdf
     $body .= '<p>Attempting to create the cache directory <em>' . $pdfDir . '</em>...';
     if (!file_exists($pdfDir)) {
         mkdir($pdfDir, 0774);
     }
     self::$logger->info('Cache directory [' . $pdfDir . '] successfully created');
     $body .= View::displayUpdateMessage('Cache directory [' . $pdfDir . '] successfully created');
     // cache/xls
     $body .= '<p>Attempting to create the cache directory <em>' . $xlsDir . '</em>...';
     if (!file_exists($xlsDir)) {
         mkdir($xlsDir, 0774);
     }
     self::$logger->info('Cache directory [' . $xlsDir . '] successfully created');
     $body .= View::displayUpdateMessage('Cache directory [' . $xlsDir . '] successfully created');
     self::$logger->debug('<<createApplicationDirs');
     return $body;
 }
 /**
  * Private method to generate the main body HTML for this page.
  *
  * @since 1.0
  *
  * @return string
  */
 private function displayBodyContent()
 {
     $classNames = ActiveRecord::getBOClassNames();
     $body = '';
     $fields = array('formAction' => $this->request->getURI());
     foreach ($classNames as $className) {
         try {
             $activeRecord = new $className();
             $view = View::getInstance($activeRecord);
             $body .= $view->adminView($fields);
         } catch (AlphaException $e) {
             self::$logger->error("[{$classname}]:" . $e->getMessage());
             // its possible that the exception occured due to the table schema being out of date
             if ($activeRecord->checkTableExists() && $activeRecord->checkTableNeedsUpdate()) {
                 $missingFields = $activeRecord->findMissingFields();
                 $count = count($missingFields);
                 for ($i = 0; $i < $count; ++$i) {
                     $activeRecord->addProperty($missingFields[$i]);
                 }
                 // now try again...
                 $activeRecord = new $className();
                 $view = View::getInstance($activeRecord);
                 $body .= $view->adminView($fields);
             }
         } catch (\Exception $e) {
             self::$logger->error($e->getMessage());
             $body .= View::displayErrorMessage('Error accessing the class [' . $classname . '], check the log!');
         }
     }
     return $body;
 }
Пример #24
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) . '])');
     $params = $request->getParams();
     $body = View::displayPageHead($this);
     $sequence = new Sequence();
     // make sure that the Sequence tables exist
     if (!$sequence->checkTableExists()) {
         $body .= View::displayErrorMessage('Warning! The Sequence table do not exist, attempting to create it now...');
         $sequence->makeTable();
     }
     // set the start point for the list pagination
     if (isset($params['start']) ? $this->startPoint = $params['start'] : ($this->startPoint = 1)) {
     }
     $records = $sequence->loadAll($this->startPoint);
     ActiveRecord::disconnect();
     $this->BOCount = $sequence->getCount();
     $body .= View::renderDeleteForm($this->request->getURI());
     foreach ($records as $record) {
         $view = View::getInstance($record);
         $body .= $view->listView(array('URI' => $request->getURI()));
     }
     $body .= View::displayPageFoot($this);
     self::$logger->debug('<<doGET');
     return new Response(200, $body, array('Content-Type' => 'text/html'));
 }
Пример #25
0
 /**
  * Handle GET requests.
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @return Alpha\Util\Http\Response
  *
  * @throws Alpha\Exception\IllegalArguementException
  *
  * @since 1.0
  */
 public function doGET($request)
 {
     self::$logger->debug('>>doGET($request=[' . var_export($request, true) . '])');
     $params = $request->getParams();
     $body = '';
     try {
         // load the business object (BO) definition
         if (isset($params['logPath']) && file_exists(urldecode($params['logPath']))) {
             $logPath = urldecode($params['logPath']);
         } else {
             throw new IllegalArguementException('No log file available to view!');
         }
         $this->logPath = $logPath;
         $body .= View::displayPageHead($this);
         $log = new LogProviderFile();
         $log->setPath($this->logPath);
         if (preg_match('/alpha.*/', basename($this->logPath))) {
             $body .= $log->renderLog(array('Date/time', 'Level', 'Class', 'Message', 'Client', 'IP', 'Server hostname', 'URI'));
         }
         if (preg_match('/search.*/', basename($this->logPath))) {
             $body .= $log->renderLog(array('Search query', 'Search date', 'Client Application', 'Client IP'));
         }
         if (preg_match('/feeds.*/', basename($this->logPath))) {
             $body .= $log->renderLog(array('Business object', 'Feed type', 'Request date', 'Client Application', 'Client IP'));
         }
         if (preg_match('/tasks.*/', basename($this->logPath))) {
             $body .= $log->renderLog(array('Date/time', 'Level', 'Class', 'Message'));
         }
         $body .= View::displayPageFoot($this);
     } catch (IllegalArguementException $e) {
         self::$logger->warn($e->getMessage());
         $body .= View::displayPageHead($this);
         $body .= View::displayErrorMessage($e->getMessage());
         $body .= View::displayPageFoot($this);
     }
     self::$logger->debug('<<doGET');
     return new Response(200, $body, array('Content-Type' => 'text/html'));
 }
Пример #26
0
 /**
  * Testing the detailedView() method.
  *
  * @since 2.0
  */
 public function testDetailedView()
 {
     $sequence = new Sequence();
     $sequence->load(1);
     $view = View::getInstance($sequence);
     $this->assertNotEmpty($view->detailedView(), 'Testing the detailedView() method');
     $this->assertTrue(strpos($view->detailedView(), 'TEST') !== false, 'Testing the detailedView() method');
 }