1
0
mirror of https://github.com/owncloudarchive/contacts.git synced 2025-01-18 07:52:21 +01:00

Contacts: Step 2 in porting to app framework.

This commit is contained in:
Thomas Tanghus 2013-04-19 09:59:30 +02:00
parent c3b49a1007
commit 09413a4fca
10 changed files with 461 additions and 153 deletions

View File

@ -3,7 +3,7 @@
namespace OCA\Contacts;
use \OCA\AppFramework\Core\API;
//require_once __DIR__ . '/../lib/contact.php';
//require_once __DIR__ . '/../controller/groupcontroller.php';
\Sabre\VObject\Component::$classMap['VCARD'] = '\OCA\Contacts\Contact';
\Sabre\VObject\Property::$classMap['FN'] = '\OC\VObject\StringProperty';
\Sabre\VObject\Property::$classMap['TITLE'] = '\OC\VObject\StringProperty';
@ -43,9 +43,9 @@ if(\OCP\App::isEnabled('appframework')) {
}
\OCP\Util::addscript('contacts', 'loader');
\OC_Search::registerProvider('\OCA\Contacts\SearchProvider');
\OCP\Share::registerBackend('contact', '\OCA\Contacts\Share_Backend_Contact');
//OCP\Share::registerBackend('addressbook', 'OCA\Contacts\Share_Backend_Addressbook', 'contact');
\OC_Search::registerProvider('OCA\Contacts\SearchProvider');
//\OCP\Share::registerBackend('contact', 'OCA\Contacts\Share_Backend_Contact');
\OCP\Share::registerBackend('addressbook', 'OCA\Contacts\Share_Backend_Addressbook', 'contact');
/*
if(OCP\User::isLoggedIn()) {

View File

@ -9,6 +9,7 @@ OC::$CLASSPATH['OCA\Contacts\PIMObjectAbstract'] = 'contacts/lib/abstractpimobje
OC::$CLASSPATH['OCA\Contacts\VCard'] = 'contacts/lib/vcard.php';
OC::$CLASSPATH['OCA\Contacts\Hooks'] = 'contacts/lib/hooks.php';
OC::$CLASSPATH['OCA\Contacts\Request'] = 'contacts/lib/request.php';
OC::$CLASSPATH['OCA\Contacts\JSONResponse'] = 'contacts/lib/jsonresponse.php';
OC::$CLASSPATH['OCA\Contacts\Utils\JSONSerializer'] = 'contacts/lib/utils/jsonserializer.php';
OC::$CLASSPATH['OCA\Contacts\Utils\Properties'] = 'contacts/lib/utils/properties.php';
OC::$CLASSPATH['OCA\Contacts\Backend\AbstractBackend'] = 'contacts/lib/backend/abstractbackend.php';

View File

@ -39,17 +39,6 @@ $this->create('contacts_address_books_for_user', 'addressbooks/{user}/')
function($params) {
session_write_close();
Main::main('AddressBookController', 'userAddressBooks', $params, new DIContainer());
/*$app = new App($params['user']);
$addressBooks = $app->getAddressBooksForUser();
$response = array();
foreach($addressBooks as $addressBook) {
$response[] = $addressBook->getMetaData();
}
\OCP\JSON::success(array(
'data' => array(
'addressbooks' => $response,
)
));*/
}
)
->requirements(array('user'))
@ -60,28 +49,7 @@ $this->create('contacts_address_book_collection', 'addressbook/{user}/{backend}/
->action(
function($params) {
session_write_close();
$app = new App($params['user']);
$addressBook = $app->getAddressBook($params['backend'], $params['addressbookid']);
$lastModified = $addressBook->lastModified();
if(!is_null($lastModified)) {
\OCP\Response::enableCaching();
\OCP\Response::setLastModifiedHeader($lastModified);
\OCP\Response::setETagHeader(md5($lastModified));
}
$contacts = array();
foreach($addressBook->getChildren() as $contact) {
//$contact->retrieve();
//error_log(__METHOD__.' jsondata: '.print_r($contact, true));
$response = Utils\JSONSerializer::serializeContact($contact);
if($response !== null) {
$contacts[] = $response;
}
}
\OCP\JSON::success(array(
'data' => array(
'contacts' => $contacts,
)
));
Main::main('AddressBookController', 'getAddressBook', $params, new DIContainer());
}
)
->requirements(array('user', 'backend', 'addressbookid'))
@ -92,15 +60,7 @@ $this->create('contacts_address_book_add', 'addressbook/{user}/{backend}/add')
->action(
function($params) {
session_write_close();
$app = new App($params['user']);
$backend = App::getBackend('local', $params['user']);
$id = $backend->createAddressBook($_POST);
if($id === false) {
bailOut(App::$l10n->t('Error creating address book'));
}
\OCP\JSON::success(array(
'data' => $backend->getAddressBook($id)
));
Main::main('AddressBookController', 'addAddressBook', $params, new DIContainer());
}
)
->requirements(array('user', 'backend', 'addressbookid'))
@ -111,12 +71,7 @@ $this->create('contacts_address_book_delete', 'addressbook/{user}/{backend}/{add
->action(
function($params) {
session_write_close();
$app = new App($params['user']);
$backend = App::getBackend('local', $params['user']);
if(!$backend->deleteAddressBook($params['addressbookid'])) {
bailOut(App::$l10n->t('Error deleting address book'));
}
\OCP\JSON::success();
Main::main('AddressBookController', 'deleteAddressBook', $params, new DIContainer());
}
)
->requirements(array('user', 'backend', 'addressbookid'))
@ -352,31 +307,7 @@ $this->create('contacts_categories_list', 'groups/{user}/')
->action(
function($params) {
session_write_close();
$catmgr = new \OC_VCategories('contact', $params['user']);
$categories = $catmgr->categories(\OC_VCategories::FORMAT_MAP);
foreach($categories as &$category) {
$ids = $catmgr->idsForCategory($category['name']);
$category['contacts'] = $ids;
}
$favorites = $catmgr->getFavorites();
\OCP\JSON::success(array(
'data' => array(
'categories' => $categories,
'favorites' => $favorites,
'shared' => \OCP\Share::getItemsSharedWith('addressbook', Share_Backend_Addressbook::FORMAT_ADDRESSBOOKS),
'lastgroup' => \OCP\Config::getUserValue(
$params['user'],
'contacts',
'lastgroup', 'all'),
'sortorder' => \OCP\Config::getUserValue(
$params['user'],
'contacts',
'groupsort', ''),
)
)
);
Main::main('GroupController', 'getGroups', $params, new DIContainer());
}
)
->requirements(array('user'))
@ -387,21 +318,7 @@ $this->create('contacts_categories_add', 'groups/{user}/add')
->action(
function($params) {
session_write_close();
$request = Request::getRequest($params);
$name = $request->post['name'];
if(is_null($name) || $name === "") {
bailOut(App::$l10n->t('No group name given.'));
}
$catman = new \OC_VCategories('contact', $params['user']);
$id = $catman->add($name);
if($id !== false) {
\OCP\JSON::success(array('data' => array('id'=>$id, 'name' => $name)));
} else {
bailOut(App::$l10n->t('Error adding group.'));
}
Main::main('GroupController', 'addGroup', $params, new DIContainer());
}
)
->requirements(array('user'))
@ -412,17 +329,7 @@ $this->create('contacts_categories_delete', 'groups/{user}/delete')
->action(
function($params) {
session_write_close();
$request = Request::getRequest($params);
$name = $request->post['name'];
if(is_null($name) || $name === "") {
bailOut(App::$l10n->t('No group name given.'));
}
$catman = new \OC_VCategories('contact', $params['user']);
$catman->delete($name);
\OCP\JSON::success();
Main::main('GroupController', 'deleteGroup', $params, new DIContainer());
}
)
->requirements(array('user'))
@ -433,26 +340,7 @@ $this->create('contacts_categories_addto', 'groups/{user}/addto/{categoryid}')
->action(
function($params) {
session_write_close();
$request = Request::getRequest($params);
$categoryid = $request['categoryid'];
$ids = $request['contactids'];
debug('request: '.print_r($request->post, true));
if(is_null($categoryid) || $categoryid === '') {
bailOut(App::$l10n->t('Group ID missing from request.'));
}
if(is_null($ids)) {
bailOut(App::$l10n->t('Contact ID missing from request.'));
}
$catman = new \OC_VCategories('contact', $params['user']);
foreach($ids as $contactid) {
debug('contactid: ' . $contactid . ', categoryid: ' . $categoryid);
$catman->addToCategory($contactid, $categoryid);
}
\OCP\JSON::success();
Main::main('GroupController', 'addToGroup', $params, new DIContainer());
}
)
->requirements(array('user', 'categoryid'))
@ -463,26 +351,7 @@ $this->create('contacts_categories_removefrom', 'groups/{user}/removefrom/{categ
->action(
function($params) {
session_write_close();
$request = Request::getRequest($params);
$categoryid = $request['categoryid'];
$ids = $request['contactids'];
debug('request: '.print_r($request->post, true));
if(is_null($categoryid) || $categoryid === '') {
bailOut(App::$l10n->t('Group ID missing from request.'));
}
if(is_null($ids)) {
bailOut(App::$l10n->t('Contact ID missing from request.'));
}
$catman = new \OC_VCategories('contact', $params['user']);
foreach($ids as $contactid) {
debug('contactid: ' . $contactid . ', categoryid: ' . $categoryid);
$catman->removeFromCategory($contactid, $categoryid);
}
\OCP\JSON::success();
Main::main('GroupController', 'removeFromGroup', $params, new DIContainer());
}
)
->requirements(array('user', 'categoryid'))

View File

@ -9,7 +9,10 @@
namespace OCA\Contacts\Controller;
use OCA\Contacts\Request;
use OCA\Contacts\App;
use OCA\Contacts\JSONResponse;
use OCA\Contacts\Utils\JSONSerializer;
//use OCA\Contacts\Request;
//use OCA\AppFramework\Http\Request;
use OCA\AppFramework\Core\API;
@ -25,16 +28,88 @@ class AddressBookController extends BaseController {
* @Ajax
*/
public function userAddressBooks() {
$app = new App($params['user']);
$app = new App($this->request->urlParams['user']);
$addressBooks = $app->getAddressBooksForUser();
$response = array();
foreach($addressBooks as $addressBook) {
$response[] = $addressBook->getMetaData();
}
\OCP\JSON::success(array(
'data' => array(
$response = new JSONResponse(array(
'addressbooks' => $response,
)
));
));
return $response;
}
/**
* @IsAdminExemption
* @IsSubAdminExemption
* @Ajax
*/
public function getAddressBook() {
$params = $this->request->urlParams;
$app = new App($params['user']);
$addressBook = $app->getAddressBook($params['backend'], $params['addressbookid']);
$lastModified = $addressBook->lastModified();
$response = new JSONResponse();
if(!is_null($lastModified)) {
$response->enableCaching();
$response->setLastModifiedHeader($lastModified);
$response->setETagHeader(md5($lastModified));
}
$contacts = array();
foreach($addressBook->getChildren() as $i => $contact) {
$result = JSONSerializer::serializeContact($contact);
if($result !== null) {
$contacts[] = $result;
}
}
$response->setParams(array(
'contacts' => $contacts,
));
return $response;
}
/**
* @IsAdminExemption
* @IsSubAdminExemption
* @Ajax
*/
public function addAddressBook() {
$params = $this->request->urlParams;
$app = new App($params['user']);
$response = new JSONResponse();
$backend = App::getBackend('local', $params['user']);
$id = $backend->createAddressBook($this->request->post);
if($id === false) {
$response->bailOut(App::$l10n->t('Error creating address book'));
return $response;
}
$response->setParams($backend->getAddressBook($id));
return $response;
}
/**
* @IsAdminExemption
* @IsSubAdminExemption
* @Ajax
*/
public function deleteAddressBook() {
$params = $this->request->urlParams;
$app = new App($params['user']);
$response = new JSONResponse();
$backend = App::getBackend('local', $params['user']);
if(!$backend->deleteAddressBook($params['addressbookid'])) {
$response->bailOut(App::$l10n->t('Error deleting address book'));
}
return $response;
}
}

View File

@ -0,0 +1,156 @@
<?php
/**
* @author Thomas Tanghus
* Copyright (c) 2013 Thomas Tanghus (thomas@tanghus.net)
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OCA\Contacts\Controller;
use OCA\Contacts\App;
use OCA\Contacts\JSONResponse;
use OCA\Contacts\Utils\JSONSerializer;
//use OCA\AppFramework\Http\Request;
use OCA\AppFramework\Core\API;
/**
* Controller for groups/categories
*/
class GroupController extends BaseController {
/**
* @IsAdminExemption
* @IsSubAdminExemption
* @Ajax
*/
public function getGroups() {
$params = $this->request->urlParams;
$app = new App($params['user']);
$catmgr = new \OC_VCategories('contact', $params['user']);
$categories = $catmgr->categories(\OC_VCategories::FORMAT_MAP);
foreach($categories as &$category) {
$ids = $catmgr->idsForCategory($category['name']);
$category['contacts'] = $ids;
}
$favorites = $catmgr->getFavorites();
$groups = array(
'categories' => $categories,
'favorites' => $favorites,
'shared' => \OCP\Share::getItemsSharedWith('addressbook', \OCA\Contacts\Share_Backend_Addressbook::FORMAT_ADDRESSBOOKS),
'lastgroup' => \OCP\Config::getUserValue($params['user'], 'contacts', 'lastgroup', 'all'),
'sortorder' => \OCP\Config::getUserValue($params['user'], 'contacts', 'groupsort', ''),
);
return new JSONResponse($groups);
}
/**
* @IsAdminExemption
* @IsSubAdminExemption
* @Ajax
*/
public function addGroup() {
$params = $this->request->urlParams;
$name = $this->request->post['name'];
$response = new JSONResponse();
if(is_null($name) || $name === "") {
$response->bailOut(App::$l10n->t('No group name given.'));
}
$catman = new \OC_VCategories('contact', $params['user']);
$id = $catman->add($name);
if($id === false) {
$response->bailOut(App::$l10n->t('Error adding group.'));
} else {
$response->setParams(array('id'=>$id, 'name' => $name));
}
return $response;
}
/**
* @IsAdminExemption
* @IsSubAdminExemption
* @Ajax
*/
public function deleteGroup() {
$params = $this->request->urlParams;
$name = $this->request->post['name'];
$response = new JSONResponse();
if(is_null($name) || $name === "") {
$response->bailOut(App::$l10n->t('No group name given.'));
}
$catman = new \OC_VCategories('contact', $params['user']);
$catman->delete($name);
return $response;
}
/**
* @IsAdminExemption
* @IsSubAdminExemption
* @Ajax
*/
public function addToGroup() {
$params = $this->request->urlParams;
$response = new JSONResponse();
$categoryid = $request['categoryid'];
$ids = $request->post['contactids'];
$response->debug('request: '.print_r($request->post, true));
if(is_null($categoryid) || $categoryid === '') {
$response->bailOut(App::$l10n->t('Group ID missing from request.'));
}
if(is_null($ids)) {
$response->bailOut(App::$l10n->t('Contact ID missing from request.'));
}
$catman = new \OC_VCategories('contact', $params['user']);
foreach($ids as $contactid) {
$response->debug('contactid: ' . $contactid . ', categoryid: ' . $categoryid);
$catman->addToCategory($contactid, $categoryid);
}
return $response;
}
/**
* @IsAdminExemption
* @IsSubAdminExemption
* @Ajax
*/
public function removeFromGroup() {
$params = $this->request->urlParams;
$response = new JSONResponse();
$categoryid = $request['categoryid'];
$ids = $request->post['contactids'];
$response->debug('request: '.print_r($request->post, true));
if(is_null($categoryid) || $categoryid === '') {
$response->bailOut(App::$l10n->t('Group ID missing from request.'));
}
if(is_null($ids)) {
$response->bailOut(App::$l10n->t('Contact ID missing from request.'));
}
$catman = new \OC_VCategories('contact', $params['user']);
foreach($ids as $contactid) {
$response->debug('contactid: ' . $contactid . ', categoryid: ' . $categoryid);
$catman->removeFromCategory($contactid, $categoryid);
}
return $response;
}
}

View File

@ -10,6 +10,7 @@
namespace OCA\Contacts;
use OCA\AppFramework\DependencyInjection\DIContainer as BaseContainer;
use OCA\Contacts\Controller\AddressBookController;
use OCA\Contacts\Controller\GroupController;
class DIContainer extends BaseContainer {
@ -27,5 +28,10 @@ class DIContainer extends BaseContainer {
$this['AddressBookController'] = $this->share(function($c){
return new AddressBookController($c['API'], $c['Request']);
});
$this['GroupController'] = $this->share(function($c){
return new GroupController($c['API'], $c['Request']);
});
}
}

View File

@ -153,7 +153,7 @@ class Addressbook extends PIMCollectionAbstract {
* @return Contact[]
*/
function getChildren($limit = null, $offset = null, $omitdata = false) {
//\OCP\Util::writeLog('contacts', __METHOD__.' backend: ' . print_r($this->backend, true), \OCP\Util::DEBUG);
\OCP\Util::writeLog('contacts', __METHOD__.' backend: ' . print_r($this->backend, true), \OCP\Util::DEBUG);
$contacts = array();
foreach($this->backend->getContacts($this->getId(), $limit, $offset, $omitdata) as $contact) {
@ -163,6 +163,7 @@ class Addressbook extends PIMCollectionAbstract {
}
$contacts[] = $this->objects[$contact['id']];
}
\OCP\Util::writeLog('contacts', __METHOD__.' children: '.count($contacts), \OCP\Util::DEBUG);
return $contacts;
}

View File

@ -115,10 +115,12 @@ class App {
* @return AddressBook|null
*/
public function getAddressBook($backendName, $addressbookid) {
\OCP\Util::writeLog('contacts', __METHOD__ . ': '. $backendName . ', ' . $addressbookid, \OCP\Util::DEBUG);
foreach(self::$addressBooks as $addressBook) {
if($addressBook->backend->name === $backendName
&& $addressBook->getId() === $addressbookid
) {
\OCP\Util::writeLog('contacts', __METHOD__ . ' returning: '. print_r($addressBook, true), \OCP\Util::DEBUG);
return $addressBook;
}
}
@ -194,8 +196,7 @@ class App {
foreach($vccontacts as $vccontact) {
$cards[] = array($vccontact['id'], $vccontact['carddata']);
}
\OCP\Util::writeLog('contacts',
__CLASS__.'::'.__METHOD__
\OCP\Util::writeLog('contacts', __METHOD__
.', scanning: '.$batchsize.' starting from '.$start,
\OCP\Util::DEBUG);
// only reset on first batch.

199
lib/jsonresponse.php Normal file
View File

@ -0,0 +1,199 @@
<?php
/**
* @author Thomas Tanghus, Bart Visscher
* Copyright (c) 2013 Thomas Tanghus (thomas@tanghus.net)
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OCA\Contacts;
use OCA\AppFramework\Http\JSONResponse as OriginalResponse;
/**
* A renderer for JSON calls
*/
class JSONResponse extends OriginalResponse {
const STATUS_FOUND = 304;
const STATUS_NOT_MODIFIED = 304;
const STATUS_TEMPORARY_REDIRECT = 307;
const STATUS_NOT_FOUND = 404;
protected $name;
protected $data;
public function __construct($params = array()) {
parent::__construct();
$this->data['data'] = $params;
$this->error = false;
$this->data['status'] = 'success';
}
/**
* in case we want to render an error message, also logs into the owncloud log
* @param string $message the error message
*/
public function setErrorMessage($message){
$this->error = true;
$this->data['data']['message'] = $message;
$this->data['status'] = 'error';
}
/**
* Sets values in the data json array
* @param array $params an array with key => value structure which will be
* transformed to JSON
*/
public function setParams(array $params){
$this->data['data'] = $params;
}
function bailOut($msg, $tracelevel = 1, $debuglevel = \OCP\Util::ERROR) {
$this->setErrorMessage($msg);
$this->debug($msg, $tracelevel, $debuglevel);
}
function debug($msg, $tracelevel = 0, $debuglevel = \OCP\Util::DEBUG) {
if(!is_numeric($tracelevel)) {
return;
}
if(PHP_VERSION >= "5.4") {
$call = debug_backtrace(false, $tracelevel + 1);
} else {
$call = debug_backtrace(false);
}
$call = $call[$tracelevel];
if($debuglevel !== false) {
\OCP\Util::writeLog('contacts',
$call['file'].'. Line: '.$call['line'].': '.$msg,
$debuglevel);
}
}
/**
* Returns the rendered json
* @return string the rendered json
*/
public function render() {
return json_encode($this->data);
}
/**
* @brief Enable response caching by sending correct HTTP headers
* @param $cache_time time to cache the response
* >0 cache time in seconds
* 0 and <0 enable default browser caching
* null cache indefinitly
*/
public function enableCaching($cache_time = null) {
if (is_numeric($cache_time)) {
$this->addHeader('Pragma: public');// enable caching in IE
if ($cache_time > 0) {
$this->setExpiresHeader('PT'.$cache_time.'S');
$this->addHeader('Cache-Control: max-age='.$cache_time.', must-revalidate');
}
else {
$this->setExpiresHeader(0);
$this->addHeader('Cache-Control: must-revalidate, post-check=0, pre-check=0');
}
}
else {
$this->addHeader('Cache-Control: cache');
$this->addHeader('Pragma: cache');
}
}
/**
* @brief Set reponse expire time
* @param $expires date-time when the response expires
* string for DateInterval from now
* DateTime object when to expire response
*/
public function setExpiresHeader($expires) {
if (is_string($expires) && $expires[0] == 'P') {
$interval = $expires;
$expires = new DateTime('now');
$expires->add(new DateInterval($interval));
}
if ($expires instanceof DateTime) {
$expires->setTimezone(new DateTimeZone('GMT'));
$expires = $expires->format(DateTime::RFC2822);
}
$this->addHeader('Expires: ' . $expires);
}
/**
* Checks and set ETag header, when the request matches sends a
* 'not modified' response
* @param $etag token to use for modification check
*/
public function setETagHeader($etag) {
if (empty($etag)) {
return;
}
$etag = '"'.$etag.'"';
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) &&
trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
$this->setStatus(self::STATUS_NOT_MODIFIED);
return;
}
$this->addHeader('ETag: ' . $etag);
}
/**
* Checks and set Last-Modified header, when the request matches sends a
* 'not modified' response
* @param $lastModified time when the reponse was last modified
*/
public function setLastModifiedHeader($lastModified) {
if (empty($lastModified)) {
return;
}
if (is_int($lastModified)) {
$lastModified = gmdate(DateTime::RFC2822, $lastModified);
}
if ($lastModified instanceof DateTime) {
$lastModified = $lastModified->format(DateTime::RFC2822);
}
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
trim($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastModified) {
$this->setStatus(self::STATUS_NOT_MODIFIED);
return;
}
$this->addHeader('Last-Modified: ' . $lastModified);
}
/**
* @brief Set response status
* @param $status a HTTP status code, see also the STATUS constants
*/
public function setStatus($status) {
$protocol = $_SERVER['SERVER_PROTOCOL'];
switch($status) {
case self::STATUS_NOT_MODIFIED:
$status = $status . ' Not Modified';
break;
case self::STATUS_TEMPORARY_REDIRECT:
if ($protocol == 'HTTP/1.1') {
$status = $status . ' Temporary Redirect';
break;
} else {
$status = self::STATUS_FOUND;
// fallthrough
}
case self::STATUS_FOUND;
$status = $status . ' Found';
break;
case self::STATUS_NOT_FOUND;
$status = $status . ' Not Found';
break;
}
$this->addHeader($protocol.' '.$status);
}
}

View File

@ -32,7 +32,7 @@ class Share_Backend_Addressbook implements \OCP\Share_Backend_Collection {
*/
public function isValidSource($itemSource, $uidOwner) {
$addressbook = $this->backend->getAddressBook($itemSource);
if(!$addressbook || $addressbook['userid'] !== $uidOwner) {
if(!$addressbook || $addressbook['owner'] !== $uidOwner) {
return false;
}
return true;