Exemplo n.º 1
0
 /**
  * Custom list view.
  *
  * @return string
  *
  * @since 1.0
  */
 public function listView($fields = array())
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $reflection = new \ReflectionClass(get_class($this->BO));
     $properties = $reflection->getProperties();
     $labels = $this->BO->getDataLabels();
     $colCount = 1;
     $html = '<form action="' . $fields['URI'] . '" method="POST">';
     $html .= '<table class="table">';
     // first render all of the table headers
     $html .= '<tr>';
     foreach ($properties as $propObj) {
         $prop = $propObj->name;
         if (!in_array($prop, $this->BO->getDefaultAttributes()) && !in_array($prop, $this->BO->getTransientAttributes())) {
             if (get_class($this->BO->getPropObject($prop)) != 'Alpha\\Model\\Type\\Text') {
                 ++$colCount;
                 $html .= '  <th>' . $labels[$prop] . '</th>';
             }
         }
         if ($prop == 'OID') {
             $html .= '  <th>' . $labels[$prop] . '</th>';
         }
     }
     // render the count
     $html .= '  <th>Item count</th>';
     $html .= '</tr><tr>';
     // and now the values
     foreach ($properties as $propObj) {
         $prop = $propObj->name;
         if (!in_array($prop, $this->BO->getDefaultAttributes()) && !in_array($prop, $this->BO->getTransientAttributes())) {
             if (get_class($this->BO->getPropObject($prop)) != 'Alpha\\Model\\Type\\Text') {
                 $html .= '  <td>&nbsp;' . $this->BO->get($prop) . '</td>';
             }
         }
         if ($prop == 'OID') {
             $html .= '  <td>&nbsp;' . $this->BO->getID() . '</td>';
         }
     }
     // render the count
     $html .= '  <td>&nbsp;' . $this->BO->getItemCount() . '</td>';
     $html .= '</tr>';
     $html .= '<tr><td colspan="' . ($colCount + 1) . '" style="text-align:center;">';
     // render edit buttons for admins only
     if ($session->get('currentUser') != null && $session->get('currentUser')->inGroup('Admin')) {
         $html .= '&nbsp;&nbsp;';
         $button = new Button("document.location = '" . FrontController::generateSecureURL('act=Alpha\\Controller\\DEnumController&denumOID=' . $this->BO->getOID()) . "'", 'Edit', 'edit' . $this->BO->getOID() . 'But');
         $html .= $button->render();
     }
     $html .= '</td></tr>';
     $html .= '</table>';
     $html .= '</form>';
     return $html;
 }
Exemplo n.º 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');
 }
Exemplo n.º 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');
 }
Exemplo n.º 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');
 }
 /**
  * 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');
 }
Exemplo n.º 7
0
 /**
  * {@inheritdoc}
  */
 public static function displayPageHead($controller)
 {
     if (self::$logger == null) {
         self::$logger = new Logger('RendererProviderHTML');
     }
     self::$logger->debug('>>displayPageHead(controller=[' . var_export($controller, true) . '])');
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     if (!class_exists(get_class($controller))) {
         throw new IllegalArguementException('The controller provided [' . get_class($controller) . '] is not defined anywhere!');
     }
     $allowCSSOverrides = true;
     $request = new Request(array('method' => 'GET'));
     if ($session->get('currentUser') != null && ActiveRecord::isInstalled() && $session->get('currentUser')->inGroup('Admin') && mb_strpos($request->getURI(), '/tk/') !== false) {
         $allowCSSOverrides = false;
     }
     $html = View::loadTemplateFragment('html', 'head.phtml', array('title' => $controller->getTitle(), 'description' => $controller->getDescription(), 'allowCSSOverrides' => $allowCSSOverrides));
     if (method_exists($controller, 'during_displayPageHead_callback')) {
         $html .= $controller->during_displayPageHead_callback();
     }
     $html .= '</head>';
     try {
         if ($controller->getRecord() != null) {
             $html .= '<body' . ($controller->getRecord()->get('bodyOnload') != '' ? ' onload="' . $controller->getRecord()->get('bodyOnload') . '"' : '') . '>';
         } else {
             $html .= '<body>';
         }
     } catch (AlphaException $e) {
         $html .= '<body>';
     }
     $html .= '<div class="container">';
     if (method_exists($controller, 'insert_CMSDisplayStandardHeader_callback')) {
         $html .= $controller->insert_CMSDisplayStandardHeader_callback();
     }
     self::$logger->debug('<<displayPageHead [HTML]');
     return $html;
 }
