Example #1
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'));
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function send($to, $from, $subject, $body, $isHTML = false)
 {
     self::$logger->debug('>>send(to=[' . $to . '], from=[' . $from . '], subject=[' . $subject . '], body=[' . $body . '], isHTML=[' . $isHTML . '])');
     $config = ConfigProvider::getInstance();
     $headers = 'MIME-Version: 1.0' . "\n";
     if ($isHTML) {
         $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\n";
     }
     $headers .= 'From: ' . $from . "\n";
     if ($config->getEnvironment() != 'dev') {
         try {
             mb_send_mail($to, $subject, $body, $headers);
         } catch (PHPException $e) {
             throw new MailNotSentException('Error sending a mail to [' . $to . ']');
         }
     } else {
         self::$logger->info("Sending email:\n" . $headers . "\n" . $body);
     }
     self::$logger->debug('<<send');
 }
 /**
  * Note that SQLite 3.6.19 is requrired for foreign key support.
  *
  * (non-PHPdoc)
  *
  * @see Alpha\Model\ActiveRecordProviderInterface::createForeignIndex()
  */
 public function createForeignIndex($attributeName, $relatedClass, $relatedClassAttribute, $indexName = null)
 {
     self::$logger->info('>>createForeignIndex(attributeName=[' . $attributeName . '], relatedClass=[' . $relatedClass . '], relatedClassAttribute=[' . $relatedClassAttribute . '], indexName=[' . $indexName . ']');
     /*
      * High-level approach
      *
      * 1. Rename the source table to [tablename]_temp
      * 2. Create a new [tablename] table, with the new FK in place.
      * 3. Copy all of the data from [tablename]_temp to [tablename].
      * 4. Drop [tablename]_temp.
      */
     try {
         ActiveRecord::begin($this->BO);
         // rename the table to [tablename]_temp
         $query = 'ALTER TABLE ' . $this->BO->getTableName() . ' RENAME TO ' . $this->BO->getTableName() . '_temp;';
         $this->BO->setLastQuery($query);
         self::getConnection()->query($query);
         self::$logger->info('Renamed the table [' . $this->BO->getTableName() . '] to [' . $this->BO->getTableName() . '_temp]');
         // now create the new table with the FK in place
         $record = new $relatedClass();
         $tableName = $record->getTableName();
         $this->foreignKeys[$attributeName] = array($tableName, $relatedClassAttribute);
         $this->makeTable();
         self::$logger->info('Made a new copy of the table [' . $this->BO->getTableName() . ']');
         // copy all of the old data to the new table
         $query = 'INSERT INTO ' . $this->BO->getTableName() . ' SELECT * FROM ' . $this->BO->getTableName() . '_temp;';
         $this->BO->setLastQuery($query);
         self::getConnection()->query($query);
         self::$logger->info('Copied all of the data from [' . $this->BO->getTableName() . '] to [' . $this->BO->getTableName() . '_temp]');
         // finally, drop the _temp table and commit the changes
         $this->BO->dropTable($this->BO->getTableName() . '_temp');
         self::$logger->info('Dropped the table [' . $this->BO->getTableName() . '_temp]');
         ActiveRecord::commit($this->BO);
     } catch (Exception $e) {
         ActiveRecord::rollback($this->BO);
         throw new FailedIndexCreateException('Failed to create the index [' . $attributeName . '] on [' . $this->BO->getTableName() . '], error is [' . $e->getMessage() . '], query [' . $this->BO->getLastQuery() . ']');
     }
     self::$logger->info('<<createForeignIndex');
 }
