From f82b818bdb852f63fdb4a431808f37902f4272ff Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Tue, 13 May 2014 20:14:00 +0200 Subject: break all the things! --- appinfo/app.php | 4 +- appinfo/application.php | 49 +++--- appinfo/routes.php | 2 +- businesslayer/businesslayer.php | 5 +- businesslayer/feedbusinesslayer.php | 29 ++-- businesslayer/folderbusinesslayer.php | 4 +- businesslayer/itembusinesslayer.php | 9 +- controller/apicontroller.php | 94 ----------- controller/feedapicontroller.php | 91 ++++++----- controller/feedcontroller.php | 4 - controller/folderapicontroller.php | 17 +- controller/foldercontroller.php | 65 +++----- controller/itemapicontroller.php | 146 +++++++++-------- controller/itemcontroller.php | 8 +- controller/jsonhttperror.php | 36 +++++ controller/pagecontroller.php | 27 ++-- controller/utilityapicontroller.php | 68 ++++++++ core/db.php | 41 ----- core/logger.php | 52 ------ db/doesnotexistexception.php | 31 ---- db/entity.php | 222 -------------------------- db/feed.php | 2 + db/feedmapper.php | 5 +- db/folder.php | 2 + db/foldermapper.php | 5 +- db/item.php | 3 + db/itemmapper.php | 6 +- db/mapper.php | 273 -------------------------------- db/mapperfactory.php | 5 +- db/multipleobjectsreturnedexception.php | 31 ---- db/postgres/itemmapper.php | 8 +- middleware/corsmiddleware.php | 57 ------- utility/config.php | 13 +- 33 files changed, 364 insertions(+), 1050 deletions(-) delete mode 100644 controller/apicontroller.php create mode 100644 controller/jsonhttperror.php create mode 100644 controller/utilityapicontroller.php delete mode 100644 core/db.php delete mode 100644 core/logger.php delete mode 100644 db/doesnotexistexception.php delete mode 100644 db/entity.php delete mode 100644 db/mapper.php delete mode 100644 db/multipleobjectsreturnedexception.php delete mode 100644 middleware/corsmiddleware.php diff --git a/appinfo/app.php b/appinfo/app.php index 1cc9994ae..ebd5f47a7 100644 --- a/appinfo/app.php +++ b/appinfo/app.php @@ -25,6 +25,8 @@ $config->registerHooks(); try { $config->testDependencies(); } catch(\OCA\News\Config\DependencyException $e) { - $container->getLogger()->log($e->getMessage()); + $logger = $container->getLogger(); + $params = $container->getLoggerParameters(); + $logger->warn($e->getMessage(), $params); } diff --git a/appinfo/application.php b/appinfo/application.php index fc2e00d1a..bf11936bd 100644 --- a/appinfo/application.php +++ b/appinfo/application.php @@ -18,15 +18,12 @@ use \OCP\AppFramework\App; use \OCA\News\Config\AppConfig; -use \OCA\News\Core\Logger; -use \OCA\News\Core\Db; - use \OCA\News\Controller\PageController; use \OCA\News\Controller\FolderController; use \OCA\News\Controller\FeedController; use \OCA\News\Controller\ItemController; use \OCA\News\Controller\ExportController; -use \OCA\News\Controller\ApiController; +use \OCA\News\Controller\UtilityApiController; use \OCA\News\Controller\FolderApiController; use \OCA\News\Controller\FeedApiController; use \OCA\News\Controller\ItemApiController; @@ -55,8 +52,6 @@ use \OCA\News\ArticleEnhancer\Enhancer; use \OCA\News\ArticleEnhancer\XPathArticleEnhancer; use \OCA\News\ArticleEnhancer\RegexArticleEnhancer; -use \OCA\News\Middleware\CORSMiddleware; - require_once __DIR__ . '/../3rdparty/htmlpurifier/library/HTMLPurifier.auto.php'; @@ -133,8 +128,8 @@ class Application extends App { ); }); - $container->registerService('ApiController', function($c) { - return new ApiController( + $container->registerService('UtilityApiController', function($c) { + return new UtilityApiController( $c->query('AppName'), $c->query('Request'), $c->query('Updater'), @@ -160,7 +155,8 @@ class Application extends App { $c->query('FeedBusinessLayer'), $c->query('ItemBusinessLayer'), $c->query('Logger'), - $c->query('UserId') + $c->query('UserId'), + $c->query('LoggerParameters') ); }); @@ -196,7 +192,8 @@ class Application extends App { $c->query('TimeFactory'), $c->query('Config'), $c->query('Enhancer'), - $c->query('HTMLPurifier') + $c->query('HTMLPurifier'), + $c->query('LoggerParameters') ); }); @@ -284,11 +281,15 @@ class Application extends App { }); $container->registerService('Logger', function($c) { - return new Logger($c->query('AppName')); + return $c->query('ServerContainer')->getLogger(); + }); + + $container->registerService('LoggerParameters', function($c) { + return array('app' => $c->query('AppName')); }); $container->registerService('Db', function() { - return new Db(); + return $c->query('ServerContainer')->getDb(); }); $container->registerService('CoreConfig', function($c) { @@ -313,7 +314,11 @@ class Application extends App { }); $container->registerService('Config', function($c) { - $config = new Config($c->query('ConfigView'), $c->query('Logger')); + $config = new Config( + $c->query('ConfigView'), + $c->query('Logger'), + $c->query('LoggerParameters') + ); $config->read('config.ini', true); return $config; }); @@ -426,17 +431,6 @@ class Application extends App { ); }); - /** - * Middleware - */ - $container->registerService('CORSMiddleware', function($c) { - return new CORSMiddleware( - $c->query('Request') - ); - }); - - $container->registerMiddleWare('CORSMiddleware'); - } public function getAppConfig() { @@ -447,5 +441,12 @@ class Application extends App { public function getLogger() { return $this->getContainer()->query('Logger'); } + + + public function getLoggerParameters() { + return $this->getContainer()->query('LoggerParameters'); + } + + } diff --git a/appinfo/routes.php b/appinfo/routes.php index 5ba7a2df7..4d91273b6 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -63,7 +63,7 @@ $application->registerRoutes($this, array('routes' => array( array('name' => 'api#version', 'url' => '/api/v1-2/version', 'verb' => 'GET'), array('name' => 'api#before_update', 'url' => '/api/v1-2/cleanup/before-update', 'verb' => 'GET'), array('name' => 'api#after_update', 'url' => '/api/v1-2/cleanup/after-update', 'verb' => 'GET'), - array('name' => 'api#cors', 'url' => '/api/v1-2/{path}', 'verb' => 'OPTIONS', 'requirements' => array('path' => '.+')), + array('name' => 'api#preflighted_cors', 'url' => '/api/v1-2/{path}', 'verb' => 'OPTIONS', 'requirements' => array('path' => '.+')), // folders array('name' => 'folder_api#index', 'url' => '/api/v1-2/folders', 'verb' => 'GET'), diff --git a/businesslayer/businesslayer.php b/businesslayer/businesslayer.php index ea03db1af..dc6fc1a68 100644 --- a/businesslayer/businesslayer.php +++ b/businesslayer/businesslayer.php @@ -13,8 +13,9 @@ namespace OCA\News\BusinessLayer; -use \OCA\News\Db\DoesNotExistException; -use \OCA\News\Db\MultipleObjectsReturnedException; +use \OCP\AppFramework\Db\DoesNotExistException; +use \OCP\AppFramework\Db\MultipleObjectsReturnedException; + use \OCA\News\Db\IMapper; diff --git a/businesslayer/feedbusinesslayer.php b/businesslayer/feedbusinesslayer.php index 024c7b8ea..acb999aa4 100644 --- a/businesslayer/feedbusinesslayer.php +++ b/businesslayer/feedbusinesslayer.php @@ -12,8 +12,11 @@ */ namespace OCA\News\BusinessLayer; -use \OCA\News\Core\Logger; -use \OCA\News\Db\DoesNotExistException; + +use \OCP\ILogger; +use \OCP\IL10N; +use \OCP\AppFramework\Db\DoesNotExistException; + use \OCA\News\Db\Feed; use \OCA\News\Db\Item; use \OCA\News\Db\FeedMapper; @@ -35,16 +38,18 @@ class FeedBusinessLayer extends BusinessLayer { private $autoPurgeMinimumInterval; private $enhancer; private $purifier; + private $loggerParams; public function __construct(FeedMapper $feedMapper, Fetcher $feedFetcher, ItemMapper $itemMapper, - Logger $logger, - $l10n, + ILogger $logger, + IL10N $l10n, $timeFactory, Config $config, Enhancer $enhancer, - $purifier){ + $purifier, + $loggerParams){ parent::__construct($feedMapper); $this->feedFetcher = $feedFetcher; $this->itemMapper = $itemMapper; @@ -55,6 +60,7 @@ class FeedBusinessLayer extends BusinessLayer { $this->enhancer = $enhancer; $this->purifier = $purifier; $this->feedMapper = $feedMapper; + $this->loggerParams = $loggerParams; } /** @@ -131,7 +137,7 @@ class FeedBusinessLayer extends BusinessLayer { return $feed; } catch(FetcherException $ex){ - $this->logger->log($ex->getMessage(), 'debug'); + $this->logger->debug($ex->getMessage(), $this->loggerParams); throw new BusinessLayerException( $this->l10n->t( 'Can not add feed: URL does not exist, SSL Certificate can not be validated ' . @@ -150,8 +156,8 @@ class FeedBusinessLayer extends BusinessLayer { try { $this->update($feed->getId(), $feed->getUserId()); } catch(BusinessLayerException $ex){ - $this->logger->log('Could not update feed ' . $ex->getMessage(), - 'debug'); + $this->logger->debug('Could not update feed ' . $ex->getMessage(), + $this->loggerParams); } } } @@ -200,9 +206,10 @@ class FeedBusinessLayer extends BusinessLayer { } catch(FetcherException $ex){ // failed updating is not really a problem, so only log it - $this->logger->log('Can not update feed with url ' . $existingFeed->getUrl() . - ': Not found or bad source', 'debug'); - $this->logger->log($ex->getMessage(), 'debug'); + + $this->logger->debug('Can not update feed with url ' . $existingFeed->getUrl() . + ': Not found or bad source', $this->loggerParams); + $this->logger->debug($ex->getMessage(), $this->loggerParams); } return $this->feedMapper->find($feedId, $userId); diff --git a/businesslayer/folderbusinesslayer.php b/businesslayer/folderbusinesslayer.php index 924e23c25..f58e937b2 100644 --- a/businesslayer/folderbusinesslayer.php +++ b/businesslayer/folderbusinesslayer.php @@ -13,6 +13,8 @@ namespace OCA\News\BusinessLayer; +use \OCP\IL10N; + use \OCA\News\Db\Folder; use \OCA\News\Db\FolderMapper; use \OCA\News\Utility\Config; @@ -26,7 +28,7 @@ class FolderBusinessLayer extends BusinessLayer { private $folderMapper; public function __construct(FolderMapper $folderMapper, - $l10n, + IL10N $l10n, $timeFactory, Config $config){ parent::__construct($folderMapper); diff --git a/businesslayer/itembusinesslayer.php b/businesslayer/itembusinesslayer.php index 85fa4d10f..23f6bcd2d 100644 --- a/businesslayer/itembusinesslayer.php +++ b/businesslayer/itembusinesslayer.php @@ -13,11 +13,12 @@ namespace OCA\News\BusinessLayer; +use \OCP\AppFramework\Db\DoesNotExistException; + use \OCA\News\Db\Item; use \OCA\News\Db\ItemMapper; use \OCA\News\Db\StatusFlag; use \OCA\News\Db\FeedType; -use \OCA\News\Db\DoesNotExistException; use \OCA\News\Utility\Config; @@ -28,8 +29,10 @@ class ItemBusinessLayer extends BusinessLayer { private $timeFactory; private $itemMapper; - public function __construct(ItemMapper $itemMapper, StatusFlag $statusFlag, - $timeFactory, Config $config){ + public function __construct(ItemMapper $itemMapper, + StatusFlag $statusFlag, + $timeFactory, + Config $config){ parent::__construct($itemMapper); $this->statusFlag = $statusFlag; $this->autoPurgeCount = $config->getAutoPurgeCount(); diff --git a/controller/apicontroller.php b/controller/apicontroller.php deleted file mode 100644 index a23a60318..000000000 --- a/controller/apicontroller.php +++ /dev/null @@ -1,94 +0,0 @@ - - * @author Bernhard Posselt - * @copyright Alessandro Cosentino 2012 - * @copyright Bernhard Posselt 2012, 2014 - */ - -namespace OCA\News\Controller; - -use \OCP\IRequest; -use \OCP\IConfig; -use \OCP\AppFramework\Controller; -use \OCP\AppFramework\Http; -use \OCP\AppFramework\Http\JSONResponse; -use \OCP\AppFramework\Http\Response; - -use \OCA\News\Utility\Updater; - -class ApiController extends Controller { - - private $updater; - private $settings; - - public function __construct($appName, IRequest $request, Updater $updater, - IConfig $settings){ - parent::__construct($appName, $request); - $this->updater = $updater; - $this->settings = $settings; - } - - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @API - */ - public function version() { - $version = $this->settings->getAppValue($this->appName, - 'installed_version'); - $response = new JSONResponse(array('version' => $version)); - return $response; - } - - - /** - * @NoCSRFRequired - */ - public function beforeUpdate() { - $this->updater->beforeUpdate(); - return new JSONResponse(); - } - - - /** - * @NoCSRFRequired - */ - public function afterUpdate() { - $this->updater->afterUpdate(); - return new JSONResponse(); - } - - - /** - * @NoAdminRequired - * @NoCSRFRequired - * @PublicPage - */ - public function cors() { - // needed for webapps access due to cross origin request policy - if(isset($this->request->server['HTTP_ORIGIN'])) { - $origin = $this->request->server['HTTP_ORIGIN']; - } else { - $origin = '*'; - } - - $response = new Response(); - $response->addHeader('Access-Control-Allow-Origin', $origin); - $response->addHeader('Access-Control-Allow-Methods', - 'PUT, POST, GET, DELETE'); - $response->addHeader('Access-Control-Allow-Credentials', 'false'); - $response->addHeader('Access-Control-Max-Age', '1728000'); - $response->addHeader('Access-Control-Allow-Headers', - 'Authorization, Content-Type'); - return $response; - } - - -} diff --git a/controller/feedapicontroller.php b/controller/feedapicontroller.php index 05c50543e..883732c87 100644 --- a/controller/feedapicontroller.php +++ b/controller/feedapicontroller.php @@ -14,11 +14,11 @@ namespace OCA\News\Controller; use \OCP\IRequest; -use \OCP\AppFramework\Controller; +use \OCP\ILogger; +use \OCP\AppFramework\ApiController; use \OCP\AppFramework\Http; use \OCP\AppFramework\Http\JSONResponse; -use \OCA\News\Core\Logger; use \OCA\News\BusinessLayer\FeedBusinessLayer; use \OCA\News\BusinessLayer\FolderBusinessLayer; use \OCA\News\BusinessLayer\ItemBusinessLayer; @@ -26,34 +26,37 @@ use \OCA\News\BusinessLayer\BusinessLayerException; use \OCA\News\BusinessLayer\BusinessLayerConflictException; -class FeedApiController extends Controller { +class FeedApiController extends ApiController { private $itemBusinessLayer; private $feedBusinessLayer; private $folderBusinessLayer; private $userId; private $logger; + private $loggerParams; public function __construct($appName, IRequest $request, FolderBusinessLayer $folderBusinessLayer, FeedBusinessLayer $feedBusinessLayer, ItemBusinessLayer $itemBusinessLayer, - Logger $logger, - $userId){ + ILogger $logger, + $userId, + $loggerParams){ parent::__construct($appName, $request); $this->folderBusinessLayer = $folderBusinessLayer; $this->feedBusinessLayer = $feedBusinessLayer; $this->itemBusinessLayer = $itemBusinessLayer; $this->userId = $userId; $this->logger = $logger; + $this->loggerParams = $loggerParams; } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS */ public function index() { @@ -62,56 +65,66 @@ class FeedApiController extends Controller { 'starredCount' => $this->itemBusinessLayer->starredCount($this->userId) ); - foreach ($this->feedBusinessLayer->findAll($this->userId) as $feed) { + $feeds = $this->feedBusinessLayer->findAll($this->userId); + foreach ($feeds as $feed) { array_push($result['feeds'], $feed->toAPI()); } // check case when there are no items try { - $result['newestItemId'] = - $this->itemBusinessLayer->getNewestItemId($this->userId); + $result['newestItemId'] = $this->itemBusinessLayer + ->getNewestItemId($this->userId); // An exception occurs if there is a newest item. If there is none, // simply ignore it and do not add the newestItemId } catch(BusinessLayerException $ex) {} - return new JSONResponse($result); + return $result; } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param string $url + * @param int $folderId */ - public function create() { - $feedUrl = $this->params('url'); - $folderId = (int) $this->params('folderId', 0); - + public function create($url, $folderId=0) { try { $this->feedBusinessLayer->purgeDeleted($this->userId, false); - $feed = $this->feedBusinessLayer->create($feedUrl, $folderId, $this->userId); + $feed = $this->feedBusinessLayer->create($url, $folderId, + $this->userId); $result = array( 'feeds' => array($feed->toAPI()) ); try { - $result['newestItemId'] = - $this->itemBusinessLayer->getNewestItemId($this->userId); + $result['newestItemId'] = $this->itemBusinessLayer + ->getNewestItemId($this->userId); // An exception occurs if there is a newest item. If there is none, // simply ignore it and do not add the newestItemId } catch(BusinessLayerException $ex) {} - return new JSONResponse($result); + return $result; } catch(BusinessLayerConflictException $ex) { - return new JSONResponse(array('message' => $ex->getMessage()), - Http::STATUS_CONFLICT); + + return new JSONResponse( + array('message' => $ex->getMessage()), + Http::STATUS_CONFLICT + ); + } catch(BusinessLayerException $ex) { - return new JSONResponse(array('message' => $ex->getMessage()), - Http::STATUS_NOT_FOUND); + + return new JSONResponse( + array('message' => $ex->getMessage()), + Http::STATUS_NOT_FOUND + ); + } } @@ -119,17 +132,18 @@ class FeedApiController extends Controller { /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int $feedId */ - public function delete() { - $feedId = (int) $this->params('feedId'); - + public function delete($feedId) { try { $this->feedBusinessLayer->delete($feedId, $this->userId); - return new JSONResponse(); } catch(BusinessLayerException $ex) { - return new JSONResponse(array('message' => $ex->getMessage()), - Http::STATUS_NOT_FOUND); + return new JSONResponse( + array('message' => $ex->getMessage()), + Http::STATUS_NOT_FOUND + ); } } @@ -137,21 +151,20 @@ class FeedApiController extends Controller { /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS */ public function read() { $feedId = (int) $this->params('feedId'); $newestItemId = (int) $this->params('newestItemId'); $this->itemBusinessLayer->readFeed($feedId, $newestItemId, $this->userId); - return new JSONResponse(); } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS */ public function move() { $feedId = (int) $this->params('feedId'); @@ -159,7 +172,6 @@ class FeedApiController extends Controller { try { $this->feedBusinessLayer->move($feedId, $folderId, $this->userId); - return new JSONResponse(); } catch(BusinessLayerException $ex) { return new JSONResponse(array('message' => $ex->getMessage()), Http::STATUS_NOT_FOUND); @@ -170,7 +182,7 @@ class FeedApiController extends Controller { /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS */ public function rename() { $feedId = (int) $this->params('feedId'); @@ -178,7 +190,6 @@ class FeedApiController extends Controller { try { $this->feedBusinessLayer->rename($feedId, $feedTitle, $this->userId); - return new JSONResponse(); } catch(BusinessLayerException $ex) { return new JSONResponse(array('message' => $ex->getMessage()), Http::STATUS_NOT_FOUND); @@ -188,7 +199,7 @@ class FeedApiController extends Controller { /** * @NoCSRFRequired - * @API + * @CORS */ public function fromAllUsers() { $feeds = $this->feedBusinessLayer->findAllFromAllUsers(); @@ -216,11 +227,9 @@ class FeedApiController extends Controller { $this->feedBusinessLayer->update($feedId, $userId); // ignore update failure (feed could not be reachable etc, we dont care) } catch(\Exception $ex) { - $this->logger->log('Could not update feed ' . $ex->getMessage(), - 'debug'); + $this->logger->debug('Could not update feed ' . $ex->getMessage(), + $this->loggerParams); } - return new JSONResponse(); - } diff --git a/controller/feedcontroller.php b/controller/feedcontroller.php index 56c7d5af8..02e523dff 100644 --- a/controller/feedcontroller.php +++ b/controller/feedcontroller.php @@ -167,7 +167,6 @@ class FeedController extends Controller { try { $this->feedBusinessLayer->markDeleted($feedId, $this->userId); - return new JSONResponse(); } catch(BusinessLayerException $ex) { return new JSONResponse(array( 'msg' => $ex->getMessage() @@ -215,7 +214,6 @@ class FeedController extends Controller { try { $this->feedBusinessLayer->move($feedId, $parentFolderId, $this->userId); - return new JSONResponse(); } catch(BusinessLayerException $ex) { return new JSONResponse(array( 'msg' => $ex->getMessage() @@ -232,7 +230,6 @@ class FeedController extends Controller { try { $this->feedBusinessLayer->rename($feedId, $feedTitle, $this->userId); - return new JSONResponse(); } catch(BusinessLayerException $ex) { return new JSONResponse(array( 'msg' => $ex->getMessage() @@ -286,7 +283,6 @@ class FeedController extends Controller { try { $this->feedBusinessLayer->unmarkDeleted($feedId, $this->userId); - return new JSONResponse(); } catch(BusinessLayerException $ex) { return new JSONResponse(array( 'msg' => $ex->getMessage() diff --git a/controller/folderapicontroller.php b/controller/folderapicontroller.php index 4e566541c..40ffc1389 100644 --- a/controller/folderapicontroller.php +++ b/controller/folderapicontroller.php @@ -14,7 +14,7 @@ namespace OCA\News\Controller; use \OCP\IRequest; -use \OCP\AppFramework\Controller; +use \OCP\AppFramework\ApiController; use \OCP\AppFramework\Http; use \OCP\AppFramework\Http\JSONResponse; @@ -25,7 +25,7 @@ use \OCA\News\BusinessLayer\BusinessLayerConflictException; use \OCA\News\BusinessLayer\BusinessLayerValidationException; -class FolderApiController extends Controller { +class FolderApiController extends ApiController { private $folderBusinessLayer; private $itemBusinessLayer; @@ -46,7 +46,7 @@ class FolderApiController extends Controller { /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS */ public function index() { $result = array( @@ -64,7 +64,7 @@ class FolderApiController extends Controller { /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS */ public function create() { $folderName = $this->params('name'); @@ -93,14 +93,13 @@ class FolderApiController extends Controller { /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS */ public function delete() { $folderId = (int) $this->params('folderId'); try { $this->folderBusinessLayer->delete($folderId, $this->userId); - return new JSONResponse(); } catch(BusinessLayerException $ex) { return new JSONResponse(array('message' => $ex->getMessage()), Http::STATUS_NOT_FOUND); @@ -111,7 +110,7 @@ class FolderApiController extends Controller { /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS */ public function update() { $folderId = (int) $this->params('folderId'); @@ -119,7 +118,6 @@ class FolderApiController extends Controller { try { $this->folderBusinessLayer->rename($folderId, $folderName, $this->userId); - return new JSONResponse(); } catch(BusinessLayerValidationException $ex) { return new JSONResponse(array('message' => $ex->getMessage()), @@ -139,14 +137,13 @@ class FolderApiController extends Controller { /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS */ public function read() { $folderId = (int) $this->params('folderId'); $newestItemId = (int) $this->params('newestItemId'); $this->itemBusinessLayer->readFolder($folderId, $newestItemId, $this->userId); - return new JSONResponse(); } diff --git a/controller/foldercontroller.php b/controller/foldercontroller.php index caa07f4d2..76476dd7a 100644 --- a/controller/foldercontroller.php +++ b/controller/foldercontroller.php @@ -27,12 +27,15 @@ use \OCA\News\BusinessLayer\BusinessLayerValidationException; class FolderController extends Controller { + use JSONHttpError; + private $folderBusinessLayer; private $feedBusinessLayer; private $itemBusinessLayer; private $userId; - public function __construct($appName, IRequest $request, + public function __construct($appName, + IRequest $request, FolderBusinessLayer $folderBusinessLayer, FeedBusinessLayer $feedBusinessLayer, ItemBusinessLayer $itemBusinessLayer, @@ -53,76 +56,64 @@ class FolderController extends Controller { $result = array( 'folders' => $folders ); - return new JSONResponse($result); + return $result; } - private function setOpened($isOpened){ - $folderId = (int) $this->params('folderId'); - + private function setOpened($isOpened, $folderId){ $this->folderBusinessLayer->open($folderId, $isOpened, $this->userId); } /** * @NoAdminRequired + * + * @param int $folderId */ - public function open(){ + public function open($folderId){ try { - $this->setOpened(true); - return new JSONResponse(); + $this->setOpened(true, $folderId); } catch(BusinessLayerException $ex) { - return new JSONResponse(array( - 'msg' => $ex->getMessage() - ), Http::STATUS_NOT_FOUND); + return $this->error($ex, Http::STATUS_NOT_FOUND); } } /** * @NoAdminRequired + * + * @param int $folderId */ - public function collapse(){ + public function collapse($folderId){ try { - $this->setOpened(false); - return new JSONResponse(); + $this->setOpened(false, $folderId); } catch(BusinessLayerException $ex) { - return new JSONResponse(array( - 'msg' => $ex->getMessage() - ), Http::STATUS_NOT_FOUND); + return $this->error($ex, Http::STATUS_NOT_FOUND); } } /** * @NoAdminRequired + * + * @param string $folderName */ - public function create(){ - $folderName = $this->params('folderName'); - + public function create($folderName){ try { // we need to purge deleted folders if a folder is created to // prevent already exists exceptions $this->folderBusinessLayer->purgeDeleted($this->userId, false); - $folder = $this->folderBusinessLayer->create($folderName, $this->userId); $params = array( 'folders' => array($folder) ); - return new JSONResponse($params); - - + return $params; } catch(BusinessLayerConflictException $ex) { - return new JSONResponse(array( - 'msg' => $ex->getMessage() - ), Http::STATUS_CONFLICT); - + return $this->error($ex, Http::STATUS_CONFLICT); } catch(BusinessLayerValidationException $ex) { - return new JSONResponse(array( - 'msg' => $ex->getMessage() - ), Http::STATUS_UNPROCESSABLE_ENTITY); + return $this->error($ex, Http::STATUS_UNPROCESSABLE_ENTITY); } } @@ -130,17 +121,14 @@ class FolderController extends Controller { /** * @NoAdminRequired + * + * @param int $folderId */ - public function delete(){ - $folderId = (int) $this->params('folderId'); - + public function delete($folderId){ try { $this->folderBusinessLayer->markDeleted($folderId, $this->userId); - return new JSONResponse(); } catch (BusinessLayerException $ex){ - return new JSONResponse(array( - 'msg' => $ex->getMessage() - ), Http::STATUS_NOT_FOUND); + return $this->error($ex, Http::STATUS_NOT_FOUND); } } @@ -202,7 +190,6 @@ class FolderController extends Controller { try { $this->folderBusinessLayer->unmarkDeleted($folderId, $this->userId); - return new JSONResponse(); } catch (BusinessLayerException $ex){ return new JSONResponse(array( 'msg' => $ex->getMessage() diff --git a/controller/itemapicontroller.php b/controller/itemapicontroller.php index 533fb2032..767023877 100644 --- a/controller/itemapicontroller.php +++ b/controller/itemapicontroller.php @@ -14,14 +14,16 @@ namespace OCA\News\Controller; use \OCP\IRequest; -use \OCP\AppFramework\Controller; +use \OCP\AppFramework\ApiController; use \OCP\AppFramework\Http; use \OCP\AppFramework\Http\JSONResponse; use \OCA\News\BusinessLayer\ItemBusinessLayer; use \OCA\News\BusinessLayer\BusinessLayerException; -class ItemApiController extends Controller { +class ItemApiController extends ApiController { + + use JSONHttpError; private $itemBusinessLayer; private $userId; @@ -39,25 +41,19 @@ class ItemApiController extends Controller { /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int $type + * @param int $id + * @param bool $getRead + * @param int $batchSize + * @param int $offset */ - public function index() { + public function index($type, $id, $getRead, $batchSize=20, $offset=0) { $result = array( 'items' => array() ); - $batchSize = (int) $this->params('batchSize', 20); - $offset = (int) $this->params('offset', 0); - $type = (int) $this->params('type'); - $id = (int) $this->params('id'); - $showAll = $this->params('getRead'); - - if($showAll === 'true' || $showAll === true) { - $showAll = true; - } else { - $showAll = false; - } - $items = $this->itemBusinessLayer->findAll( $id, $type, @@ -71,24 +67,24 @@ class ItemApiController extends Controller { array_push($result['items'], $item->toAPI()); } - return new JSONResponse($result); + return $result; } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int $type + * @param int $id + * @param int $lastModified */ - public function updated() { + public function updated($type, $id, $lastModified=0) { $result = array( 'items' => array() ); - $lastModified = (int) $this->params('lastModified', 0); - $type = (int) $this->params('type'); - $id = (int) $this->params('id'); - $items = $this->itemBusinessLayer->findAllNew( $id, $type, @@ -101,31 +97,24 @@ class ItemApiController extends Controller { array_push($result['items'], $item->toAPI()); } - return new JSONResponse($result); + $result; } - private function setRead($isRead) { - $itemId = (int) $this->params('itemId'); + private function setRead($isRead, $itemId) { try { $this->itemBusinessLayer->read($itemId, $isRead, $this->userId); - return new JSONResponse(); } catch(BusinessLayerException $ex){ - return new JSONResponse(array('message' => $ex->getMessage()), - Http::STATUS_NOT_FOUND); + return $this->error($ex, Http::STATUS_NOT_FOUND); } } - private function setStarred($isStarred) { - $feedId = (int) $this->params('feedId'); - $guidHash = $this->params('guidHash'); + private function setStarred($isStarred, $feedId, $guidHash) { try { $this->itemBusinessLayer->star($feedId, $guidHash, $isStarred, $this->userId); - return new JSONResponse(); } catch(BusinessLayerException $ex){ - return new JSONResponse(array('message' => $ex->getMessage()), - Http::STATUS_NOT_FOUND); + return $this->error($ex, Http::STATUS_NOT_FOUND); } } @@ -133,59 +122,66 @@ class ItemApiController extends Controller { /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int $itemId */ - public function read() { - return $this->setRead(true); + public function read($itemId) { + return $this->setRead(true, $itemId); } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int $itemId */ - public function unread() { - return $this->setRead(false); + public function unread($itemId) { + return $this->setRead(false, $itemId); } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int $feedId + * @param string $guidHash */ - public function star() { - return $this->setStarred(true); + public function star($feedId, $guidHash) { + return $this->setStarred(true, $feedId, $guidHash); } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int $feedId + * @param string $guidHash */ - public function unstar() { - return $this->setStarred(false); + public function unstar($feedId, $guidHash) { + return $this->setStarred(false, $feedId, $guidHash); } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int $newestItemId */ - public function readAll() { - $newestItemId = (int) $this->params('newestItemId'); - + public function readAll($newestItemId) { $this->itemBusinessLayer->readAll($newestItemId, $this->userId); - return new JSONResponse(); } - private function setMultipleRead($isRead) { - $items = $this->params('items'); - + private function setMultipleRead($isRead, $items) { foreach($items as $id) { try { $this->itemBusinessLayer->read($id, $isRead, $this->userId); @@ -193,34 +189,34 @@ class ItemApiController extends Controller { continue; } } - - return new JSONResponse(); } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int[] item ids */ - public function readMultiple() { - return $this->setMultipleRead(true); + public function readMultiple($items) { + return $this->setMultipleRead(true, $items); } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int[] item ids */ - public function unreadMultiple() { - return $this->setMultipleRead(false); + public function unreadMultiple($items) { + return $this->setMultipleRead(false, $items); } - private function setMultipleStarred($isStarred) { - $items = $this->params('items'); - + private function setMultipleStarred($isStarred, $items) { foreach($items as $item) { try { $this->itemBusinessLayer->star($item['feedId'], @@ -229,28 +225,30 @@ class ItemApiController extends Controller { continue; } } - - return new JSONResponse(); } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int[] item ids */ - public function starMultiple() { - return $this->setMultipleStarred(true); + public function starMultiple($items) { + return $this->setMultipleStarred(true, $items); } /** * @NoAdminRequired * @NoCSRFRequired - * @API + * @CORS + * + * @param int[] item ids */ - public function unstarMultiple() { - return $this->setMultipleStarred(false); + public function unstarMultiple($items) { + return $this->setMultipleStarred(false, $items); } diff --git a/controller/itemcontroller.php b/controller/itemcontroller.php index 99f308be7..b7836fdaa 100644 --- a/controller/itemcontroller.php +++ b/controller/itemcontroller.php @@ -82,7 +82,7 @@ class ItemController extends Controller { // in that case just return an empty array } catch(BusinessLayerException $ex) {} - return new JSONResponse($params); + return $params; } @@ -109,7 +109,7 @@ class ItemController extends Controller { // in that case just return an empty array } catch(BusinessLayerException $ex) {} - return new JSONResponse($params); + return new $params; } @@ -127,7 +127,6 @@ class ItemController extends Controller { public function star(){ try { $this->setStarred(true); - return new JSONResponse(); } catch(BusinessLayerException $ex) { return new JSONResponse(array( 'msg' => $ex->getMessage() @@ -142,7 +141,6 @@ class ItemController extends Controller { public function unstar(){ try { $this->setStarred(false); - return new JSONResponse(); } catch(BusinessLayerException $ex) { return new JSONResponse(array( 'msg' => $ex->getMessage() @@ -164,7 +162,6 @@ class ItemController extends Controller { public function read(){ try { $this->setRead(true); - return new JSONResponse(); } catch(BusinessLayerException $ex) { return new JSONResponse(array( 'msg' => $ex->getMessage() @@ -179,7 +176,6 @@ class ItemController extends Controller { public function unread(){ try { $this->setRead(false); - return new JSONResponse(); } catch(BusinessLayerException $ex) { return new JSONResponse(array( 'msg' => $ex->getMessage() diff --git a/controller/jsonhttperror.php b/controller/jsonhttperror.php new file mode 100644 index 000000000..5948a8a63 --- /dev/null +++ b/controller/jsonhttperror.php @@ -0,0 +1,36 @@ + + * @author Bernhard Posselt + * @copyright Alessandro Cosentino 2012 + * @copyright Bernhard Posselt 2012, 2014 + */ + +namespace OCA\News\Controller; + +use \OCP\AppFramework\Http\JSONResponse; + + +trait JSONHttpError { + + + /** + * @param \Excpetion $exception the message that is returned taken from the + * exception + * @param int the http error code + * @return \OCP\AppFramework\Http\JSONResponse + */ + protected function error($exception, $code) { + return new JSONResponse( + array('message' => $exception->getMessage()), + $code + ); + } + + +} \ No newline at end of file diff --git a/controller/pagecontroller.php b/controller/pagecontroller.php index fe6fe967a..5a9c592f5 100644 --- a/controller/pagecontroller.php +++ b/controller/pagecontroller.php @@ -15,6 +15,7 @@ namespace OCA\News\Controller; use \OCP\IRequest; use \OCP\IConfig; +use \OCP\IL10N; use \OCP\AppFramework\Http\JSONResponse; use \OCP\AppFramework\Controller; @@ -24,8 +25,11 @@ class PageController extends Controller { private $l10n; private $userId; - public function __construct($appName, IRequest $request, IConfig $settings, - $l10n, $userId){ + public function __construct($appName, + IRequest $request, + IConfig $settings, + IL10N $l10n, + $userId){ parent::__construct($appName, $request); $this->settings = $settings; $this->l10n = $l10n; @@ -58,28 +62,25 @@ class PageController extends Controller { 'language' => $language ); - return new JSONResponse($settings); + return $settings; } /** * @NoAdminRequired + * + * */ - public function updateSettings() { - $isShowAll = $this->params('showAll', null); - $isCompact = $this->params('compact', null); - - if($isShowAll !== null) { + public function updateSettings($showAll, $compact) { + if($showAll !== null) { $this->settings->setUserValue($this->userId, $this->appName, - 'showAll', $isShowAll); + 'showAll', $showAll); } - if($isCompact !== null) { + if($compact !== null) { $this->settings->setUserValue($this->userId, $this->appName, - 'compact', $isCompact); + 'compact', $compact); } - - return new JSONResponse(); } } \ No newline at end of file diff --git a/controller/utilityapicontroller.php b/controller/utilityapicontroller.php new file mode 100644 index 000000000..cb36b97b9 --- /dev/null +++ b/controller/utilityapicontroller.php @@ -0,0 +1,68 @@ + + * @author Bernhard Posselt + * @copyright Alessandro Cosentino 2012 + * @copyright Bernhard Posselt 2012, 2014 + */ + +namespace OCA\News\Controller; + +use \OCP\IRequest; +use \OCP\IConfig; +use \OCP\AppFramework\ApiController; +use \OCP\AppFramework\Http; +use \OCP\AppFramework\Http\JSONResponse; +use \OCP\AppFramework\Http\Response; + +use \OCA\News\Utility\Updater; + +class UtilityApiController extends ApiController { + + private $updater; + private $settings; + + public function __construct($appName, + IRequest $request, + Updater $updater, + IConfig $settings){ + parent::__construct($appName, $request); + $this->updater = $updater; + $this->settings = $settings; + } + + + /** + * @NoAdminRequired + * @NoCSRFRequired + * @API + */ + public function version() { + $version = $this->settings->getAppValue($this->appName, + 'installed_version'); + return array('version' => $version); + } + + + /** + * @NoCSRFRequired + */ + public function beforeUpdate() { + $this->updater->beforeUpdate(); + } + + + /** + * @NoCSRFRequired + */ + public function afterUpdate() { + $this->updater->afterUpdate(); + } + + +} diff --git a/core/db.php b/core/db.php deleted file mode 100644 index beda5240c..000000000 --- a/core/db.php +++ /dev/null @@ -1,41 +0,0 @@ - - * @author Bernhard Posselt - * @copyright Alessandro Cosentino 2012 - * @copyright Bernhard Posselt 2012, 2014 - */ - -namespace OCA\News\Core; - -class Db { - - - /** - * Used to abstract the owncloud database access away - * @param string $sql the sql query with ? placeholder for params - * @param int $limit the maximum number of rows - * @param int $offset from which row we want to start - * @return \OCP\DB a query object - */ - public function prepareQuery($sql, $limit=null, $offset=null){ - return \OCP\DB::prepare($sql, $limit, $offset); - } - - - /** - * Used to get the id of the just inserted element - * @param string $tableName the name of the table where we inserted the item - * @return int the id of the inserted element - */ - public function getInsertId($tableName){ - return \OCP\DB::insertid($tableName); - } - - -} diff --git a/core/logger.php b/core/logger.php deleted file mode 100644 index 3ad6ff23a..000000000 --- a/core/logger.php +++ /dev/null @@ -1,52 +0,0 @@ - - * @author Bernhard Posselt - * @copyright Alessandro Cosentino 2012 - * @copyright Bernhard Posselt 2012, 2014 - */ - -namespace OCA\News\Core; - -class Logger { - - protected $appName; - - public function __construct($appName) { - $this->appName = $appName; - } - - - /** - * Writes a function into the error log - * @param string $msg the error message to be logged - * @param int $level the error level - */ - public function log($msg, $level=null){ - switch($level){ - case 'debug': - $level = \OCP\Util::DEBUG; - break; - case 'info': - $level = \OCP\Util::INFO; - break; - case 'warn': - $level = \OCP\Util::WARN; - break; - case 'fatal': - $level = \OCP\Util::FATAL; - break; - default: - $level = \OCP\Util::ERROR; - break; - } - \OCP\Util::writeLog($this->appName, $msg, $level); - } - - -} diff --git a/db/doesnotexistexception.php b/db/doesnotexistexception.php deleted file mode 100644 index ef2e9dd7d..000000000 --- a/db/doesnotexistexception.php +++ /dev/null @@ -1,31 +0,0 @@ - - * @author Bernhard Posselt - * @copyright Alessandro Cosentino 2012 - * @copyright Bernhard Posselt 2012, 2014 - */ - -namespace OCA\News\Db; - - -/** - * This is returned or should be returned when a find request does not find an - * entry in the database - */ -class DoesNotExistException extends \Exception { - - /** - * Constructor - * @param string $msg the error message - */ - public function __construct($msg){ - parent::__construct($msg); - } - -} \ No newline at end of file diff --git a/db/entity.php b/db/entity.php deleted file mode 100644 index 194895fee..000000000 --- a/db/entity.php +++ /dev/null @@ -1,222 +0,0 @@ - - * @author Bernhard Posselt - * @copyright Alessandro Cosentino 2012 - * @copyright Bernhard Posselt 2012, 2014 - */ - -namespace OCA\News\Db; - -/** - * @method integer getId() - * @method void setId(integer $value) - */ -abstract class Entity { - - public $id; - - private $_updatedFields = array(); - private $_fieldTypes = array('id' => 'integer'); - - - /** - * Simple alternative constructor for building entities from a request - * @param array $params the array which was obtained via $this->params('key') - * in the controller - * @return Entity - */ - public static function fromParams(array $params) { - $instance = new static(); - - foreach($params as $key => $value) { - $method = 'set' . ucfirst($key); - $instance->$method($value); - } - - return $instance; - } - - - /** - * Maps the keys of the row array to the attributes - * @param array $row the row to map onto the entity - */ - public static function fromRow(array $row){ - $instance = new static(); - - foreach($row as $key => $value){ - $prop = ucfirst($instance->columnToProperty($key)); - $setter = 'set' . $prop; - $instance->$setter($value); - } - - $instance->resetUpdatedFields(); - - return $instance; - } - - - /** - * @return an array with attribute and type - */ - public function getFieldTypes() { - return $this->_fieldTypes; - } - - - /** - * Marks the entity as clean needed for setting the id after the insertion - */ - public function resetUpdatedFields(){ - $this->_updatedFields = array(); - } - - - protected function setter($name, $args) { - // setters should only work for existing attributes - if(property_exists($this, $name)){ - $this->markFieldUpdated($name); - - // if type definition exists, cast to correct type - if($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) { - settype($args[0], $this->_fieldTypes[$name]); - } - $this->$name = $args[0]; - - } else { - throw new \BadFunctionCallException($name . - ' is not a valid attribute'); - } - } - - - protected function getter($name) { - // getters should only work for existing attributes - if(property_exists($this, $name)){ - return $this->$name; - } else { - throw new \BadFunctionCallException($name . - ' is not a valid attribute'); - } - } - - - /** - * Each time a setter is called, push the part after set - * into an array: for instance setId will save Id in the - * updated fields array so it can be easily used to create the - * getter method - */ - public function __call($methodName, $args){ - $attr = lcfirst( substr($methodName, 3) ); - - if(strpos($methodName, 'set') === 0){ - $this->setter($attr, $args); - } elseif(strpos($methodName, 'get') === 0) { - return $this->getter($attr); - } else { - throw new \BadFunctionCallException($methodName . - ' does not exist'); - } - - } - - - /** - * Mark am attribute as updated - * @param string $attribute the name of the attribute - */ - protected function markFieldUpdated($attribute){ - $this->_updatedFields[$attribute] = true; - } - - - /** - * Transform a database columnname to a property - * @param string $columnName the name of the column - * @return string the property name - */ - public function columnToProperty($columnName){ - $parts = explode('_', $columnName); - $property = null; - - foreach($parts as $part){ - if($property === null){ - $property = $part; - } else { - $property .= ucfirst($part); - } - } - - return $property; - } - - - /** - * Transform a property to a database column name - * @param string $property the name of the property - * @return string the column name - */ - public function propertyToColumn($property){ - $parts = preg_split('/(?=[A-Z])/', $property); - $column = null; - - foreach($parts as $part){ - if($column === null){ - $column = $part; - } else { - $column .= '_' . lcfirst($part); - } - } - - return $column; - } - - - /** - * @return array array of updated fields for update query - */ - public function getUpdatedFields(){ - return $this->_updatedFields; - } - - - /** - * Adds type information for a field so that its automatically casted to - * that value once its being returned from the database - * @param string $fieldName the name of the attribute - * @param string $type the type which will be used to call settype() - */ - protected function addType($fieldName, $type){ - $this->_fieldTypes[$fieldName] = $type; - } - - - /** - * Slugify the value of a given attribute - * Warning: This doesn't result in a unique value - * @param string $attributeName the name of the attribute, which value should be slugified - * @return string slugified value - */ - public function slugify($attributeName){ - // toSlug should only work for existing attributes - if(property_exists($this, $attributeName)){ - $value = $this->$attributeName; - // replace everything except alphanumeric with a single '-' - $value = preg_replace('/[^A-Za-z0-9]+/', '-', $value); - $value = strtolower($value); - // trim '-' - return trim($value, '-'); - } else { - throw new \BadFunctionCallException($attributeName . - ' is not a valid attribute'); - } - } - -} diff --git a/db/feed.php b/db/feed.php index 280b7362f..1e47a89cf 100644 --- a/db/feed.php +++ b/db/feed.php @@ -13,6 +13,8 @@ namespace OCA\News\Db; +use \OCP\AppFramework\Db\Entity; + /** * @method integer getId() * @method void setId(integer $value) diff --git a/db/feedmapper.php b/db/feedmapper.php index a69f1fa89..6ac21ddac 100644 --- a/db/feedmapper.php +++ b/db/feedmapper.php @@ -13,13 +13,14 @@ namespace OCA\News\Db; -use \OCA\News\Core\Db; +use \OCP\IDb; +use \OCP\AppFramework\Db\Mapper; class FeedMapper extends Mapper implements IMapper { - public function __construct(Db $db) { + public function __construct(IDb $db) { parent::__construct($db, 'news_feeds', '\OCA\News\Db\Feed'); } diff --git a/db/folder.php b/db/folder.php index f8fb3df58..851fae6d8 100644 --- a/db/folder.php +++ b/db/folder.php @@ -13,6 +13,8 @@ namespace OCA\News\Db; +use \OCP\AppFramework\Db\Entity; + /** * @method integer getId() * @method void setId(integer $value) diff --git a/db/foldermapper.php b/db/foldermapper.php index 017ccd0db..6df2d21d6 100644 --- a/db/foldermapper.php +++ b/db/foldermapper.php @@ -13,12 +13,13 @@ namespace OCA\News\Db; -use \OCA\News\Core\Db; +use \OCP\IDb; +use \OCP\AppFramework\Db\Mapper; class FolderMapper extends Mapper implements IMapper { - public function __construct(Db $db) { + public function __construct(IDb $db) { parent::__construct($db, 'news_folders', '\OCA\News\Db\Folder'); } diff --git a/db/item.php b/db/item.php index 7d3d4dce7..4a3fa0d8c 100644 --- a/db/item.php +++ b/db/item.php @@ -13,6 +13,9 @@ namespace OCA\News\Db; +use \OCP\AppFramework\Db\Entity; + + /** * @method integer getId() * @method void setId(integer $value) diff --git a/db/itemmapper.php b/db/itemmapper.php index b223a8aaf..0ce4eb665 100644 --- a/db/itemmapper.php +++ b/db/itemmapper.php @@ -13,11 +13,13 @@ namespace OCA\News\Db; -use \OCA\News\Core\Db; +use \OCP\IDb; +use \OCP\AppFramework\Db\Mapper; + class ItemMapper extends Mapper implements IMapper { - public function __construct(Db $db){ + public function __construct(IDb $db){ parent::__construct($db, 'news_items', '\OCA\News\Db\Item'); } diff --git a/db/mapper.php b/db/mapper.php deleted file mode 100644 index e61be0a6c..000000000 --- a/db/mapper.php +++ /dev/null @@ -1,273 +0,0 @@ - - * @author Bernhard Posselt - * @copyright Alessandro Cosentino 2012 - * @copyright Bernhard Posselt 2012, 2014 - */ - -namespace OCA\News\Db; - -use \OCA\News\Core\Db; - - -/** - * Simple parent class for inheriting your data access layer from. This class - * may be subject to change in the future - */ -abstract class Mapper { - - protected $tableName; - protected $entityClass; - private $db; - - /** - * @param Db $db Instance of the Db abstraction layer - * @param string $tableName the name of the table. set this to allow entity - * @param string $entityClass the name of the entity that the sql should be - * mapped to queries without using sql - */ - public function __construct(Db $db, $tableName, $entityClass=null){ - $this->db = $db; - $this->tableName = '*PREFIX*' . $tableName; - - // if not given set the entity name to the class without the mapper part - // cache it here for later use since reflection is slow - if($entityClass === null) { - $this->entityClass = str_replace('Mapper', '', get_class($this)); - } else { - $this->entityClass = $entityClass; - } - } - - - /** - * @return string the table name - */ - public function getTableName(){ - return $this->tableName; - } - - - /** - * Deletes an entity from the table - * @param Entity $entity the entity that should be deleted - */ - public function delete(Entity $entity){ - $sql = 'DELETE FROM `' . $this->tableName . '` WHERE `id` = ?'; - $this->execute($sql, array($entity->getId())); - } - - - /** - * Creates a new entry in the db from an entity - * @param Entity $enttiy the entity that should be created - * @return the saved entity with the set id - */ - public function insert(Entity $entity){ - // get updated fields to save, fields have to be set using a setter to - // be saved - $properties = $entity->getUpdatedFields(); - $values = ''; - $columns = ''; - $params = array(); - - // build the fields - $i = 0; - foreach($properties as $property => $updated) { - $column = $entity->propertyToColumn($property); - $getter = 'get' . ucfirst($property); - - $columns .= '`' . $column . '`'; - $values .= '?'; - - // only append colon if there are more entries - if($i < count($properties)-1){ - $columns .= ','; - $values .= ','; - } - - array_push($params, $entity->$getter()); - $i++; - - } - - $sql = 'INSERT INTO `' . $this->tableName . '`(' . - $columns . ') VALUES(' . $values . ')'; - - $this->execute($sql, $params); - - $entity->setId((int) $this->db->getInsertId($this->tableName)); - return $entity; - } - - - - /** - * Updates an entry in the db from an entity - * @throws \InvalidArgumentException if entity has no id - * @param Entity $enttiy the entity that should be created - */ - public function update(Entity $entity){ - // entity needs an id - $id = $entity->getId(); - if($id === null){ - throw new \InvalidArgumentException( - 'Entity which should be updated has no id'); - } - - // get updated fields to save, fields have to be set using a setter to - // be saved - $properties = $entity->getUpdatedFields(); - // dont update the id field - unset($properties['id']); - - $columns = ''; - $params = array(); - - // build the fields - $i = 0; - foreach($properties as $property => $updated) { - - $column = $entity->propertyToColumn($property); - $getter = 'get' . ucfirst($property); - - $columns .= '`' . $column . '` = ?'; - - // only append colon if there are more entries - if($i < count($properties)-1){ - $columns .= ','; - } - - array_push($params, $entity->$getter()); - $i++; - } - - $sql = 'UPDATE `' . $this->tableName . '` SET ' . - $columns . ' WHERE `id` = ?'; - array_push($params, $id); - - $this->execute($sql, $params); - } - - - /** - * Runs an sql query - * @param string $sql the prepare string - * @param array $params the params which should replace the ? in the sql query - * @param int $limit the maximum number of rows - * @param int $offset from which row we want to start - * @return \PDOStatement the database query result - */ - protected function execute($sql, array $params=array(), $limit=null, $offset=null){ - $query = $this->db->prepareQuery($sql, $limit, $offset); - - $index = 1; // bindParam is 1 indexed - foreach($params as $param) { - - switch (gettype($param)) { - case 'integer': - $pdoConstant = \PDO::PARAM_INT; - break; - - case 'boolean': - $pdoConstant = \PDO::PARAM_BOOL; - break; - - default: - $pdoConstant = \PDO::PARAM_STR; - break; - } - - $query->bindValue($index, $param, $pdoConstant); - - $index++; - } - - return $query->execute(); - } - - - /** - * Returns an db result and throws exceptions when there are more or less - * results - * @see findEntity - * @param string $sql the sql query - * @param array $params the parameters of the sql query - * @param int $limit the maximum number of rows - * @param int $offset from which row we want to start - * @throws DoesNotExistException if the item does not exist - * @throws MultipleObjectsReturnedException if more than one item exist - * @return array the result as row - */ - protected function findOneQuery($sql, array $params=array(), $limit=null, $offset=null){ - $result = $this->execute($sql, $params, $limit, $offset); - $row = $result->fetch(); - - if($row === false || $row === null){ - throw new DoesNotExistException('No matching entry found'); - } - $row2 = $result->fetch(); - //MDB2 returns null, PDO and doctrine false when no row is available - if( ! ($row2 === false || $row2 === null )) { - throw new MultipleObjectsReturnedException('More than one result'); - } else { - return $row; - } - } - - - /** - * Creates an entity from a row. Automatically determines the entity class - * from the current mapper name (MyEntityMapper -> MyEntity) - * @param array $row the row which should be converted to an entity - * @return Entity the entity - */ - protected function mapRowToEntity($row) { - return call_user_func($this->entityClass .'::fromRow', $row); - } - - - /** - * Runs a sql query and returns an array of entities - * @param string $sql the prepare string - * @param array $params the params which should replace the ? in the sql query - * @param int $limit the maximum number of rows - * @param int $offset from which row we want to start - * @return array all fetched entities - */ - protected function findEntities($sql, array $params=array(), $limit=null, $offset=null) { - $result = $this->execute($sql, $params, $limit, $offset); - - $entities = array(); - - while($row = $result->fetch()){ - $entities[] = $this->mapRowToEntity($row); - } - - return $entities; - } - - - /** - * Returns an db result and throws exceptions when there are more or less - * results - * @param string $sql the sql query - * @param array $params the parameters of the sql query - * @param int $limit the maximum number of rows - * @param int $offset from which row we want to start - * @throws DoesNotExistException if the item does not exist - * @throws MultipleObjectsReturnedException if more than one item exist - * @return Entity the entity - */ - protected function findEntity($sql, array $params=array(), $limit=null, $offset=null){ - return $this->mapRowToEntity($this->findOneQuery($sql, $params, $limit, $offset)); - } - - -} diff --git a/db/mapperfactory.php b/db/mapperfactory.php index 7d7c5d7cc..35d52ad72 100644 --- a/db/mapperfactory.php +++ b/db/mapperfactory.php @@ -14,8 +14,7 @@ namespace OCA\News\Db; use \OCP\IConfig; - -use \OCA\News\Core\Db; +use \OCP\IDb; class MapperFactory { @@ -23,7 +22,7 @@ class MapperFactory { private $dbType; private $db; - public function __construct($dbType, Db $db) { + public function __construct($dbType, IDb $db) { $this->dbType = $dbType; $this->db = $db; } diff --git a/db/multipleobjectsreturnedexception.php b/db/multipleobjectsreturnedexception.php deleted file mode 100644 index 922d7a22a..000000000 --- a/db/multipleobjectsreturnedexception.php +++ /dev/null @@ -1,31 +0,0 @@ - - * @author Bernhard Posselt - * @copyright Alessandro Cosentino 2012 - * @copyright Bernhard Posselt 2012, 2014 - */ - -namespace OCA\News\Db; - - -/** - * This is returned or should be returned when a find request finds more than one - * row - */ -class MultipleObjectsReturnedException extends \Exception { - - /** - * Constructor - * @param string $msg the error message - */ - public function __construct($msg){ - parent::__construct($msg); - } - -} \ No newline at end of file diff --git a/db/postgres/itemmapper.php b/db/postgres/itemmapper.php index 86b63f23b..8a305bcb4 100644 --- a/db/postgres/itemmapper.php +++ b/db/postgres/itemmapper.php @@ -13,16 +13,14 @@ namespace OCA\News\Db\Postgres; -use \OCA\News\Core\Db; -use \OCA\News\Db\DoesNotExistException; -use \OCA\News\Db\MultipleObjectsReturnedException; -use \OCA\News\Db\Mapper; +use \OCP\IDb; + use \OCA\News\Db\StatusFlag; class ItemMapper extends \OCA\News\Db\ItemMapper { - public function __construct(Db $db){ + public function __construct(IDb $db){ parent::__construct($db); } diff --git a/middleware/corsmiddleware.php b/middleware/corsmiddleware.php deleted file mode 100644 index e88e3b3cc..000000000 --- a/middleware/corsmiddleware.php +++ /dev/null @@ -1,57 +0,0 @@ - - * @author Bernhard Posselt - * @copyright Alessandro Cosentino 2012 - * @copyright Bernhard Posselt 2012, 2014 - */ - -namespace OCA\News\Middleware; - -use OCP\IRequest; -use OCP\AppFramework\Http\Response; -use OCP\AppFramework\Middleware; - -use OCA\News\Utility\MethodAnnotationReader; - -class CORSMiddleware extends Middleware { - - private $request; - - public function __construct(IRequest $request) { - $this->request = $request; - } - - - /** - * This is being run after a successful controllermethod call and allows - * the manipulation of a Response object. The middleware is run in reverse order - * - * @param Controller $controller the controller that is being called - * @param string $methodName the name of the method that will be called on - * the controller - * @param Response $response the generated response from the controller - * @return Response a Response object - */ - public function afterContro