Exemplo n.º 8
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'));
 }
Exemplo n.º 9
0
 /**
  * Custom version of the check rights method that only checks for a session for the config admin username/password,
  * when the system database is not set-up.
  *
  * @return bool
  *
  * @since 1.0
  */
 public function checkRights()
 {
     self::$logger->debug('>>checkRights()');
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     if ($this->getVisibility() == 'Public') {
         self::$logger->debug('<<checkRights [true]');
         return true;
     }
     if (ActiveRecord::isInstalled()) {
         self::$logger->debug('<<checkRights [false]');
         return false;
     }
     // the person is logged in?
     if ($session->get('currentUser') !== false) {
         if ($session->get('currentUser')->get('email') == $config->get('app.install.username')) {
             self::$logger->debug('<<checkRights [true]');
             return true;
         }
     }
 }
Exemplo n.º 10
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 '';
     }
 }
Exemplo n.º 11
0
 /**
  * Stores the current startTime for the KPI in the session, useful for multi-request KPI tracking.
  *
  * @since 1.0
  */
 public function storeStartTimeInSession()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $session->set($this->name->getValue() . '-startTime', $this->startTime);
 }
 /**
  * Testing updating a table via doPOST method
  */
 public function testDoPOSTUpdateTable()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $front = new FrontController();
     $controller = new ListActiveRecordsController();
     $article = new Article();
     $securityParams = $controller->generateSecurityFields();
     $params = array('var1' => $securityParams[0], 'var2' => $securityParams[1], 'admin_AlphaModelArticle_button_pressed' => 'updateTableBut', 'updateTableClass' => 'Alpha\\Model\\Article');
     $request = new Request(array('method' => 'POST', 'URI' => '/listactiverecords', 'params' => $params));
     $response = $front->process($request);
     $this->assertEquals(0, count($article->findMissingFields()), 'Testing updating a table via doPOST method');
 }
Exemplo n.º 13
0
 /**
  * Log an action carried out by a person to the ActionLog table.
  *
  * @param string $message
  *
  * @since 1.1
  */
 public function action($message)
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     if ($session->get('currentUser') != null) {
         $action = new ActionLog();
         $action->set('client', $this->request->getUserAgent());
         $action->set('IP', $this->request->getIP());
         $action->set('message', $message);
         $action->save();
     }
 }
Exemplo n.º 14
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');
 }
Exemplo n.º 15
0
 /**
  * Sets the attribute value indicated by the key.  The ViewState instance will be serialized and saved back to the $_SESSION.
  *
  * @param string $key
  * @param string $value
  *
  * @throws Alpha\Exception\IllegalArguementException
  *
  * @since 1.0
  */
 public function set($key, $value)
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $attribute = new ReflectionProperty(get_class($this), $key);
     if ($attribute != null) {
         $this->{$key} = $value;
         $session->set('ViewState', serialize($this));
     } else {
         throw new IllegalArguementException('The property [' . $key . '] does not exist on the [' . get_class($this) . '] class');
     }
 }
Exemplo n.º 16
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');
         }
     }
 }