Example #4
0
 /**
  * Handle GET requests.
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @since 1.0
  *
  * @throws Alpha\Exception\ResourceNotFoundException
  */
 public function doGET($request)
 {
     self::$logger->debug('>>doGET($request=[' . var_export($request, true) . '])');
     $config = ConfigProvider::getInstance();
     $params = $request->getParams();
     try {
         if (isset($params['articleOID']) && isset($params['filename'])) {
             if (!Validator::isInteger($params['articleOID'])) {
                 throw new IllegalArguementException('The articleOID [' . $params['articleOID'] . '] provided is invalid');
             }
             $article = new Article();
             $article->setOID($params['articleOID']);
             $filePath = $article->getAttachmentsLocation() . '/' . $params['filename'];
             if (file_exists($filePath)) {
                 self::$logger->info('Downloading the file [' . $params['filename'] . '] from the folder [' . $article->getAttachmentsLocation() . ']');
                 $pathParts = pathinfo($filePath);
                 $mimeType = FileUtils::getMIMETypeByExtension($pathParts['extension']);
                 $response = new Response(200, file_get_contents($filePath));
                 $response->setHeader('Content-Type', $mimeType);
                 $response->setHeader('Content-Disposition', 'attachment; filename="' . $pathParts['basename'] . '"');
                 $response->setHeader('Content-Length', filesize($filePath));
                 self::$logger->debug('<<doGET');
                 return $response;
             } else {
                 self::$logger->error('Could not access article attachment file [' . $filePath . '] as it does not exist!');
                 throw new IllegalArguementException('File not found');
             }
         } else {
             self::$logger->error('Could not access article attachment as articleOID and/or filename were not provided!');
             throw new IllegalArguementException('File not found');
         }
     } catch (IllegalArguementException $e) {
         self::$logger->error($e->getMessage());
         throw new ResourceNotFoundException($e->getMessage());
     }
     self::$logger->debug('<<doGET');
 }
Example #5
0
 /**
  * Constructor.
  *
  * @since 1.0
  */
 public function __construct()
 {
     $config = ConfigProvider::getInstance();
     self::$logger = new Logger('CronManager');
     self::$logger->setLogProviderFile($config->get('app.file.store.dir') . 'logs/tasks.log');
     self::$logger->debug('>>__construct()');
     self::$logger->info('New CronManager invoked');
     $taskList = self::getTaskClassNames();
     self::$logger->info('Found [' . count($taskList) . '] tasks in the directory [' . $config->get('app.root') . 'tasks]');
     foreach ($taskList as $taskClass) {
         $taskClass = 'Alpha\\Task\\' . $taskClass;
         self::$logger->info('Loading task [' . $taskClass . ']');
         $task = new $taskClass();
         $startTime = microtime(true);
         $maxAllowedTime = $startTime + $task->getMaxRunTime();
         self::$logger->info('Start time is [' . $startTime . '], maximum task run time is [' . $task->getMaxRunTime() . ']');
         // only continue to execute for the task max time
         set_time_limit($task->getMaxRunTime());
         $task->doTask();
         self::$logger->info('Done in [' . round(microtime(true) - $startTime, 5) . '] seconds');
     }
     self::$logger->info('Finished processing all cron tasks');
     self::$logger->debug('<<__construct');
 }
Example #6
0
 /**
  * Processes the supplied request by invoking the callable defined matching the request's URI.
  *
  * @param Alpha\Util\Http\Request $request The request to process
  *
  * @return Alpha\Util\Http\Response
  *
  * @throws Alpha\Exception\ResourceNotFoundException
  * @throws Alpha\Exception\ResourceNotAllowedException
  * @throws Alpha\Exception\AlphaException
  *
  * @since 2.0
  */
 public function process($request)
 {
     foreach ($this->filters as $filter) {
         $filter->process($request);
     }
     try {
         $callback = $this->getRouteCallback($request->getURI());
     } catch (IllegalArguementException $e) {
         self::$logger->warn($e->getMessage());
         throw new ResourceNotFoundException('Resource not found');
     }
     if ($request->getURI() != $this->currentRoute) {
         if (isset($this->defaultParamValues[$this->currentRoute])) {
             $request->parseParamsFromRoute($this->currentRoute, $this->defaultParamValues[$this->currentRoute]);
         } else {
             $request->parseParamsFromRoute($this->currentRoute);
         }
     }
     try {
         $response = call_user_func($callback, $request);
     } catch (ResourceNotFoundException $rnfe) {
         self::$logger->info('ResourceNotFoundException throw, source message [' . $rnfe->getMessage() . ']');
         return new Response(404, $rnfe->getMessage());
     }
     if ($response instanceof Response) {
         return $response;
     } else {
         self::$logger->error('The callable defined for route [' . $request->getURI() . '] does not return a Response object');
         throw new AlphaException('Unable to process request');
     }
 }
Example #7
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;
 }
Example #8
0
 /**
  * Builds a new database table for the BO class to story it's history of changes.
  *
  * @since 1.2
  *
  * @throws Alpha\Exception\AlphaException
  */
 public function makeHistoryTable()
 {
     self::$logger->debug('>>makeHistoryTable()');
     if (method_exists($this, 'before_makeHistoryTable_callback')) {
         $this->before_makeHistoryTable_callback();
     }
     $config = ConfigProvider::getInstance();
     $provider = ActiveRecordProviderFactory::getInstance($config->get('db.provider.name'), $this);
     $provider->makeHistoryTable();
     if (method_exists($this, 'after_makeHistoryTable_callback')) {
         $this->after_makeHistoryTable_callback();
     }
     self::$logger->info('Successfully created the table [' . $this->getTableName() . '_history] for the class [' . get_class($this) . ']');
     self::$logger->debug('<<makeHistoryTable');
 }
