/** * Drop the test database between tests. * * @since 2.0 */ protected function tearDown() { $config = ConfigProvider::getInstance(); foreach ($this->getActiveRecordProviders() as $provider) { $config->set('db.provider.name', $provider[0]); ActiveRecord::dropDatabase(); ActiveRecord::disconnect(); } }
/** * Method to load all of the BO items to the feed from the database, from the newest to the * $limit provided. * * @param int $limit The amount of items to render in the feed. * @param string $sortBy The name of the field to sort the feed by. * * @since 1.0 */ public function loadBOs($limit, $sortBy) { $BOs = $this->BO->loadAll(0, $limit, $sortBy, 'DESC'); ActiveRecord::disconnect(); foreach ($BOs as $BO) { $this->addBO($BO); } }
/** * 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')); }
/** * Tear down tests. * * @since 1.2.3 */ protected function tearDown() { unset($this->article); ActiveRecord::dropDatabase(); ActiveRecord::disconnect(); }
/** * Loads the BO indicated in the GET request and handles the conversion to Excel. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @throws Alpha\Exception\ResourceNotFoundException * * @since 1.0 */ public function doGet($request) { self::$logger->debug('>>doGet(request=[' . var_export($request, true) . '])'); $params = $request->getParams(); $body = ''; try { if (isset($params['ActiveRecordType'])) { $ActiveRecordType = $params['ActiveRecordType']; $className = "Alpha\\Model\\{$ActiveRecordType}"; if (class_exists($className)) { $this->BO = new $className(); } else { throw new IllegalArguementException('No ActiveRecord available to render!'); } // the name of the file download if (isset($params['ActiveRecordOID'])) { $fileName = $this->BO->getTableName() . '-' . $params['ActiveRecordOID']; } else { $fileName = $this->BO->getTableName(); } $response = new Response(200); // header info for browser $response->setHeader('Content-Type', 'application/vnd.ms-excel'); $response->setHeader('Content-Disposition', 'attachment; filename=' . $fileName . '.xls'); $response->setHeader('Pragma', 'no-cache'); $response->setHeader('Expires', '0'); // handle a single BO if (isset($params['ActiveRecordOID'])) { $this->BO->load($params['ActiveRecordOID']); ActiveRecord::disconnect(); $convertor = new ActiveRecord2Excel($this->BO); $body .= $convertor->render(); } else { // handle all BOs of this type $BOs = $BO->loadAll(); ActiveRecord::disconnect(); $first = true; foreach ($BOs as $BO) { $convertor = new ActiveRecord2Excel($BO); if ($first) { $body .= $convertor->render(true); $first = false; } else { $body .= $convertor->render(false); } } } } else { throw new IllegalArguementException('No ActiveRecordType parameter available for ViewExcel controller!'); } } catch (RecordNotFoundException $e) { self::$logger->error($e->getMessage()); throw new ResourceNotFoundException($e->getMessage()); } catch (IllegalArguementException $e) { self::$logger->error($e->getMessage()); throw new ResourceNotFoundException($e->getMessage()); } self::$logger->debug('<<__doGet'); $response->setBody($body); return $response; }
/** * 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; }
/** * Handle POST requests. * * @param Alpha\Util\Http\Request $request * * @return Alpha\Util\Http\Response * * @throws Alpha\Exception\SecurityException * * @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!'); self::$logger->debug('<<doPOST'); } // ensure that a OID is provided if (isset($params['denumOID'])) { $BOoid = $params['denumOID']; } else { throw new IllegalArguementException('Could not load the DEnum object as an denumOID was not supplied!'); } if (isset($params['saveBut'])) { try { $this->BO->load($BOoid); // update the object from post data $this->BO->populateFromArray($params); ActiveRecord::begin(); $this->BO->save(); self::$logger->action('DEnum ' . $this->BO->getOID() . ' saved'); // now save the DEnumItems $tmp = new DEnumItem(); $denumItems = $tmp->loadItems($this->BO->getID()); foreach ($denumItems as $item) { $item->set('value', $params['value_' . $item->getID()]); $item->save(); self::$logger->action('DEnumItem ' . $item->getOID() . ' saved'); } // handle new DEnumItem if posted if (isset($params['new_value']) && trim($params['new_value']) != '') { $newItem = new DEnumItem(); $newItem->set('value', $params['new_value']); $newItem->set('DEnumID', $this->BO->getID()); $newItem->save(); self::$logger->action('DEnumItem ' . $newItem->getOID() . ' created'); } ActiveRecord::commit(); $this->setStatusMessage(View::displayUpdateMessage(get_class($this->BO) . ' ' . $this->BO->getID() . ' saved successfully.')); return $this->doGET($request); } catch (FailedSaveException $e) { self::$logger->error('Unable to save the DEnum of id [' . $params['oid'] . '], error was [' . $e->getMessage() . ']'); ActiveRecord::rollback(); } ActiveRecord::disconnect(); } } catch (SecurityException $e) { $this->setStatusMessage(View::displayErrorMessage($e->getMessage())); self::$logger->warn($e->getMessage()); } catch (IllegalArguementException $e) { $this->setStatusMessage(View::displayErrorMessage($e->getMessage())); 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!')); } $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')); }
/** * 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')); }
/** * 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'); }
/** * Callback used to render footer content, including comments, votes and print/PDF buttons when * enabled to do so. * * @return string * * @since 1.0 */ public function before_displayPageFoot_callback() { $config = ConfigProvider::getInstance(); $sessionProvider = $config->get('session.provider.name'); $session = SessionProviderFactory::getInstance($sessionProvider); $html = ''; $params = $this->request->getParams(); // this will ensure that direct requests to ActiveRecordController will be re-directed here. if (isset($this->record) && !$this->record->isTransient()) { $this->setName($config->get('app.url') . $this->request->getURI()); $this->setUnitOfWork(array($config->get('app.url') . $this->request->getURI(), $config->get('app.url') . $this->request->getURI())); } else { $this->setUnitOfWork(array()); } if ($this->record != null) { if (isset($params['view']) && $params['view'] == 'detailed') { if ($config->get('cms.display.comments')) { $html .= $this->renderComments(); } if ($config->get('cms.display.tags')) { $tags = $this->record->getPropObject('tags')->getRelatedObjects(); if (count($tags) > 0) { $html .= '<p>Tags:'; foreach ($tags as $tag) { $html .= ' <a href="' . $config->get('app.url') . '/search/' . $tag->get('content') . '">' . $tag->get('content') . '</a>'; } $html .= '</p>'; } } if ($config->get('cms.display.votes')) { $rating = $this->record->getArticleScore(); $votes = $this->record->getArticleVotes(); $html .= '<p>Average Article User Rating: <strong>' . $rating . '</strong> out of 10 (based on <strong>' . count($votes) . '</strong> votes)</p>'; } if (!$this->record->checkUserVoted() && $config->get('cms.voting.allowed')) { $URL = FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=Alpha\\Model\\ArticleVote'); $html .= '<form action="' . $URL . '" method="post" accept-charset="UTF-8">'; $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('score')) : 'score'; $html .= '<p>Please rate this article from 1-10 (10 being the best):' . '<select name="' . $fieldname . '">' . '<option value="1">1' . '<option value="2">2' . '<option value="3">3' . '<option value="4">4' . '<option value="5">5' . '<option value="6">6' . '<option value="7">7' . '<option value="8">8' . '<option value="9">9' . '<option value="10">10' . '</select></p> '; $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('articleOID')) : 'articleOID'; $html .= '<input type="hidden" name="' . $fieldname . '" value="' . $this->record->getOID() . '"/>'; $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('personOID')) : 'personOID'; $html .= '<input type="hidden" name="' . $fieldname . '" value="' . $session->get('currentUser')->getID() . '"/>'; $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt('statusMessage')) : 'statusMessage'; $html .= '<input type="hidden" name="' . $fieldname . '" value="Thank you for rating this article!"/>'; $temp = new Button('submit', 'Vote!', 'voteBut'); $html .= $temp->render(); $html .= View::renderSecurityFields(); $html .= '<form>'; } ActiveRecord::disconnect(); if ($config->get('cms.allow.print.versions')) { $html .= ' '; $temp = new Button("window.open('" . $this->record->get('printURL') . "')", 'Open Printer Version', 'printBut'); $html .= $temp->render(); } $html .= ' '; if ($config->get('cms.allow.pdf.versions')) { $html .= ' '; $temp = new Button("document.location = '" . FrontController::generateSecureURL("act=Alpha\\Controller\\ArticleController&mode=pdf&title=" . $this->record->get('title')) . "';", 'Open PDF Version', 'pdfBut'); $html .= $temp->render(); } // render edit button for admins only if ($session->get('currentUser') instanceof Alpha\Model\Person && $session->get('currentUser')->inGroup('Admin')) { $html .= ' '; $button = new Button("document.location = '" . FrontController::generateSecureURL('act=Alpha\\Controller\\ArticleController&mode=edit&ActiveRecordOID=' . $this->record->getID()) . "'", 'Edit', 'editBut'); $html .= $button->render(); } } if ($config->get('cms.display.standard.footer')) { $html .= '<p>Article URL: <a href="' . $this->record->get('URL') . '">' . $this->record->get('URL') . '</a><br>'; $html .= 'Title: ' . $this->record->get('title') . '<br>'; $html .= 'Author: ' . $this->record->get('author') . '</p>'; } } $html .= $config->get('cms.footer'); return $html; }