Exemplo n.º 17
0
 /**
  * (non-PHPdoc).
  *
  * @see Alpha\Model\ActiveRecordProviderInterface::save()
  */
 public function save()
 {
     self::$logger->debug('>>save()');
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     // get the class attributes
     $reflection = new ReflectionClass(get_class($this->BO));
     $properties = $reflection->getProperties();
     $sqlQuery = '';
     $stmt = null;
     if ($this->BO->getVersion() != $this->BO->getVersionNumber()->getValue()) {
         throw new LockingException('Could not save the object as it has been updated by another user.  Please try saving again.');
         return;
     }
     // set the "updated by" fields, we can only set the user id if someone is logged in
     if ($session->get('currentUser') != null) {
         $this->BO->set('updated_by', $session->get('currentUser')->getOID());
     }
     $this->BO->set('updated_ts', new Timestamp(date('Y-m-d H:i:s')));
     // check to see if it is a transient object that needs to be inserted
     if ($this->BO->isTransient()) {
         $savedFieldsCount = 0;
         $sqlQuery = 'INSERT INTO ' . $this->BO->getTableName() . ' (';
         foreach ($properties as $propObj) {
             $propName = $propObj->name;
             if (!in_array($propName, $this->BO->getTransientAttributes())) {
                 // Skip the OID, database auto number takes care of this.
                 if ($propName != 'OID' && $propName != 'version_num') {
                     $sqlQuery .= "{$propName},";
                     ++$savedFieldsCount;
                 }
                 if ($propName == 'version_num') {
                     $sqlQuery .= 'version_num,';
                     ++$savedFieldsCount;
                 }
             }
         }
         if ($this->BO->isTableOverloaded()) {
             $sqlQuery .= 'classname,';
         }
         $sqlQuery = rtrim($sqlQuery, ',');
         $sqlQuery .= ') VALUES (';
         for ($i = 0; $i < $savedFieldsCount; ++$i) {
             $sqlQuery .= '?,';
         }
         if ($this->BO->isTableOverloaded()) {
             $sqlQuery .= '?,';
         }
         $sqlQuery = rtrim($sqlQuery, ',') . ')';
         $this->BO->setLastQuery($sqlQuery);
         self::$logger->debug('Query [' . $sqlQuery . ']');
         $stmt = self::getConnection()->stmt_init();
         if ($stmt->prepare($sqlQuery)) {
             $stmt = $this->bindParams($stmt);
             $stmt->execute();
         } else {
             throw new FailedSaveException('Failed to save object, error is [' . $stmt->error . '], query [' . $this->BO->getLastQuery() . ']');
         }
     } else {
         // assume that it is a persistent object that needs to be updated
         $savedFieldsCount = 0;
         $sqlQuery = 'UPDATE ' . $this->BO->getTableName() . ' SET ';
         foreach ($properties as $propObj) {
             $propName = $propObj->name;
             if (!in_array($propName, $this->BO->getTransientAttributes())) {
                 // Skip the OID, database auto number takes care of this.
                 if ($propName != 'OID' && $propName != 'version_num') {
                     $sqlQuery .= "{$propName} = ?,";
                     ++$savedFieldsCount;
                 }
                 if ($propName == 'version_num') {
                     $sqlQuery .= 'version_num = ?,';
                     ++$savedFieldsCount;
                 }
             }
         }
         if ($this->BO->isTableOverloaded()) {
             $sqlQuery .= 'classname = ?,';
         }
         $sqlQuery = rtrim($sqlQuery, ',');
         $sqlQuery .= ' WHERE OID=?;';
         $this->BO->setLastQuery($sqlQuery);
         $stmt = self::getConnection()->stmt_init();
         if ($stmt->prepare($sqlQuery)) {
             $this->bindParams($stmt);
             $stmt->execute();
         } else {
             throw new FailedSaveException('Failed to save object, error is [' . $stmt->error . '], query [' . $this->BO->getLastQuery() . ']');
         }
     }
     if ($stmt != null && $stmt->error == '') {
         // populate the updated OID in case we just done an insert
         if ($this->BO->isTransient()) {
             $this->BO->setOID(self::getConnection()->insert_id);
         }
         try {
             foreach ($properties as $propObj) {
                 $propName = $propObj->name;
                 if ($this->BO->getPropObject($propName) instanceof Relation) {
                     $prop = $this->BO->getPropObject($propName);
                     // handle the saving of MANY-TO-MANY relation values
                     if ($prop->getRelationType() == 'MANY-TO-MANY' && count($prop->getRelatedOIDs()) > 0) {
                         try {
                             try {
                                 // check to see if the rel is on this class
                                 $side = $prop->getSide(get_class($this->BO));
                             } catch (IllegalArguementException $iae) {
                                 $side = $prop->getSide(get_parent_class($this->BO));
                             }
                             $lookUp = $prop->getLookup();
                             // first delete all of the old RelationLookup objects for this rel
                             try {
                                 if ($side == 'left') {
                                     $lookUp->deleteAllByAttribute('leftID', $this->BO->getOID());
                                 } else {
                                     $lookUp->deleteAllByAttribute('rightID', $this->BO->getOID());
                                 }
                             } catch (\Exception $e) {
                                 throw new FailedSaveException('Failed to delete old RelationLookup objects on the table [' . $prop->getLookup()->getTableName() . '], error is [' . $e->getMessage() . ']');
                             }
                             $OIDs = $prop->getRelatedOIDs();
                             if (isset($OIDs) && !empty($OIDs[0])) {
                                 // now for each posted OID, create a new RelationLookup record and save
                                 foreach ($OIDs as $oid) {
                                     $newLookUp = new RelationLookup($lookUp->get('leftClassName'), $lookUp->get('rightClassName'));
                                     if ($side == 'left') {
                                         $newLookUp->set('leftID', $this->BO->getOID());
                                         $newLookUp->set('rightID', $oid);
                                     } else {
                                         $newLookUp->set('rightID', $this->BO->getOID());
                                         $newLookUp->set('leftID', $oid);
                                     }
                                     $newLookUp->save();
                                 }
                             }
                         } catch (\Exception $e) {
                             throw new FailedSaveException('Failed to update a MANY-TO-MANY relation on the object, error is [' . $e->getMessage() . ']');
                             return;
                         }
                     }
                     // handle the saving of ONE-TO-MANY relation values
                     if ($prop->getRelationType() == 'ONE-TO-MANY') {
                         $prop->setValue($this->BO->getOID());
                     }
                 }
             }
         } catch (\Exception $e) {
             throw new FailedSaveException('Failed to save object, error is [' . $e->getMessage() . ']');
             return;
         }
         $stmt->close();
     } else {
         // there has been an error, so decrement the version number back
         $temp = $this->BO->getVersionNumber()->getValue();
         $this->BO->set('version_num', $temp - 1);
         // check for unique violations
         if (self::getConnection()->errno == '1062') {
             throw new ValidationException('Failed to save, the value ' . $this->findOffendingValue(self::getConnection()->error) . ' is already in use!');
             return;
         } else {
             throw new FailedSaveException('Failed to save object, MySql error is [' . self::getConnection()->error . '], query [' . $this->BO->getLastQuery() . ']');
         }
     }
     if ($this->BO->getMaintainHistory()) {
         $this->BO->saveHistory();
     }
 }