Example #9
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'));
 }
 /**
  * (non-PHPdoc).
  *
  * @see Alpha\Model\ActiveRecordProviderInterface::addProperty()
  */
 public function addProperty($propName)
 {
     self::$logger->debug('>>addProperty(propName=[' . $propName . '])');
     $sqlQuery = 'ALTER TABLE ' . $this->BO->getTableName() . ' ADD ';
     if ($this->isTableOverloaded() && $propName == 'classname') {
         $sqlQuery .= 'classname VARCHAR(100)';
     } else {
         if (!in_array($propName, $this->BO->getDefaultAttributes()) && !in_array($propName, $this->BO->getTransientAttributes())) {
             $reflection = new ReflectionClass($this->BO->getPropObject($propName));
             $propClass = $reflection->getShortName();
             switch (mb_strtoupper($propClass)) {
                 case 'INTEGER':
                     $sqlQuery .= "{$propName} INT(" . $this->BO->getPropObject($propName)->getSize() . ')';
                     break;
                 case 'DOUBLE':
                     $sqlQuery .= "{$propName} DOUBLE(" . $this->BO->getPropObject($propName)->getSize(true) . ')';
                     break;
                 case 'STRING':
                     $sqlQuery .= "{$propName} VARCHAR(" . $this->BO->getPropObject($propName)->getSize() . ')';
                     break;
                 case 'SEQUENCE':
                     $sqlQuery .= "{$propName} VARCHAR(" . $this->BO->getPropObject($propName)->getSize() . ')';
                     break;
                 case 'TEXT':
                     $sqlQuery .= "{$propName} TEXT";
                     break;
                 case 'BOOLEAN':
                     $sqlQuery .= "{$propName} CHAR(1) DEFAULT '0'";
                     break;
                 case 'DATE':
                     $sqlQuery .= "{$propName} DATE";
                     break;
                 case 'TIMESTAMP':
                     $sqlQuery .= "{$propName} DATETIME";
                     break;
                 case 'ENUM':
                     $sqlQuery .= "{$propName} ENUM(";
                     $enumVals = $this->BO->getPropObject($propName)->getOptions();
                     foreach ($enumVals as $val) {
                         $sqlQuery .= "'" . $val . "',";
                     }
                     $sqlQuery = rtrim($sqlQuery, ',');
                     $sqlQuery .= ')';
                     break;
                 case 'DENUM':
                     $tmp = new DEnum(get_class($this->BO) . '::' . $propName);
                     $tmp->save();
                     $sqlQuery .= "{$propName} INT(11) ZEROFILL";
                     break;
                 case 'RELATION':
                     $sqlQuery .= "{$propName} INT(11) ZEROFILL UNSIGNED";
                     break;
                 default:
                     $sqlQuery .= '';
                     break;
             }
         }
     }
     $this->BO->setLastQuery($sqlQuery);
     if (!($result = self::getConnection()->query($sqlQuery))) {
         throw new AlphaException('Failed to add the new attribute [' . $propName . '] to the table [' . $this->BO->getTableName() . '], query is [' . $this->BO->getLastQuery() . ']');
         self::$logger->debug('<<addProperty');
     } else {
         self::$logger->info('Successfully added the [' . $propName . '] column onto the [' . $this->BO->getTableName() . '] table for the class [' . get_class($this->BO) . ']');
     }
     if ($this->BO->getMaintainHistory()) {
         $sqlQuery = str_replace($this->BO->getTableName(), $this->BO->getTableName() . '_history', $sqlQuery);
         if (!($result = self::getConnection()->query($sqlQuery))) {
             throw new AlphaException('Failed to add the new attribute [' . $propName . '] to the table [' . $this->BO->getTableName() . '_history], query is [' . $this->BO->getLastQuery() . ']');
             self::$logger->debug('<<addProperty');
         } else {
             self::$logger->info('Successfully added the [' . $propName . '] column onto the [' . $this->BO->getTableName() . '_history] table for the class [' . get_class($this->BO) . ']');
         }
     }
     self::$logger->debug('<<addProperty');
 }
Example #11
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');
 }