コード例 #1
0
ファイル: IndexController.php プロジェクト: alphadevx/alpha
 /**
  * Handle GET requests.
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @return Alpha\Util\Http\Response
  *
  * @since 1.0
  */
 public function doGET($request)
 {
     self::$logger->debug('>>doGET(request=[' . var_export($request, true) . '])');
     $config = ConfigProvider::getInstance();
     if ($config->get('app.check.installed') && !ActiveRecord::isInstalled()) {
         $response = new Response(301);
         $response->redirect($config->get('app.url') . '/install');
         self::$logger->warn('App not installed so re-directing to the install controller');
         self::$logger->debug('<<doGET');
         return $response;
     }
     $params = $request->getParams();
     $body = View::loadTemplateFragment('html', 'head.phtml', array('title' => $config->get('app.title'), 'description' => 'Welcome to our site', 'allowCSSOverrides' => true));
     $body .= View::loadTemplateFragment('html', 'index.phtml');
     $body .= View::loadTemplateFragment('html', 'footer.phtml');
     self::$logger->debug('<<doGET');
     return new Response(200, $body, array('Content-Type' => 'text/html'));
 }
コード例 #2
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');
 }
コード例 #3
0
ファイル: index.php プロジェクト: alphadevx/alpha
use Alpha\Util\Http\Filter\ClientTempBlacklistFilter;
use Alpha\Util\Http\Request;
use Alpha\Util\Http\Response;
use Alpha\Exception\ResourceNotFoundException;
use Alpha\Exception\ResourceNotAllowedException;
use Alpha\View\View;
try {
    $config = ConfigProvider::getInstance();
    set_exception_handler('Alpha\\Util\\ErrorHandlers::catchException');
    set_error_handler('Alpha\\Util\\ErrorHandlers::catchError', $config->get('php.error.log.level'));
    $front = new FrontController();
    if ($config->get('security.client.blacklist.filter.enabled')) {
        $front->registerFilter(new ClientBlacklistFilter());
    }
    if ($config->get('security.ip.blacklist.filter.enabled')) {
        $front->registerFilter(new IPBlacklistFilter());
    }
    if ($config->get('security.client.temp.blacklist.filter.enabled')) {
        $front->registerFilter(new ClientTempBlacklistFilter());
    }
    $request = new Request();
    $response = $front->process($request);
} catch (ResourceNotFoundException $rnfe) {
    $response = new Response(404, View::renderErrorPage(404, $rnfe->getMessage(), array('Content-Type' => 'text/html')));
} catch (ResourceNotAllowedException $rnae) {
    $response = new Response(403, View::renderErrorPage(403, $rnae->getMessage(), array('Content-Type' => 'text/html')));
}
if ($config->get('security.http.header.x.frame.options') != '' && $response->getHeader('X-Frame-Options') == null) {
    $response->setHeader('X-Frame-Options', $config->get('security.http.header.x.frame.options'));
}
echo $response->send();
コード例 #4
0
 /**
  * Method to handle DELETE requests.
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @throws Alpha\Exception\IllegalArguementException
  * @throws Alpha\Exception\SecurityException
  *
  * @return Alpha\Util\Http\Response
  *
  * @since 2.0
  */
 public function doDELETE($request)
 {
     self::$logger->debug('>>doDELETE(request=[' . var_export($request, true) . '])');
     $config = ConfigProvider::getInstance();
     $params = $request->getParams();
     $accept = $request->getAccept();
     try {
         // check the hidden security fields before accepting the form data
         if (!$this->checkSecurityFields()) {
             throw new SecurityException('This page cannot accept data from remote servers!');
         }
         if (isset($params['ActiveRecordType'])) {
             $ActiveRecordType = urldecode($params['ActiveRecordType']);
         } else {
             throw new IllegalArguementException('No ActiveRecord available to edit!');
         }
         if (class_exists($ActiveRecordType)) {
             $record = new $ActiveRecordType();
         } else {
             throw new IllegalArguementException('No ActiveRecord [' . $ActiveRecordType . '] available to edit!');
         }
         // check the hidden security fields before accepting the form POST data
         if (!$this->checkSecurityFields()) {
             throw new SecurityException('This page cannot accept post data from remote servers!');
         }
         $record->load($params['ActiveRecordOID']);
         ActiveRecord::begin();
         $record->delete();
         ActiveRecord::commit();
         ActiveRecord::disconnect();
         self::$logger->action('Deleted ' . $ActiveRecordType . ' instance with OID ' . $params['ActiveRecordOID']);
         if ($accept == 'application/json') {
             $response = new Response(200);
             $response->setHeader('Content-Type', 'application/json');
             $response->setBody(json_encode(array('message' => 'deleted')));
         } else {
             $response = new Response(301);
             if (isset($params['statusMessage'])) {
                 $this->setStatusMessage(View::displayUpdateMessage($params['statusMessage']));
             } else {
                 $this->setStatusMessage(View::displayUpdateMessage('Deleted'));
             }
             if ($this->getNextJob() != '') {
                 $response->redirect($this->getNextJob());
             } else {
                 if ($this->request->isSecureURI()) {
                     $response->redirect(FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=' . $ActiveRecordType . '&start=0&limit=' . $config->get('app.list.page.amount')));
                 } else {
                     $response->redirect($config->get('app.url') . '/records/' . $params['ActiveRecordType']);
                 }
             }
         }
     } catch (SecurityException $e) {
         self::$logger->warn($e->getMessage());
         throw new ResourceNotAllowedException($e->getMessage());
     } catch (RecordNotFoundException $e) {
         self::$logger->warn($e->getMessage());
         throw new ResourceNotFoundException('The item that you have requested cannot be found!');
     } catch (AlphaException $e) {
         self::$logger->error($e->getMessage());
         ActiveRecord::rollback();
     }
     self::$logger->debug('<<doDELETE');
     return $response;
 }
コード例 #5
0
ファイル: ExcelController.php プロジェクト: alphadevx/alpha
 /**
  * Loads the BO indicated in the GET request and handles the conversion to Excel.
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @return Alpha\Util\Http\Response
  *
  * @throws Alpha\Exception\ResourceNotFoundException
  *
  * @since 1.0
  */
 public function doGet($request)
 {
     self::$logger->debug('>>doGet(request=[' . var_export($request, true) . '])');
     $params = $request->getParams();
     $body = '';
     try {
         if (isset($params['ActiveRecordType'])) {
             $ActiveRecordType = $params['ActiveRecordType'];
             $className = "Alpha\\Model\\{$ActiveRecordType}";
             if (class_exists($className)) {
                 $this->BO = new $className();
             } else {
                 throw new IllegalArguementException('No ActiveRecord available to render!');
             }
             // the name of the file download
             if (isset($params['ActiveRecordOID'])) {
                 $fileName = $this->BO->getTableName() . '-' . $params['ActiveRecordOID'];
             } else {
                 $fileName = $this->BO->getTableName();
             }
             $response = new Response(200);
             // header info for browser
             $response->setHeader('Content-Type', 'application/vnd.ms-excel');
             $response->setHeader('Content-Disposition', 'attachment; filename=' . $fileName . '.xls');
             $response->setHeader('Pragma', 'no-cache');
             $response->setHeader('Expires', '0');
             // handle a single BO
             if (isset($params['ActiveRecordOID'])) {
                 $this->BO->load($params['ActiveRecordOID']);
                 ActiveRecord::disconnect();
                 $convertor = new ActiveRecord2Excel($this->BO);
                 $body .= $convertor->render();
             } else {
                 // handle all BOs of this type
                 $BOs = $BO->loadAll();
                 ActiveRecord::disconnect();
                 $first = true;
                 foreach ($BOs as $BO) {
                     $convertor = new ActiveRecord2Excel($BO);
                     if ($first) {
                         $body .= $convertor->render(true);
                         $first = false;
                     } else {
                         $body .= $convertor->render(false);
                     }
                 }
             }
         } else {
             throw new IllegalArguementException('No ActiveRecordType parameter available for ViewExcel controller!');
         }
     } catch (RecordNotFoundException $e) {
         self::$logger->error($e->getMessage());
         throw new ResourceNotFoundException($e->getMessage());
     } catch (IllegalArguementException $e) {
         self::$logger->error($e->getMessage());
         throw new ResourceNotFoundException($e->getMessage());
     }
     self::$logger->debug('<<__doGet');
     $response->setBody($body);
     return $response;
 }
コード例 #6
0
ファイル: LoginController.php プロジェクト: alphadevx/alpha
 /**
  * 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');
         }
     }
 }
コード例 #7
0
ファイル: FeedController.php プロジェクト: alphadevx/alpha
 /**
  * Handle GET requests.
  *
  * @param Alpha\Util\Http\Request $request
  *
  * @return Alpha\Util\Http\Response
  *
  * @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();
     $response = new Response(200);
     try {
         if (isset($params['ActiveRecordType'])) {
             $ActiveRecordType = urldecode($params['ActiveRecordType']);
         } else {
             throw new IllegalArguementException('ActiveRecordType not specified to generate feed!');
         }
         if (isset($params['type'])) {
             $type = $params['type'];
         } else {
             throw new IllegalArguementException('No feed type specified to generate feed!');
         }
         if (class_exists($ActiveRecordType)) {
             $this->ActiveRecordType = $ActiveRecordType;
         } else {
             throw new IllegalArguementException('No ActiveRecord available to render!');
         }
         $this->type = $type;
         $this->setup();
         switch ($type) {
             case 'RSS2':
                 $feed = new RSS2($this->ActiveRecordType, $this->title, str_replace('&', '&amp;', $request->getURI()), $this->description);
                 $feed->setFieldMappings($this->fieldMappings[0], $this->fieldMappings[1], $this->fieldMappings[2], $this->fieldMappings[3]);
                 $response->setHeader('Content-Type', 'application/rss+xml');
                 break;
             case 'RSS':
                 $feed = new RSS($this->ActiveRecordType, $this->title, str_replace('&', '&amp;', $request->getURI()), $this->description);
                 $feed->setFieldMappings($this->fieldMappings[0], $this->fieldMappings[1], $this->fieldMappings[2], $this->fieldMappings[3]);
                 $response->setHeader('Content-Type', 'application/rss+xml');
                 break;
             case 'Atom':
                 $feed = new Atom($this->ActiveRecordType, $this->title, str_replace('&', '&amp;', $request->getURI()), $this->description);
                 $feed->setFieldMappings($this->fieldMappings[0], $this->fieldMappings[1], $this->fieldMappings[2], $this->fieldMappings[3], $this->fieldMappings[4]);
                 if ($config->get('feeds.atom.author') != '') {
                     $feed->addAuthor($config->get('feeds.atom.author'));
                 }
                 $response->setHeader('Content-Type', 'application/atom+xml');
                 break;
         }
         // now add the twenty last items (from newest to oldest) to the feed, and render
         $feed->loadBOs(20, $this->sortBy);
         $response->setBody($feed->render());
         // log the request for this news feed
         $feedLog = new LogProviderFile();
         $feedLog->setPath($config->get('app.file.store.dir') . 'logs/feeds.log');
         $feedLog->writeLine(array($this->ActiveRecordType, $this->type, date('Y-m-d H:i:s'), $request->getUserAgent(), $request->getIP()));
     } catch (IllegalArguementException $e) {
         self::$logger->error($e->getMessage());
         throw new ResourceNotFoundException($e->getMessage());
     }
     self::$logger->debug('<<doGet');
     return $response;
 }
コード例 #8
0
ファイル: ResponseTest.php プロジェクト: alphadevx/alpha
 /**
  * Testing the redirect method.
  */
 public function testRedirect()
 {
     $response = new Response(301);
     try {
         $response->redirect('notreallythere');
         $this->fail('Testing the redirect method');
     } catch (IllegalArguementException $e) {
         $this->assertEquals('Unable to redirect to URL [notreallythere] as it is invalid', $e->getMessage());
     }
     $response->redirect('http://alphaframework.org/');
     $this->assertEquals('http://alphaframework.org/', $response->getHeader('Location'), 'Testing the redirect method');
     $this->assertEquals(1, count($response->getHeaders()), 'Testing the redirect method');
 }
コード例 #9
0
ファイル: Controller.php プロジェクト: alphadevx/alpha
 /**
  * {@inheritdoc}
  *
  * @since 2.0.2
  */
 public function doTRACE($request)
 {
     $HTTPMethods = array('HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
     $supported = array();
     foreach ($HTTPMethods as $HTTPMethod) {
         $reflector = new \ReflectionMethod($this, 'do' . $HTTPMethod);
         $isOverridden = $reflector->getDeclaringClass()->getName() === get_class($this);
         if ($isOverridden) {
             $supported[] = $HTTPMethod;
         }
     }
     $supported = implode(',', $supported);
     $response = new Response(405);
     $response->setHeader('Allow', $supported);
     return $response;
 }
コード例 #10
0
ファイル: ArticleController.php プロジェクト: alphadevx/alpha
 /**
  * Method to handle PUT requests.
  *
  * @param Alpha\Util\Http\Request
  *
  * @return Alpha\Util\Http\Response
  *
  * @since 1.0
  */
 public function doPUT($request)
 {
     self::$logger->debug('>>doPUT($request=[' . var_export($request, true) . '])');
     $config = ConfigProvider::getInstance();
     $params = $request->getParams();
     try {
         // check the hidden security fields before accepting the form POST data
         if (!$this->checkSecurityFields()) {
             throw new SecurityException('This page cannot accept post data from remote servers!');
             self::$logger->debug('<<doPUT');
         }
         if (isset($params['markdownTextBoxRows']) && $params['markdownTextBoxRows'] != '') {
             $viewState = ViewState::getInstance();
             $viewState->set('markdownTextBoxRows', $params['markdownTextBoxRows']);
         }
         if (isset($params['title']) || isset($params['ActiveRecordOID'])) {
             if (isset($params['ActiveRecordType']) && class_exists($params['ActiveRecordType'])) {
                 $record = new $params['ActiveRecordType']();
             } else {
                 $record = new Article();
             }
             if (isset($params['title'])) {
                 $title = str_replace($config->get('cms.url.title.separator'), ' ', $params['title']);
                 $record->loadByAttribute('title', $title, false, array('OID', 'version_num', 'created_ts', 'updated_ts', 'title', 'author', 'published', 'content', 'headerContent'));
             } else {
                 $record->load($params['ActiveRecordOID']);
             }
             // uploading an article attachment
             if (isset($params['uploadBut'])) {
                 $source = $request->getFile('userfile')['tmp_name'];
                 $dest = $record->getAttachmentsLocation() . '/' . $request->getFile('userfile')['name'];
                 // upload the file to the attachments directory
                 FileUtils::copy($source, $dest);
                 if (!file_exists($dest)) {
                     throw new AlphaException('Could not move the uploaded file [' . $request->getFile('userfile')['name'] . ']');
                 }
                 // set read/write permissions on the file
                 $success = chmod($dest, 0666);
                 if (!$success) {
                     throw new AlphaException('Unable to set read/write permissions on the uploaded file [' . $dest . '].');
                 }
                 if ($success) {
                     self::$logger->action('File ' . $source . ' uploaded to ' . $dest);
                     $this->setStatusMessage(View::displayUpdateMessage('File ' . $source . ' uploaded to ' . $dest));
                 }
             } elseif (isset($params['deletefile']) && $params['deletefile'] != '') {
                 $success = unlink($record->getAttachmentsLocation() . '/' . $params['deletefile']);
                 if (!$success) {
                     throw new AlphaException('Could not delete the file [' . $params['deletefile'] . ']');
                 }
                 if ($success) {
                     self::$logger->action('File ' . $record->getAttachmentsLocation() . '/' . $params['deletefile'] . ' deleted');
                     $this->setStatusMessage(View::displayUpdateMessage('File ' . $record->getAttachmentsLocation() . '/' . $params['deletefile'] . ' deleted'));
                 }
             } else {
                 self::$logger->debug('<<doPUT');
                 return parent::doPUT($request);
             }
         } else {
             throw new IllegalArguementException('No valid article ID provided!');
         }
     } catch (SecurityException $e) {
         $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
         self::$logger->warn($e->getMessage());
     } catch (IllegalArguementException $e) {
         $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
         self::$logger->error($e->getMessage());
     } catch (RecordNotFoundException $e) {
         self::$logger->warn($e->getMessage());
         $this->setStatusMessage(View::displayErrorMessage('Failed to load the requested article from the database!'));
     } catch (AlphaException $e) {
         $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
         self::$logger->error($e->getMessage());
     }
     $response = new Response(301);
     if ($this->getNextJob() != '') {
         $response->redirect($this->getNextJob());
     } else {
         if ($this->request->isSecureURI()) {
             $response->redirect(FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType=Alpha\\Model\\Article&ActiveRecordOID=' . $record->getOID() . '&view=edit'));
         } else {
             $title = str_replace(' ', $config->get('cms.url.title.separator'), $record->get('title'));
             $response->redirect($config->get('app.url') . '/a/' . $title . '/edit');
         }
     }
     self::$logger->debug('<<doPUT');
     return $response;
 }