Exemplo n.º 18
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');
 }
Exemplo n.º 19
0
 /**
  * Renders the text boxes and buttons for the widget, that will appear in user forms.
  *
  * @param bool $expanded Render the related fields in expanded format or not (optional)
  * @param bool $buttons  Render buttons for expanding/contacting the related fields (optional)
  *
  * @return string
  *
  * @since 1.0
  */
 public function render($expanded = false, $buttons = true)
 {
     self::$logger->debug('>>render(expanded=[' . $expanded . '], buttons=[' . $buttons . '])');
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $fieldname = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt($this->name)) : $this->name;
     $html = '';
     // render text-box for many-to-one relations
     if ($this->relationObject->getRelationType() == 'MANY-TO-ONE') {
         // value to appear in the text-box
         $inputBoxValue = $this->relationObject->getRelatedClassDisplayFieldValue();
         $html .= '<div class="form-group">';
         $html .= '<label for="' . $this->name . '_display">' . $this->label . '</label>';
         $html .= '<input type="text" size="70" class="form-control" name="' . $this->name . '_display" id="' . $this->name . '_display" value="' . $inputBoxValue . '" disabled/>';
         $js = " if(window.jQuery) {\n                        window.jQuery.dialog = new BootstrapDialog({\n                            title: 'Please select',\n                            message: 'Loading...',\n                            onshow: function(dialogRef){\n                                dialogRef.getModalBody().load('" . $config->get('app.url') . "/recordselector/12m/'+document.getElementById('" . $fieldname . "').value+'/" . $this->name . '/' . urlencode($this->relationObject->getRelatedClass()) . '/' . $this->relationObject->getRelatedClassField() . '/' . $this->relationObject->getRelatedClassDisplayField() . "');\n                            },\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                        });\n                        window.jQuery.dialog.open();\n                    }";
         $tmp = new Button($js, 'Select', 'relBut', '', 'glyphicon-check');
         $html .= '<div class="centered lower">' . $tmp->render() . '</div>';
         // hidden field to store the actual value of the relation
         $html .= '<input type="hidden" name="' . $fieldname . '" id="' . $fieldname . '" value="' . $this->relationObject->getValue() . '"/>';
         if ($this->relationObject->getRule() != '') {
             $html .= '<input type="hidden" id="' . $fieldname . '_msg" value="' . $this->relationObject->getHelper() . '"/>';
             $html .= '<input type="hidden" id="' . $fieldname . '_rule" value="' . $this->relationObject->getRule() . '"/>';
         }
         $html .= '</div>';
     }
     // render read-only list for one-to-many relations
     if ($this->relationObject->getRelationType() == 'ONE-TO-MANY') {
         $objects = $this->relationObject->getRelatedObjects();
         if (count($objects) > 0) {
             // render tags differently
             if ($this->name == 'tags' && $this->relationObject->getRelatedClass() == 'TagObject') {
                 $html .= '<p><strong>' . $this->label . ':</strong>';
                 foreach ($objects as $tag) {
                     $html .= ' <a href="' . $config->get('app.url') . '/search/' . $tag->get('content') . '">' . $tag->get('content') . '</a>';
                 }
                 $html .= '</p>';
             } else {
                 $html .= '<div><strong>' . $this->label . ':</strong>';
                 if ($buttons) {
                     $html .= '<div class="spread">';
                     $tmp = new Button("document.getElementById('relation_field_" . $this->name . "').style.display = '';", 'Show', $this->name . 'DisBut', '', 'glyphicon-list');
                     $html .= $tmp->render();
                     $tmp = new Button("document.getElementById('relation_field_" . $this->name . "').style.display = 'none';", 'Hide', $this->name . 'HidBut', '', 'glyphicon-minus');
                     $html .= $tmp->render();
                     $html .= '</div>';
                 }
                 $html .= '</div>';
                 $html .= '<div id="relation_field_' . $this->name . '" style="display:' . ($expanded ? '' : 'none') . ';">';
                 $customViewControllerName = Controller::getCustomControllerName(get_class($objects[0]), 'view');
                 $customEditControllerName = Controller::getCustomControllerName(get_class($objects[0]), 'edit');
                 $request = new Request(array('method' => 'GET'));
                 $URI = $request->getURI();
                 foreach ($objects as $obj) {
                     // check to see if we are in the admin back-end
                     if (mb_strpos($URI, '/tk/') !== false) {
                         $viewURL = FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . get_class($obj) . '&ActiveRecordOID=' . $obj->getOID());
                         $editURL = FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . get_class($obj) . '&ActiveRecordOID=' . $obj->getOID() . '&view=edit');
                     } else {
                         if (isset($customViewControllerName)) {
                             if ($config->get('app.use.mod.rewrite')) {
                                 $viewURL = $config->get('app.url') . $customViewControllerName . '/oid/' . $obj->getOID();
                             } else {
                                 $viewURL = $config->get('app.url') . 'controller/' . $customViewControllerName . '.php?oid=' . $obj->getOID();
                             }
                         } else {
                             $viewURL = $config->get('app.url') . 'alpha/controller/Detail.php?bo=' . get_class($obj) . '&oid=' . $obj->getOID();
                         }
                         if (isset($customEditControllerName)) {
                             if ($config->get('app.use.mod.rewrite')) {
                                 $editURL = $config->get('app.url') . $customEditControllerName . '/oid/' . $obj->getOID();
                             } else {
                                 $editURL = $config->get('app.url') . 'controller/' . $customEditControllerName . '.php?oid=' . $obj->getOID();
                             }
                         } else {
                             $editURL = $config->get('app.url') . 'alpha/controller/Edit.php?bo=' . get_class($obj) . '&oid=' . $obj->getOID();
                         }
                     }
                     /*
                      * If any display headers were set with setRelatedClassHeaderFields, use them otherwise
                      * use the OID of the related class as the only header.
                      */
                     $headerFields = $this->relationObject->getRelatedClassHeaderFields();
                     if (count($headerFields) > 0) {
                         foreach ($headerFields as $field) {
                             $label = $obj->getDataLabel($field);
                             $value = $obj->get($field);
                             if ($field == 'created_by' || $field == 'updated_by') {
                                 $person = new PersonObject();
                                 $person->load($value);
                                 $value = $person->getDisplayName();
                             }
                             $html .= '<em>' . $label . ': </em>' . $value . '&nbsp;&nbsp;&nbsp;&nbsp;';
                         }
                         // if the related BO has been updated, render the update time
                         if ($obj->getCreateTS() != $obj->getUpdateTS()) {
                             try {
                                 $html .= '<em>' . $obj->getDataLabel('updated_ts') . ': </em>' . $obj->get('updated_ts');
                             } catch (IllegalArguementException $e) {
                                 $html .= '<em>Updated: </em>' . $obj->get('updated_ts');
                             }
                         }
                     } else {
                         $html .= '<em>' . $obj->getDataLabel('OID') . ': </em>' . $obj->get('OID');
                     }
                     // ensures that line returns are rendered
                     $value = str_replace("\n", '<br>', $obj->get($this->relationObject->getRelatedClassDisplayField()));
                     $html .= '<p>' . $value . '</p>';
                     $html .= '<div class="centered">';
                     $html .= '<a href="' . $viewURL . '">View</a>';
                     // if the current user owns it, they get the edit link
                     if ($session->get('currentUser') != null && $session->get('currentUser')->getOID() == $obj->getCreatorId()) {
                         $html .= '&nbsp;&nbsp;&nbsp;&nbsp;<a href="' . $editURL . '">Edit</a>';
                     }
                     $html .= '</div>';
                 }
                 $html .= '</div>';
             }
         }
     }
     // render text-box for many-to-many relations
     if ($this->relationObject->getRelationType() == 'MANY-TO-MANY') {
         // value to appear in the text-box
         $inputBoxValue = $this->relationObject->getRelatedClassDisplayFieldValue($this->accessingClassName);
         // replace commas with line returns
         $inputBoxValue = str_replace(',', "\n", $inputBoxValue);
         $html .= '<div class="form-group">';
         $html .= '<label for="' . $this->name . '_display">' . $this->label . '</label>';
         $html .= '<textarea id="' . $this->name . '_display" class="form-control" rows="5" readonly>';
         $html .= $inputBoxValue;
         $html .= '</textarea>';
         $fieldname1 = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt($this->name)) : $this->name;
         $fieldname2 = $config->get('security.encrypt.http.fieldnames') ? base64_encode(SecurityUtils::encrypt($this->name . '_OID')) : $this->name . '_OID';
         $js = "if(window.jQuery) {\n                        BootstrapDialog.show({\n                            title: 'Please select',\n                            message: 'Loading...',\n                            onshow: function(dialogRef){\n                                dialogRef.getModalBody().load('" . $config->get('app.url') . "/recordselector/m2m/'+document.getElementById('" . $fieldname2 . "').value+'/" . $this->name . '/' . urlencode($this->relationObject->getRelatedClass('left')) . '/' . $this->relationObject->getRelatedClassDisplayField('left') . '/' . urlencode($this->relationObject->getRelatedClass('right')) . '/' . $this->relationObject->getRelatedClassDisplayField('right') . '/' . urlencode($this->accessingClassName) . "/'+document.getElementById('" . $fieldname1 . "').value);\n                            },\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                                    setParentFieldValues();\n                                    \$('[id=\\'" . $this->name . "_display\\']').blur();\n                                    dialogItself.close();\n                                }\n                            }\n                        ]\n                        });\n                    }";
         $tmp = new Button($js, 'Select', 'relBut', '', 'glyphicon-check');
         $html .= '<div class="centered lower">' . $tmp->render() . '</div>';
         $html .= '</div>';
         // hidden field to store the OID of the current BO
         $html .= '<input type="hidden" name="' . $fieldname2 . '" id="' . $fieldname2 . '" value="' . $this->relationObject->getValue() . '"/>';
         // hidden field to store the OIDs of the related BOs on the other side of the rel (this is what we check for when saving)
         if ($this->relationObject->getSide($this->accessingClassName) == 'left') {
             $lookupOIDs = $this->relationObject->getLookup()->loadAllFieldValuesByAttribute('leftID', $this->relationObject->getValue(), 'rightID', 'DESC');
         } else {
             $lookupOIDs = $this->relationObject->getLookup()->loadAllFieldValuesByAttribute('rightID', $this->relationObject->getValue(), 'leftID', 'DESC');
         }
         $html .= '<input type="hidden" name="' . $fieldname1 . '" id="' . $fieldname1 . '" value="' . implode(',', $lookupOIDs) . '"/>';
     }
     self::$logger->debug('<<__render [html]');
     return $html;
 }
Exemplo n.º 20
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');
 }
Exemplo n.º 21
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;
 }
Exemplo n.º 22
0
 /**
  * Drop the user tables and session between tests.
  *
  * @since 2.0
  */
 protected function tearDown()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $session->set('currentUser', null);
     $person = new Person();
     $person->dropTable();
     $rights = new Rights();
     $rights->dropTable();
     $rights->dropTable('Person2Rights');
 }
Exemplo n.º 23
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'));
 }
 public function getProviders()
 {
     $arrayProvider = SessionProviderFactory::getInstance('Alpha\\Util\\Http\\Session\\SessionProviderArray');
     $PHPSessionProvider = SessionProviderFactory::getInstance('Alpha\\Util\\Http\\Session\\SessionProviderPHP');
     return array(array($arrayProvider), array($PHPSessionProvider));
 }
Exemplo n.º 25
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'));
 }
Exemplo n.º 26
0
 /**
  * Test that the constructor sets the correct values of the "house keeping" attributes.
  *
  * @since 1.0
  *
  * @dataProvider getActiveRecordProviders
  */
 public function testDefaultHouseKeepingValues($provider)
 {
     $config = ConfigProvider::getInstance();
     $config->set('db.provider.name', $provider);
     $this->person->save();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     $session->set('currentUser', $this->person);
     $request = new BadRequest();
     $request->set('IP', '127.0.0.1');
     $request->save();
     // make sure the person logged in is the same person to create/update the object
     $this->assertEquals($session->get('currentUser')->getOID(), $request->getCreatorId()->getValue(), 'test that the constructor sets the correct values of the "house keeping" attributes');
     $this->assertEquals($session->get('currentUser')->getID(), $request->getUpdatorId()->getValue(), 'test that the constructor sets the correct values of the "house keeping" attributes');
     $request = new BadRequest();
     // as it is a new object, make sure the version number is zero
     $this->assertEquals(0, $request->getVersionNumber()->getValue(), 'test that the constructor sets the correct values of the "house keeping" attributes');
     // check that the date created and updated equal to today
     $today = date('Y-m-d');
     $this->assertEquals($today, $request->getCreateTS()->getDate(), 'test that the constructor sets the correct values of the "house keeping" attributes');
     $this->assertEquals($today, $request->getUpdateTS()->getDate(), 'test that the constructor sets the correct values of the "house keeping" attributes');
     // make sure the object is transient
     $this->assertTrue($request->isTransient(), 'test that the constructor sets the correct values of the "house keeping" attributes');
 }
 /**
  * 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');
 }
Exemplo n.º 28
0
 /**
  * The constructor which sets up some housekeeping attributes.
  *
  * @since 1.0
  */
 public function __construct()
 {
     self::$logger = new Logger('ActiveRecord');
     self::$logger->debug('>>__construct()');
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     set_exception_handler('Alpha\\Util\\ErrorHandlers::catchException');
     set_error_handler('Alpha\\Util\\ErrorHandlers::catchError', $config->get('php.error.log.level'));
     $this->version_num = new Integer(0);
     $this->created_ts = new Timestamp(date('Y-m-d H:i:s'));
     $person_ID = $session->get('currentUser') != null ? $session->get('currentUser')->getOID() : 0;
     $this->created_by = new Integer($person_ID);
     $this->updated_ts = new Timestamp(date('Y-m-d H:i:s'));
     $this->updated_by = new Integer($person_ID);
     self::$logger->debug('<<__construct');
 }
Exemplo n.º 29
0
 /**
  * Method to determine if the logged-in user has already voted for this article.
  *
  * @return bool True if they have voted already, false otherwise
  *
  * @since 1.0
  *
  * @throws Alpha\Exception\AlphaException
  */
 public function checkUserVoted()
 {
     $config = ConfigProvider::getInstance();
     $sessionProvider = $config->get('session.provider.name');
     $session = SessionProviderFactory::getInstance($sessionProvider);
     // just going to return true if nobody is logged in
     if ($session->get('currentUser') == null) {
         return true;
     }
     $userID = $session->get('currentUser')->getID();
     $vote = new ArticleVote();
     $sqlQuery = 'SELECT COUNT(*) AS usersVote FROM ' . $vote->getTableName() . " WHERE articleOID='" . $this->OID . "' AND personOID='" . $userID . "';";
     $result = $this->query($sqlQuery);
     if (!isset($result[0])) {
         throw new AlphaException('Failed to check if the current user voted for the article [' . $this->OID . '], query [' . $sqlQuery . ']');
         return false;
     }
     $row = $result[0];
     if ($row['usersVote'] == '0') {
         return false;
     } else {
         return true;
     }
 }
Exemplo n.º 30
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');
 }