aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--RELEASE-NOTES.md1
-rw-r--r--app/controllers/activityfeed.php189
-rw-r--r--app/controllers/admin/api.php210
-rw-r--r--app/controllers/api/authorizations.php58
-rw-r--r--app/controllers/api/oauth.php113
-rw-r--r--app/controllers/resources/ajax.php243
-rw-r--r--app/routes/Activity.php168
-rw-r--r--app/routes/Blubber.php321
-rw-r--r--app/routes/Clipboard.php193
-rw-r--r--app/routes/Contacts.php302
-rw-r--r--app/routes/Course.php242
-rw-r--r--app/routes/Discovery.php27
-rw-r--r--app/routes/Events.php186
-rw-r--r--app/routes/Feedback.php271
-rw-r--r--app/routes/FileSystem.php684
-rw-r--r--app/routes/Forum.php419
-rw-r--r--app/routes/Messages.php301
-rw-r--r--app/routes/News.php375
-rw-r--r--app/routes/ResourceBooking.php192
-rw-r--r--app/routes/ResourceCategories.php349
-rw-r--r--app/routes/ResourcePermissions.php585
-rw-r--r--app/routes/ResourceProperties.php224
-rw-r--r--app/routes/ResourceRequest.php138
-rw-r--r--app/routes/Resources.php950
-rw-r--r--app/routes/RoomClipboard.php322
-rw-r--r--app/routes/Schedule.php71
-rw-r--r--app/routes/Semester.php115
-rw-r--r--app/routes/Studip.php65
-rw-r--r--app/routes/User.php300
-rw-r--r--app/routes/UserConfig.php99
-rw-r--r--app/routes/Wiki.php148
-rw-r--r--app/views/admin/api/config.php35
-rw-r--r--app/views/admin/api/edit.php136
-rw-r--r--app/views/admin/api/index.php77
-rw-r--r--app/views/admin/api/permissions.php62
-rw-r--r--app/views/api/authorizations/index.php44
-rw-r--r--app/views/api/oauth/authorize.php34
-rw-r--r--app/views/api/oauth/authorized.php0
-rw-r--r--composer.json1
-rw-r--r--composer.lock157
-rw-r--r--db/migrations/1.127_setup_api.php71
-rw-r--r--db/migrations/5.1.34_activate_semester_routes.php6
-rw-r--r--db/migrations/6.0.10_remove_restapi.php63
-rw-r--r--lib/activities/DocumentsProvider.php3
-rw-r--r--lib/activities/ForumProvider.php4
-rw-r--r--lib/activities/MessageProvider.php4
-rw-r--r--lib/activities/NewsProvider.php2
-rw-r--r--lib/activities/ParticipantsProvider.php4
-rw-r--r--lib/activities/ScheduleProvider.php3
-rw-r--r--lib/activities/WikiProvider.php6
-rw-r--r--lib/bootstrap-api.php40
-rw-r--r--lib/classes/restapi/ConsumerPermissions.php212
-rw-r--r--lib/classes/restapi/Response.php148
-rw-r--r--lib/classes/restapi/RouteMap.php1060
-rw-r--r--lib/classes/restapi/Router.php665
-rw-r--r--lib/classes/restapi/RouterException.php31
-rw-r--r--lib/classes/restapi/RouterHalt.php19
-rw-r--r--lib/classes/restapi/UriTemplate.php115
-rw-r--r--lib/classes/restapi/UserPermissions.php144
-rw-r--r--lib/classes/restapi/consumer/Base.php226
-rw-r--r--lib/classes/restapi/consumer/HTTP.php50
-rw-r--r--lib/classes/restapi/consumer/OAuth.php231
-rw-r--r--lib/classes/restapi/consumer/Studip.php36
-rw-r--r--lib/classes/restapi/renderer/DebugRenderer.php57
-rw-r--r--lib/classes/restapi/renderer/DefaultRenderer.php74
-rw-r--r--lib/classes/restapi/renderer/JSONRenderer.php35
-rw-r--r--lib/models/resources/ResourceBooking.php16
-rw-r--r--lib/models/resources/ResourceRequest.php60
-rw-r--r--lib/modules/ActivityFeed.php24
-rw-r--r--lib/navigation/AdminNavigation.php4
-rw-r--r--lib/navigation/ProfileNavigation.php4
-rw-r--r--lib/plugins/core/RESTAPIPlugin.php26
-rw-r--r--public/api.php103
-rw-r--r--resources/assets/javascripts/bootstrap/resources.js67
-rw-r--r--resources/assets/javascripts/init.js3
-rw-r--r--resources/assets/javascripts/lib/activityfeed.js53
-rw-r--r--resources/assets/javascripts/lib/fullcalendar.js9
-rw-r--r--resources/assets/javascripts/lib/resources.js45
-rw-r--r--resources/assets/javascripts/lib/restapi.js12
-rw-r--r--vendor/oauth-php/LICENSE22
-rw-r--r--vendor/oauth-php/README1
-rw-r--r--vendor/oauth-php/example/client/googledocs.php109
-rw-r--r--vendor/oauth-php/example/client/opera.php125
-rw-r--r--vendor/oauth-php/example/client/twolegged.php67
-rw-r--r--vendor/oauth-php/example/client/twoleggedtest.php78
-rw-r--r--vendor/oauth-php/example/client/twoleggedtwitter.php67
-rw-r--r--vendor/oauth-php/example/server/INSTALL53
-rw-r--r--vendor/oauth-php/example/server/core/init.php128
-rw-r--r--vendor/oauth-php/example/server/core/templates/inc/footer.tpl2
-rw-r--r--vendor/oauth-php/example/server/core/templates/inc/header.tpl2
-rw-r--r--vendor/oauth-php/example/server/core/templates/index.tpl13
-rw-r--r--vendor/oauth-php/example/server/core/templates/logon.tpl21
-rw-r--r--vendor/oauth-php/example/server/core/templates/register.tpl41
-rw-r--r--vendor/oauth-php/example/server/www/hello.php65
-rw-r--r--vendor/oauth-php/example/server/www/index.php37
-rw-r--r--vendor/oauth-php/example/server/www/logon.php55
-rw-r--r--vendor/oauth-php/example/server/www/oauth.php77
-rw-r--r--vendor/oauth-php/example/server/www/register.php29
-rw-r--r--vendor/oauth-php/example/server/www/services.xrds.php71
-rw-r--r--vendor/oauth-php/library/OAuthDiscovery.php227
-rw-r--r--vendor/oauth-php/library/OAuthException2.php50
-rw-r--r--vendor/oauth-php/library/OAuthRequest.php854
-rw-r--r--vendor/oauth-php/library/OAuthRequestLogger.php314
-rw-r--r--vendor/oauth-php/library/OAuthRequestSigner.php215
-rw-r--r--vendor/oauth-php/library/OAuthRequestVerifier.php306
-rw-r--r--vendor/oauth-php/library/OAuthRequester.php543
-rw-r--r--vendor/oauth-php/library/OAuthServer.php333
-rw-r--r--vendor/oauth-php/library/OAuthSession.php86
-rw-r--r--vendor/oauth-php/library/OAuthStore.php91
-rw-r--r--vendor/oauth-php/library/body/OAuthBodyContentDisposition.php129
-rw-r--r--vendor/oauth-php/library/body/OAuthBodyMultipartFormdata.php143
-rw-r--r--vendor/oauth-php/library/discovery/xrds_parse.php304
-rw-r--r--vendor/oauth-php/library/discovery/xrds_parse.txt101
-rw-r--r--vendor/oauth-php/library/session/OAuthSessionAbstract.php44
-rw-r--r--vendor/oauth-php/library/session/OAuthSessionSESSION.php63
-rw-r--r--vendor/oauth-php/library/signature_method/OAuthSignatureMethod.php69
-rw-r--r--vendor/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php115
-rw-r--r--vendor/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA256.php81
-rw-r--r--vendor/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php95
-rw-r--r--vendor/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php80
-rw-r--r--vendor/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php139
-rw-r--r--vendor/oauth-php/library/store/OAuthStore2Leg.php118
-rw-r--r--vendor/oauth-php/library/store/OAuthStoreAbstract.php151
-rw-r--r--vendor/oauth-php/library/store/OAuthStoreAnyMeta.php264
-rw-r--r--vendor/oauth-php/library/store/OAuthStoreMySQL.php245
-rw-r--r--vendor/oauth-php/library/store/OAuthStoreMySQLi.php306
-rw-r--r--vendor/oauth-php/library/store/OAuthStoreOracle.php1541
-rw-r--r--vendor/oauth-php/library/store/OAuthStorePDO.php274
-rw-r--r--vendor/oauth-php/library/store/OAuthStorePostgreSQL.php1981
-rw-r--r--vendor/oauth-php/library/store/OAuthStoreSQL.php1843
-rw-r--r--vendor/oauth-php/library/store/OAuthStoreSession.php157
-rw-r--r--vendor/oauth-php/library/store/mysql/install.php32
-rw-r--r--vendor/oauth-php/library/store/mysql/mysql.sql240
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql114
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql9
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc71
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc31
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc55
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc32
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc82
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc28
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc27
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc28
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc35
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc35
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc37
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc33
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc25
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc96
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc41
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc43
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc41
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc25
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc43
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc52
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc35
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc41
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc45
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc47
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc41
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc43
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc75
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc66
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc45
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc28
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc29
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc40
-rw-r--r--vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc139
-rw-r--r--vendor/oauth-php/library/store/oracle/install.php28
-rw-r--r--vendor/oauth-php/library/store/postgresql/pgsql.sql166
-rw-r--r--vendor/oauth-php/test/discovery/xrds-fireeagle.xrds78
-rw-r--r--vendor/oauth-php/test/discovery/xrds-getsatisfaction.xrds73
-rw-r--r--vendor/oauth-php/test/discovery/xrds-magnolia.xrds81
-rw-r--r--vendor/oauth-php/test/oauth_test.php188
174 files changed, 628 insertions, 26382 deletions
diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md
index 0995c63..e445aca 100644
--- a/RELEASE-NOTES.md
+++ b/RELEASE-NOTES.md
@@ -59,6 +59,7 @@
- Die Klasse `AuxLockRules` wurde ausgebaut. ([Issue #4187](https://gitlab.studip.de/studip/studip/-/issues/4187))
- Die Klasse `ProfileModel` wurde gelöscht. Die darin enthaltenen Methoden wurden in den `Profile_Controller` verschoben. ([Issue #4185]https://gitlab.studip.de/studip/studip/-/issues/4185))
- Die Klasse `StudipTransformFormat` wurde ausgebaut ([Issue #4188](https://gitlab.studip.de/studip/studip/-/issues/4188))
+- Die REST-API (`public/api.php`) wurde zu Stud.IP 5.0 deprecated und nun mit Stud.IP 6.0 entfernt. Als Ersatz steht die JSONAPI zur Verfügung. ([Issue #2798](https://gitlab.studip.de/studip/studip/-/issues/2798))
## Security related issues
diff --git a/app/controllers/activityfeed.php b/app/controllers/activityfeed.php
index 8e81912..ee83826 100644
--- a/app/controllers/activityfeed.php
+++ b/app/controllers/activityfeed.php
@@ -92,4 +92,193 @@ class ActivityfeedController extends AuthenticatedController
PageLayout::setTitle(_('Aktivitäten konfigurieren'));
}
+
+ public function load_action(): void
+ {
+ $user = User::findCurrent();
+
+ // failsafe einbauen - falls es keine älteren Aktivitäten mehr im System gibt, Abbruch!
+
+ $oldest_activity = \Studip\Activity\Activity::getOldestActivity();
+ $max_age = $oldest_activity ? $oldest_activity->mkdate : time();
+
+
+ $contexts = [];
+
+ // create system context
+ $system_context = new \Studip\Activity\SystemContext($user);
+ $contexts[] = $system_context;
+
+ $contexts[] = new \Studip\Activity\UserContext($user, $user);
+ $user->contacts->each(function ($another_user) use (&$contexts, $user) {
+ $contexts[] = new \Studip\Activity\UserContext($another_user, $user);
+ });
+
+ if (!in_array($user->perms, ['admin','root'])) {
+ // create courses and institutes context
+ foreach (\Course::findMany($user->course_memberships->pluck('seminar_id')) as $course) {
+ $contexts[] = new \Studip\Activity\CourseContext($course, $user);
+ }
+ foreach (\Institute::findMany($user->institute_memberships->pluck('institut_id')) as $institute) {
+ $contexts[] = new \Studip\Activity\InstituteContext($institute, $user);
+ }
+ }
+
+
+ // add filters
+ $filter = new \Studip\Activity\Filter();
+
+ $start = Request::int('start', strtotime('yesterday'));
+ $end = Request::int('end', time());
+
+
+ $scrollfrom = Request::int('scrollfrom', false);
+ $filtertype = Request::get('filtertype', '');
+
+ $objectType = Request::get('object_type');
+ $filter->setObjectType($objectType);
+
+ $objectId = Request::get('object_id');
+ $filter->setObjectId($objectId);
+
+ $context = Request::get('context_type');
+ $filter->setContext($context);
+
+ $contextId = Request::get('context_id');
+ $filter->setContextId($contextId);
+
+ if (!empty($filtertype)) {
+ $filter->setType(json_decode($filtertype));
+ }
+
+ if ($scrollfrom) {
+ // shorten "watch-window" by one second to prevent duplication of activities
+ $scrollfrom -= 1;
+
+ if ($scrollfrom > $max_age){
+ $end = $scrollfrom;
+ $start = strtotime('yesterday', $end);
+ $data = [];
+
+ $backtrack = 1;
+
+ while (empty($data)) {
+ $filter->setStartDate($start);
+ $filter->setEndDate($end);
+
+ $data = $this->getStreamData($contexts, $filter);
+
+ if ($start < $max_age) {
+ break;
+ }
+
+ // move "watch-window" back one day at a time
+ $end = $start - 1;
+ $start = strtotime("-{$backtrack} days", $start);
+
+ // enforce maximum "watch-window", currently 2 weeks
+ $backtrack = min(14, $backtrack + 1);
+ }
+ } else {
+ $data = false;
+ }
+ } else {
+ $filter->setStartDate($start);
+ $filter->setEndDate($end);
+ $data = $this->getStreamData($contexts, $filter);
+ }
+
+ // set etag for preventing resending the same stuff over and over again
+ $etag = md5(serialize($data));
+ $this->response->add_header('ETag', '"' . $etag . '"');
+ if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $this->etagMatches($etag, $_SERVER['HTTP_IF_NONE_MATCH'])) {
+ $this->set_status(304);
+ $this->render_nothing();
+ return;
+ }
+ if (isset($_SERVER['HTTP_IF_MATCH']) && !$this->etagMatches($etag, $_SERVER['HTTP_IF_MATCH'])) {
+ $this->set_status(412);
+ $this->render_nothing();
+ return;
+ }
+
+ $this->render_json($data);
+ }
+
+ /**
+ * private helper function to get stream data for given contexts and filter
+ *
+ * @param $contexts
+ * @param $filter
+ * @return array
+ */
+
+ private function getStreamData($contexts, $filter): array
+ {
+ $stream = new Studip\Activity\Stream($contexts, $filter);
+ $data = $stream->toArray();
+
+ foreach ($data as $key => $act) {
+ $actor = [
+ 'type' => $act['actor_type'],
+ 'id' => $act['actor_id'],
+ ];
+
+ if ($act['actor_type'] == 'user') {
+ $a_user = \User::findFull($act['actor_id']);
+ $actor['details'] = $this->getMiniUser($a_user ?: new \User());
+ } elseif ($act['actor_type'] === 'anonymous') {
+ $actor['details'] = [
+ 'name' => _('Anonym'),
+ ];
+ }
+
+ unset($data[$key]['actor_type']);
+ unset($data[$key]['actor_id']);
+
+ $data[$key]['actor'] = $actor;
+ }
+
+ return $data;
+ }
+
+ private function getMiniUser(User $user): array
+ {
+ $avatar = \Avatar::getAvatar($user->id);
+
+ return [
+ 'id' => $user->id,
+ 'name' => $this->getNamesOfUser($user),
+ 'avatar_small' => $avatar->getURL(\Avatar::SMALL),
+ 'avatar_medium' => $avatar->getURL(\Avatar::MEDIUM),
+ 'avatar_normal' => $avatar->getURL(\Avatar::NORMAL),
+ 'avatar_original' => $avatar->getURL(\Avatar::NORMAL)
+ ];
+ }
+
+ private function getNamesOfUser(User $user): array
+ {
+ return [
+ 'username' => $user->username,
+ 'formatted' => $user->getFullName(),
+ 'family' => $user->nachname,
+ 'given' => $user->vorname,
+ 'prefix' => $user->title_front,
+ 'suffix' => $user->title_rear,
+ ];
+ }
+
+ // Helper method checking if a ETag value list includes the current ETag.
+ private function etagMatches(string $etag, string $list)
+ {
+ if ($list === '*') {
+ return true;
+ }
+
+ return in_array(
+ $etag,
+ preg_split('/\s*,\s*/', $list)
+ );
+ }
+
}
diff --git a/app/controllers/admin/api.php b/app/controllers/admin/api.php
deleted file mode 100644
index 96adb65..0000000
--- a/app/controllers/admin/api.php
+++ /dev/null
@@ -1,210 +0,0 @@
-<?php
-/**
- *
- **/
-class Admin_ApiController extends AuthenticatedController
-{
- /**
- *
- **/
- public function before_filter(&$action, &$args)
- {
- parent::before_filter($action, $args);
-
- require_once 'lib/bootstrap-api.php';
-
- $GLOBALS['perm']->check('root');
-
- Navigation::activateItem('/admin/config/api');
- PageLayout::setTitle(_('API Verwaltung'));
-
- $this->types = [
- 'website' => _('Website'),
- 'desktop' => _('Herkömmliches Desktopprogramm'),
- 'mobile' => _('Mobile App')
- ];
-
- // Sidebar
- $views = new ViewsWidget();
- $views->addLink(_('Registrierte Applikationen'),
- $this->url_for('admin/api'))
- ->setActive($action === 'index');
- $views->addLink(_('Globale Zugriffseinstellungen'),
- $this->url_for('admin/api/permissions'))
- ->setActive($action == 'permissions');
- $views->addLink(_('Konfiguration'),
- $this->url_for('admin/api/config'))
- ->setActive($action == 'config');
- Sidebar::get()->addWidget($views);
-
- $actions = new ActionsWidget();
- $actions->addLink(_('Neue Applikation registrieren'),
- $this->url_for('admin/api/edit'),
- Icon::create('add', 'clickable'))
- ->asDialog();
- Sidebar::get()->addWidget($actions);
- }
-
- /**
- *
- **/
- public function index_action()
- {
- $this->consumers = RESTAPI\Consumer\Base::findAll();
- $this->routes = RESTAPI\Router::getInstance()->getRoutes(true);
- }
-
- /**
- *
- **/
- public function render_keys($id)
- {
- $consumer = RESTAPI\Consumer\Base::find($id);
-
- return [
- 'Consumer Key = ' . $consumer->auth_key,
- 'Consumer Secret = ' . $consumer->auth_secret,
- ];
- }
-
- /**
- *
- **/
- public function keys_action($id)
- {
- $details = $this->render_keys($id);
-
- if (Request::isXhr()) {
- $this->render_text(implode('<br>', $details));
- } else {
- PageLayout::postMessage(MessageBox::info(_('Die Schlüssel in den Details dieser Meldung sollten vertraulich behandelt werden!'), $details, true));
- $this->redirect('admin/api/#' . $id);
- }
- }
-
- /**
- *
- **/
- public function edit_action($id = null)
- {
- $consumer = $id
- ? RESTAPI\Consumer\Base::find($id)
- : RESTAPI\Consumer\Base::create(Request::option('consumer_type') ?: 'oauth');
-
- if (Request::submitted('store')) {
- $errors = [];
-
- $consumer->active = (bool) Request::int('active');
- $consumer->title = Request::get('title');
- $consumer->contact = Request::get('contact');
- $consumer->email = Request::get('email');
- $consumer->callback = Request::get('callback');
- $consumer->url = Request::get('url');
- $consumer->type = Request::get('type') ?: null;
- $consumer->commercial = Request::int('commercial');
- $consumer->notes = Request::get('notes');
- $consumer->description = Request::get('description');
-
- if (!empty($errors)) {
- $message = MessageBox::error(_('Folgende Fehler sind aufgetreten:'), $errors);
- PageLayout::postMessage($message);
- return;
- }
-
- $consumer->store();
-
- if ($id) {
- $message = MessageBox::success(_('Die Applikation wurde erfolgreich gespeichert.'));
- } else {
- $details = $this->render_keys($consumer->id);
- $message = MessageBox::success(_('Die Applikation wurde erfolgreich erstellt, die Schlüssel finden Sie in den Details dieser Meldung.'), $details, true);
- }
- PageLayout::postMessage($message);
- $this->redirect('admin/api/index#' . $consumer->id);
- return;
- }
-
- $this->consumer = $consumer;
- $this->id = $id;
- }
-
- /**
- *
- **/
- public function toggle_action($id, $state = null)
- {
- $consumer = RESTAPI\Consumer\Base::find($id);
-
- $consumer->active = $state === null ? !$consumer->active : ($state === 'on');
- $consumer->store();
-
- $message = $state
- ? _('Die Applikation wurde erfolgreich aktiviert.')
- : _('Die Applikation wurde erfolgreich deaktiviert.');
-
- PageLayout::postMessage(MessageBox::success($message));
- $this->redirect('admin/api/#' . $consumer->id);
- }
-
- /**
- *
- **/
- public function delete_action($id)
- {
- if (!Request::isPost()) {
- throw new MethodNotAllowedException();
- }
- if ($consumer = RESTAPI\Consumer\Base::find($id)) {
- $consumer->delete();
-
- PageLayout::postSuccess(_('Die Applikation wurde erfolgreich gelöscht.'));
- }
- $this->redirect('admin/api');
- }
-
- /**
- *
- **/
- public function permissions_action($consumer_id = null)
- {
- if (Request::submitted('store')) {
- $perms = Request::getArray('permission');
- $permissions = RESTAPI\ConsumerPermissions::get($consumer_id ?: 'global');
-
- foreach ($perms as $route => $methods) {
- foreach ($methods as $method => $granted) {
- $permissions->set(urldecode($route), urldecode($method), (bool)$granted, true);
- }
- }
-
- $permissions->store();
-
- PageLayout::postMessage(MessageBox::success(_('Die Zugriffsberechtigungen wurden erfolgreich gespeichert')));
- $this->redirect($consumer_id ? 'admin/api' : 'admin/api/permissions');
- return;
- }
-
- $title = $consumer_id ? _('Zugriffsberechtigungen') : _('Globale Zugriffsberechtigungen');
- $title .= ' - ' . PageLayout::getTitle();
- PageLayout::setTitle($title);
-
- $this->consumer_id = $consumer_id;
- $this->router = RESTAPI\Router::getInstance();
- $this->routes = $this->router->getRoutes(true, false);
- $this->permissions = RESTAPI\ConsumerPermissions::get($consumer_id ?: 'global');
- $this->global = $consumer_id ? RESTAPI\ConsumerPermissions::get('global') : false;
- }
-
- public function config_action()
- {
- $this->config = Config::get();
-
- if (Request::isPost()) {
- $this->config->store('API_ENABLED', Request::int('active', 0));
- $this->config->store('API_OAUTH_AUTH_PLUGIN', Request::option('auth'));
-
- PageLayout::postMessage(MessageBox::success(_('Die Einstellungen wurden gespeichert.')));
- $this->redirect('admin/api/config');
- }
- }
-}
diff --git a/app/controllers/api/authorizations.php b/app/controllers/api/authorizations.php
deleted file mode 100644
index 543bc79..0000000
--- a/app/controllers/api/authorizations.php
+++ /dev/null
@@ -1,58 +0,0 @@
-<?php
-
-require_once 'lib/bootstrap-api.php';
-
-/**
-* @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- **/
-class Api_AuthorizationsController extends AuthenticatedController
-{
- /**
- *
- **/
- public function before_filter(&$action, &$args)
- {
- parent::before_filter($action, $args);
-
- $GLOBALS['perm']->check('autor');
-
- Navigation::activateItem('/profile/settings/api');
- PageLayout::setTitle(_('Applikationen'));
-
- $this->types = [
- 'website' => _('Website'),
- 'program' => _('Herkömmliches Desktopprogramm'),
- 'app' => _('Mobile App')
- ];
- }
-
- /**
- *
- **/
- public function index_action()
- {
- $this->consumers = RESTAPI\UserPermissions::get($GLOBALS['user']->id)->getConsumers();
- $this->types = [
- 'website' => _('Website'),
- 'program' => _('Herkömmliches Desktopprogramm'),
- 'app' => _('Mobile App')
- ];
-
- $widget = new SidebarWidget();
- $widget->setTitle(_('Informationen'));
- $widget->addElement(new WidgetElement(_('Dies sind die Apps, die Zugriff auf Ihren Account haben.')));
- Sidebar::Get()->addWidget($widget);
- }
-
- /**
- *
- **/
- public function revoke_action($id)
- {
- $consumer = new RESTAPI\Consumer\OAuth($id);
- $consumer->revokeAccess($GLOBALS['user']->id);
-
- PageLayout::postMessage(MessageBox::success(_('Der Applikation wurde der Zugriff auf Ihre Daten untersagt.')));
- $this->redirect('api/authorizations');
- }
-}
diff --git a/app/controllers/api/oauth.php b/app/controllers/api/oauth.php
deleted file mode 100644
index bc80c90..0000000
--- a/app/controllers/api/oauth.php
+++ /dev/null
@@ -1,113 +0,0 @@
-<?php
-
-require_once 'lib/bootstrap-api.php';
-
-/**
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- **/
-class Api_OauthController extends StudipController
-{
- /**
- *
- **/
- public function before_filter(&$action, &$args)
- {
- parent::before_filter($action, $args);
-
- # initialize Stud.IP-Session
- page_open(['sess' => 'Seminar_Session',
- 'auth' => 'Seminar_Default_Auth',
- 'perm' => 'Seminar_Perm',
- 'user' => 'Seminar_User']);
-
- $this->set_layout(null);
- }
-
- /**
- *
- **/
- public function index_action()
- {
- $this->render_text('TODO');
- }
-
- /**
- *
- **/
- public function request_token_action()
- {
- $server = new OAuthServer();
- $token = $server->requestToken();
-
- $this->response->headers = [];
- $this->render_nothing();
- }
-
- /**
- *
- **/
- public function authorize_action()
- {
- global $user, $auth;
-
- $auth_plugin = Config::get()->API_OAUTH_AUTH_PLUGIN;
- if ($GLOBALS['user']->id === 'nobody' && $auth_plugin !== 'Standard' && !Request::option('sso')) {
- $params = $_GET;
- $params['sso'] = strtolower($auth_plugin);
- $this->redirect($this->url_for('api/oauth/authorize?' . http_build_query($params)));
- return;
- } else {
- $auth->login_if($user->id === 'nobody');
- }
-
- $user_id = RESTAPI\Consumer\OAuth::getOAuthId($GLOBALS['user']->id);
-
- try {
- $consumer = RESTAPI\Consumer\Base::detectConsumer('oauth', 'request');
- if (!$consumer) {
- $this->response->set_status(400, 'No consumer detected');
- $this->render_nothing();
- return;
- }
-
- if (Request::submitted('allow')) {
- $result = $consumer->grantAccess($GLOBALS['user']->id);
-
- $redirect_uri = Request::get('oauth_callback', $consumer->callback);
-
- if ($redirect_uri) {
- $this->redirect($redirect_uri);
- } else {
- // No oauth_callback, show the user the result of the authorization
- // ** your code here **
- PageLayout::postMessage(MessageBox::success(_('Sie haben der Applikation Zugriff auf Ihre Daten gewährt.')));
- $this->redirect('api/authorizations#' . $consumer->auth_key);
- }
- return;
- }
- } catch (OAuthException2 $e) {
- // No token to be verified in the request, show a page where the user can enter the token to be verified
- // **your code here**
- die('invalid');
- }
-
- PageLayout::disableHeader();
- PageLayout::setTitle(sprintf(_('"%s" bittet um Zugriff'), $consumer->title));
- $this->set_layout($GLOBALS['template_factory']->open('layouts/base.php'));
- $this->consumer = $consumer;
- $this->token = Request::option('oauth_token');
- $this->oauth_callback = Request::get('oauth_callback');
- }
-
- /**
- *
- **/
- public function access_token_action()
- {
- $server = new OAuthServer();
- $server->accessToken();
-
- $this->response->headers = [];
- $this->render_nothing();
- }
-}
diff --git a/app/controllers/resources/ajax.php b/app/controllers/resources/ajax.php
index 998acaf..cffd878 100644
--- a/app/controllers/resources/ajax.php
+++ b/app/controllers/resources/ajax.php
@@ -16,22 +16,22 @@ class Resources_AjaxController extends AuthenticatedController
{
public function toggle_marked_action($request_id)
{
- $request = \ResourceRequest::find($request_id);
+ $request = ResourceRequest::find($request_id);
if (!$request) {
throw new Exception('Resource request object not found!');
}
- $current_user = \User::findCurrent();
+ $current_user = User::findCurrent();
if ($request->isReadOnlyForUser($current_user)) {
- throw new \AccessDeniedException();
+ throw new AccessDeniedException();
}
//Switch to the next marking state or return to the unmarked state
//if the next marking state would be after the last defined
//marking state.
- $request->marked = ($request->marked + 1) % \ResourceRequest::MARKING_STATES;
+ $request->marked = ($request->marked + 1) % ResourceRequest::MARKING_STATES;
$request->store();
$this->render_json($request->toArray());
@@ -39,46 +39,46 @@ class Resources_AjaxController extends AuthenticatedController
public function get_resource_booking_intervals_action($booking_id)
{
- $booking = \ResourceBooking::find($booking_id);
+ $booking = ResourceBooking::find($booking_id);
if (!$booking) {
throw new Exception('Resource booking object not found!');
}
$resource = $booking->resource->getDerivedClassInstance();
- if (!$resource->bookingPlanVisibleForUser(\User::findCurrent())) {
- throw new \AccessDeniedException();
+ if (!$resource->bookingPlanVisibleForUser(User::findCurrent())) {
+ throw new AccessDeniedException();
}
//Get begin and end:
- $begin_str = \Request::get('begin');
- $end_str = \Request::get('end');
+ $begin_str = Request::get('begin');
+ $end_str = Request::get('end');
$begin = null;
$end = null;
if ($begin_str && $end_str) {
//Try the ISO format first: YYYY-MM-DDTHH:MM:SS±ZZ:ZZ
- $begin = \DateTime::createFromFormat(\DateTime::RFC3339, $begin_str);
- $end = \DateTime::createFromFormat(\DateTime::RFC3339, $end_str);
- if (!($begin instanceof \DateTime) || !($end instanceof \DateTime)) {
- $tz = new \DateTime();
+ $begin = DateTime::createFromFormat(DateTime::RFC3339, $begin_str);
+ $end = DateTime::createFromFormat(DateTime::RFC3339, $end_str);
+ if (!($begin instanceof DateTime) || !($end instanceof DateTime)) {
+ $tz = new DateTime();
$tz = $tz->getTimezone();
//Try the ISO format without timezone:
- $begin = \DateTime::createFromFormat('Y-m-d\TH:i:s', $begin_str, $tz);
- $end = \DateTime::createFromFormat('Y-m-d\TH:i:s', $end_str, $tz);
+ $begin = DateTime::createFromFormat('Y-m-d\TH:i:s', $begin_str, $tz);
+ $end = DateTime::createFromFormat('Y-m-d\TH:i:s', $end_str, $tz);
}
}
$sql = "booking_id = :booking_id ";
$sql_data = ['booking_id' => $booking->id];
- if ($begin instanceof \DateTime && $end instanceof \DateTime) {
+ if ($begin instanceof DateTime && $end instanceof DateTime) {
$sql .= "AND begin >= :begin AND end <= :end ";
$sql_data['begin'] = $begin->getTimestamp();
$sql_data['end'] = $end->getTimestamp();
}
- if (\Request::submitted('exclude_cancelled_intervals')) {
+ if (Request::submitted('exclude_cancelled_intervals')) {
$sql .= "AND takes_place = '1' ";
}
$sql .= "ORDER BY begin ASC, end ASC";
- $intervals = \ResourceBookingInterval::findBySql($sql, $sql_data);
+ $intervals = ResourceBookingInterval::findBySql($sql, $sql_data);
$result = [];
foreach ($intervals as $interval) {
@@ -90,7 +90,7 @@ class Resources_AjaxController extends AuthenticatedController
public function toggle_takes_place_field_action($interval_id)
{
- $interval = \ResourceBookingInterval::find($interval_id);
+ $interval = ResourceBookingInterval::find($interval_id);
if (!$interval) {
throw new Exception('ResourceBookingInterval object not found!');
}
@@ -103,13 +103,13 @@ class Resources_AjaxController extends AuthenticatedController
$resource = $resource->getDerivedClassInstance();
- if (!$resource->userHasPermission(\User::findCurrent(), 'autor', [$interval->begin, $interval->end])) {
+ if (!$resource->userHasPermission(User::findCurrent(), 'autor', [$interval->begin, $interval->end])) {
throw new Exception('You do not have sufficient permissions to modify the interval!');
}
if (
!$interval->takes_place
- && $resource->isAssigned(new \DateTime('@' . $interval->begin), new \DateTime('@' . $interval->end))
+ && $resource->isAssigned(new DateTime('@' . $interval->begin), new DateTime('@' . $interval->end))
) {
throw new Exception('Already booked');
}
@@ -121,13 +121,14 @@ class Resources_AjaxController extends AuthenticatedController
'takes_place' => $interval->takes_place
]);
} else {
- throw new Exception('Error while storing the interval!');
+ $this->set_status(500);
+ $this->render_text('Error while storing the interval!');
}
}
public function get_semester_booking_plan_action($resource_id)
{
- $resource = \Resource::find($resource_id);
+ $resource = Resource::find($resource_id);
if (!$resource) {
throw new Exception('Resource object not found!');
}
@@ -143,8 +144,8 @@ class Resources_AjaxController extends AuthenticatedController
$display_requests = Request::get('display_requests');
$display_all_requests = Request::get('display_all_requests');
- $begin = new \DateTime();
- $end = new \DateTime();
+ $begin = new DateTime();
+ $end = new DateTime();
$semester_id = Request::get('semester_id');
@@ -194,7 +195,7 @@ class Resources_AjaxController extends AuthenticatedController
$requests_sql_params['user_id'] = $current_user->id;
}
- $requests = \ResourceRequest::findBySql(
+ $requests = ResourceRequest::findBySql(
$requests_sql,
$requests_sql_params
);
@@ -207,7 +208,7 @@ class Resources_AjaxController extends AuthenticatedController
$booking->resource = $resource;
$irrelevant_booking = $booking->getRepetitionType() !== 'weekly'
&& (
- !\Request::get('display_single_bookings')
+ !Request::get('display_single_bookings')
|| $booking->end < strtotime('today')
);
if ($booking->getAssignedUserType() === 'course' && in_array($booking->assigned_course_date->metadate_id, $meta_dates)) {
@@ -261,7 +262,7 @@ class Resources_AjaxController extends AuthenticatedController
$relevant_request = false;
foreach ($requests as $request) {
- if ($request->cycle instanceof \SeminarCycleDate) {
+ if ($request->cycle instanceof SeminarCycleDate) {
$cycle_dates = $request->cycle->getAllDates();
foreach ($cycle_dates as $cycle_date) {
$relevant_request = $semester->beginn <= $cycle_date->date
@@ -488,7 +489,7 @@ class Resources_AjaxController extends AuthenticatedController
$clipboard = Clipboard::find($clipboard_id);
if (!empty($_SESSION['selected_clipboard_id'])) {
- $clipboard = \Clipboard::find($_SESSION['selected_clipboard_id']);
+ $clipboard = Clipboard::find($_SESSION['selected_clipboard_id']);
}
if (!$clipboard) {
throw new Exception('Clipboard object not found!');
@@ -497,7 +498,7 @@ class Resources_AjaxController extends AuthenticatedController
//Permission check:
if ($clipboard->user_id !== $current_user->id) {
- throw new \AccessDeniedException();
+ throw new AccessDeniedException();
}
$display_requests = Request::bool('display_requests');
@@ -656,4 +657,186 @@ class Resources_AjaxController extends AuthenticatedController
$this->render_json($data);
}
+
+ public function move_booking_action($booking_id): void
+ {
+ $booking = ResourceBooking::find($booking_id);
+ if (!$booking) {
+ $this->notFound('Resource booking object not found!');
+ return;
+ }
+
+ $current_user = User::findCurrent();
+
+ if ($booking->isReadOnlyForUser($current_user)) {
+ throw new AccessDeniedException();
+ }
+
+ $resource_id = Request::get('resource_id');
+ $interval_id = Request::get('interval_id');
+
+ $begin = $this->convertDatetime(Request::get('begin'));
+ $end = $this->convertDatetime(Request::get('end'));
+
+ //Check if a specific interval has been moved:
+ if ($interval_id) {
+ $interval = ResourceBookingInterval::findOneBySql(
+ 'interval_id = ? AND booking_id = ?',
+ [$interval_id, $booking->id]
+ );
+ if (!$interval) {
+ $this->notFound('Resource booking interval not found!');
+ return;
+ }
+ $interval_begin = new DateTime();
+ $interval_begin->setTimestamp($interval->begin);
+ $interval_end = new DateTime();
+ $interval_end->setTimestamp($interval->end);
+
+ //Calculate the difference from the interval time range
+ //to the time range from the request. That difference
+ //is then applied to the booking.
+ $begin_diff = $interval_begin->diff($begin);
+ $end_diff = $interval_end->diff($end);
+
+ $new_booking_begin = new DateTime();
+ $new_booking_begin->setTimestamp($booking->begin);
+ $new_booking_end = new DateTime();
+ $new_booking_end->setTimestamp($booking->end);
+
+ $new_booking_begin = $new_booking_begin->add($begin_diff);
+ $new_booking_end = $new_booking_end->add($end_diff);
+ //We must substract the preparation time to the begin timestamp
+ //to get the real begin:
+ $real_begin = clone $new_booking_begin;
+ if ($booking->preparation_time > 0) {
+ $real_begin->sub(new DateInterval('PT' . ($booking->preparation_time / 60 ) . 'M'));
+ }
+ $booking->begin = $real_begin->getTimestamp();
+ $booking->end = $new_booking_end->getTimestamp();
+ } else {
+ //We must substract the preparation time to the begin timestamp
+ //to get the real begin:
+ $real_begin = clone $begin;
+ if ($booking->preparation_time > 0) {
+ $real_begin->sub(new DateInterval('PT' . ($booking->preparation_time / 60 ) . 'M'));
+ }
+ $booking->begin = $real_begin->getTimestamp();
+ $booking->end = $end->getTimestamp();
+ }
+ if ($resource_id) {
+ //The resource-ID has changed:
+ //The booking was moved from one resource to another.
+ $booking->resource_id = $resource_id;
+ }
+
+ //Update the booking_user_id field:
+ $booking->booking_user_id = User::findCurrent()->id;
+
+ try {
+ $booking->store();
+
+ if (Request::bool('quiet')) {
+ $this->render_nothing();
+ } else {
+ $this->render_json($booking->toRawArray());
+ }
+ } catch (Exception $e) {
+ $this->set_status(500);
+ $this->render_text($e->getMessage());
+ }
+ }
+
+ public function move_request_action($request_id): void
+ {
+ $request = ResourceRequest::find($request_id);
+ if (!$request) {
+ $this->notFound('Resource request object not found!');
+ return;
+ }
+
+ $current_user = User::findCurrent();
+
+ if ($request->isReadOnlyForUser($current_user)) {
+ throw new AccessDeniedException();
+ }
+
+ $request->begin = $this->convertDatetime(Request::get('begin'));
+ $request->end = $this->convertDatetime(Request::get('end'));
+
+ try {
+ $request->store();
+ $this->renderObject($request);
+ } catch (\Exception $e) {
+ $this->set_status(500);
+ $this->render_text($e->getMessage());
+ }
+ }
+
+ public function semester_week_action($timestamp)
+ {
+ $semester = \Semester::findByTimestamp($timestamp);
+ if (!$semester) {
+ $this->notFound('No semester found for given timestamp');
+ throw new RecordNotFoundException();
+ }
+
+ $timestamp = strtotime('today', $timestamp);
+ $week_begin_timestamp = strtotime('monday this week', $semester->vorles_beginn);
+ $end_date = $semester->vorles_ende;
+
+ $i = 0;
+ $result = [
+ 'semester_name' => (string)$semester->name,
+ 'week_number' => sprintf(_('KW %u'), date('W', $timestamp)),
+ 'current_day' => strftime('%x', $timestamp)
+ ];
+ while ($week_begin_timestamp < $end_date) {
+ $next_week_timestamp = strtotime('+1 week', $week_begin_timestamp);
+ if ($week_begin_timestamp <= $timestamp && $timestamp < $next_week_timestamp) {
+ $result['sem_week'] = sprintf(
+ _('%u. Vorlesungswoche (ab %s)'),
+ $i + 1,
+ strftime('%x', $week_begin_timestamp));
+ break;
+ }
+ $i += 1;
+
+ $week_begin_timestamp = $next_week_timestamp;
+ }
+
+ $this->render_json($result);
+ }
+
+ private function notFound(string $message = ''): void
+ {
+ $this->set_status(404);
+ $this->render_text($message);
+ }
+
+ private function renderObject(SimpleORMap $object): void
+ {
+ if (Request::bool('quiet')) {
+ $this->render_nothing();
+ } else{
+ $this->render_json($object->toArray());
+ }
+ }
+
+ /**
+ * Tries the ISO format first: YYYY-MM-DDTHH:MM:SS±ZZ:ZZ
+ */
+ private function convertDatetime(?string $input): ?Datetime
+ {
+ if (!$input) {
+ return null;
+ }
+
+ return DateTime::createFromFormat(DateTime::RFC3339, $input)
+ ?? DateTime::createFromFormat(
+ 'Y-m-d\TH:i:s',
+ $input,
+ (new DateTime())->getTimezone()
+ );
+ }
}
diff --git a/app/routes/Activity.php b/app/routes/Activity.php
deleted file mode 100644
index fadca0f..0000000
--- a/app/routes/Activity.php
+++ /dev/null
@@ -1,168 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @author Till Glöggler <tgloeggl@uos.de>
- * @author André Klaßen <klassen@elan-ev.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition user_id ^[a-f0-9]{1,32}$
- */
-class Activity extends \RESTAPI\RouteMap
-{
- /**
- * List activities for an user
- *
- * @get /user/:user_id/activitystream
- *
- * @param string $user_id the user to get the activities for
- *
- * @return array the activities as array('collection' => array(...), 'pagination' => array())
- */
- public function getActivities($user_id)
- {
- // only root can retrieve arbitrary streams
- if (!$GLOBALS['perm']->have_perm('root') && $GLOBALS['user']->id != $user_id) {
- $this->error(401);
- }
-
- // failsafe einbauen - falls es keine älteren Aktivitäten mehr im System gibt, Abbruch!
-
- $oldest_activity = \Studip\Activity\Activity::getOldestActivity();
- $max_age = $oldest_activity ? $oldest_activity->mkdate : time();
-
-
- $contexts = [];
-
- $user = \User::find($user_id);
-
- // create system context
- $system_context = new \Studip\Activity\SystemContext($user);
- $contexts[] = $system_context;
-
- $contexts[] = new \Studip\Activity\UserContext($user, $user);
- $user->contacts->each(function($another_user) use (&$contexts, $user) {
- $contexts[] = new \Studip\Activity\UserContext($another_user, $user);
- });
-
- if (!in_array($user->perms, ['admin','root'])) {
- // create courses and institutes context
- foreach (\Course::findMany($user->course_memberships->pluck('seminar_id')) as $course) {
- $contexts[] = new \Studip\Activity\CourseContext($course, $user);
- }
- foreach (\Institute::findMany($user->institute_memberships->pluck('institut_id')) as $institute) {
- $contexts[] = new \Studip\Activity\InstituteContext($institute, $user);
- }
- }
-
-
- // add filters
- $filter = new \Studip\Activity\Filter();
-
- $start = \Request::int('start', strtotime('-1 days'));
- $end = \Request::int('end', time());
-
-
- $scrollfrom = \Request::int('scrollfrom', false);
- $filtertype = \Request::get('filtertype', '');
-
- $objectType = \Request::get('object_type');
- $filter->setObjectType($objectType);
-
- $objectId = \Request::get('object_id');
- $filter->setObjectId($objectId);
-
- $context = \Request::get('context_type');
- $filter->setContext($context);
-
- $contextId = \Request::get('context_id');
- $filter->setContextId($contextId);
-
- if (!empty($filtertype)) {
- $filter->setType(json_decode($filtertype));
- }
-
- if ($scrollfrom) {
- // shorten "watch-window" by one second to prevent duplication of activities
- $scrollfrom -= 1;
-
- if ($scrollfrom > $max_age){
- $end = $scrollfrom;
- $start = strtotime('-1 day', $end);
- $data = [];
-
- $backtrack = 1;
-
- while (empty($data)) {
- $filter->setStartDate($start);
- $filter->setEndDate($end);
-
- $data = $this->getStreamData($contexts, $filter);
-
- if ($start < $max_age) {
- break;
- }
-
- // move "watch-window" back one day at a time
- $end = $start - 1;
- $start = strtotime('-'. $backtrack . ' days', $start);
-
- // enforce maximum "watch-window", currently 2 weeks
- $backtrack = min (14, $backtrack + 1);
- }
- } else {
- $data = false;
- }
- } else {
-
- $filter->setStartDate($start);
- $filter->setEndDate($end);
- $data = $this->getStreamData($contexts, $filter);
-
- }
-
- // set etag for preventing resending the same stuff over and over again
- $this->etag(md5(serialize($data)));
-
- return $data;
- }
-
- /**
- * private helper function to get stream data for given contexts and filter
- *
- * @param $contexts
- * @param $filter
- * @return array
- */
-
- private function getStreamData($contexts, $filter)
- {
- $stream = new \Studip\Activity\Stream($contexts, $filter);
- $data = $stream->toArray();
-
- foreach ($data as $key => $act) {
- $actor = [
- 'type' => $data[$key]['actor_type'],
- 'id' => $data[$key]['actor_id']
- ];
-
- if ($data[$key]['actor_type'] == 'user') {
- $a_user = \User::findFull($data[$key]['actor_id']);
- $actor['details'] = User::getMiniUser($this, $a_user ?: new \User());
- } elseif ($data[$key]['actor_type'] === 'anonymous') {
- $actor['details'] = [
- 'name' => _('Anonym'),
- ];
- }
-
- unset($data[$key]['actor_type']);
- unset($data[$key]['actor_id']);
-
- $data[$key]['actor'] = $actor;
- }
-
- return $data;
-
- }
-}
diff --git a/app/routes/Blubber.php b/app/routes/Blubber.php
deleted file mode 100644
index 1445088..0000000
--- a/app/routes/Blubber.php
+++ /dev/null
@@ -1,321 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition course_id ^[a-f0-9]{1,32}$
- * @condition stream_id ^(global|[a-f0-9]{1,32})$
- * @condition user_id ^[a-f0-9]{1,32}$
- * @condition blubber_id ^[a-f0-9]{1,32}$
- */
-class Blubber extends \RESTAPI\RouteMap
-{
-
- /**
- * Get content and some comments for a blubber-thread or for the "global" thread all "public" threads.
- *
- * @get /blubber/threads/:thread_id
- * @param string $thread_id id of the blubber thread or "global" if you want public threads (not comments). Remind the global thread is a virtual thread with a special behaviour.
- * @return array the blubber as array
- */
- public function getThreadData($thread_id)
- {
- if (!$GLOBALS['perm']->have_perm('autor')) {
- $this->error(401);
- }
- $GLOBALS['user']->cfg->store('BLUBBER_DEFAULT_THREAD', $thread_id);
-
- $thread = new \BlubberThread($thread_id);
- $thread = \BlubberThread::upgradeThread($thread);
- if (!$thread->isReadable()) {
- $this->error(401);
- }
-
- $json = $thread->getJSONData(50, null, \Request::get("search"));
- $thread->markAsRead();
-
- $this->etag(md5(serialize($json)));
-
- return $json;
- }
-
- /**
- * Get threads
- *
- * @get /blubber/threads
- * @return array the stream as array
- */
- public function getMyThreads()
- {
- $threads_data = [
- 'threads' => [],
- 'more_down' => 0,
- ];
- $limit = \Request::int('limit', 50);
-
- $threads = \BlubberThread::findMyGlobalThreads(
- $limit + 1,
- null,
- \Request::int('timestamp'),
- null,
- \Request::get("search") ?: null
- );
- if (count($threads) > $limit) {
- array_pop($threads);
- $threads_data['more_down'] = 1;
- }
- foreach ($threads as $thread) {
- $threads_data['threads'][] = [
- 'thread_id' => $thread->getId(),
- 'avatar' => $thread->getAvatar(),
- 'name' => $thread->getName(),
- 'timestamp' => (int) $thread->getLatestActivity(),
- ];
- }
- return $threads_data;
- }
-
- /**
- * Write a comment to a thread
- *
- * @post /blubber/threads/:thread_id/comments
- * @param string $thread_id id of the blubber thread
- * @return array the comment as array
- */
- public function postComment($thread_id)
- {
- if (!$GLOBALS['perm']->have_perm('autor')) {
- $this->error(401);
- }
-
- if (!trim($this->data['content'])) {
- $this->error(406);
- }
-
- $thread = \BlubberThread::find($thread_id);
- if (!$thread->isCommentable()) {
- $this->error(401);
- }
-
- $comment = new \BlubberComment();
- $comment['thread_id'] = $thread_id;
- $comment['content'] = $this->data['content'];
- $comment['user_id'] = $GLOBALS['user']->id;
- $comment['external_contact'] = 0;
- $comment->store();
-
- $thread->setLastVisit();
-
- return $comment->getJSONData();
- }
-
- /**
- * Write a comment to a thread
- *
- * @put /blubber/threads/:thread_id/comments/:comment_id
- *
- * @param string $thread_id id of the blubber thread
- * @param string $comment id of the comment
- *
- * @return array the comment as array
- */
- public function editComment($thread_id, $comment_id)
- {
- $comment = \BlubberComment::find($comment_id);
- if (!$comment->isWritable()) {
- $this->error(401);
- }
- $old_content = $comment['content'];
- $comment['content'] = $this->data['content'];
-
- if ($comment['user_id'] !== $GLOBALS['user']->id) {
- $messaging = new \messaging();
- $message = sprintf(
- _("%s hat als Moderator gerade Ihren Beitrag in Blubber editiert.\n\nDie alte Version des Beitrags lautete:\n\n%s\n\nDie neue lautet:\n\n%s\n"),
- get_fullname(), $old_content, $comment['content']
- );
-
- $message .= "\n\n";
-
- $message .= '[' . _('Link zu diesem Beitrag') . ']';
- $message .= \URLHelper::getURL(
- "{$GLOBALS['ABSOLUTE_URI_STUDIP']}dispatch.php/blubber/index/{$comment->thread_id}",
- [],
- true
- );
-
- $messaging->insert_message(
- $message,
- get_username($comment['user_id']),
- $GLOBALS['user']->id,
- null, null, null, null,
- _("Änderungen an Ihrem Blubber.")
- );
- }
-
- if (!trim($this->data['content'])) {
- $data = $comment->getJSONData();
- $comment->delete();
- } else {
- $comment->store();
- $data = $comment->getJSONData();
- }
- return $data;
- }
-
- /**
- * Write a comment to a thread
- *
- * @get /blubber/threads/:thread_id/comments
- *
- * @param string $thread_id id of the blubber thread
- *
- * @return array the comments as array
- */
- public function getComments($thread_id)
- {
- if (!$GLOBALS['perm']->have_perm('autor')) {
- $this->error(401);
- }
-
- $thread = new \BlubberThread($thread_id);
- if (!$thread->isReadable()) {
- $this->error(401);
- }
-
- $modifier = \Request::get('modifier');
- if ($modifier === 'olderthan') {
- $limit = \Request::int('limit', 50);
-
- $query = "SELECT blubber_comments.*
- FROM blubber_comments
- WHERE blubber_comments.thread_id = :thread_id
- AND blubber_comments.mkdate <= :timestamp
- ORDER BY mkdate DESC
- LIMIT :limit";
- $result = \DBManager::get()->fetchAll($query, [
- 'thread_id' => $thread_id,
- 'timestamp' => \Request::int('timestamp', time()),
- 'limit' => $limit + 1,
- ]);
-
- $output = ['comments' => []];
-
- if (count($result) > $limit) {
- array_pop($result);
- $output['more_up'] = 1;
- } else {
- $output['more_up'] = 0;
- }
- foreach ($result as $data) {
- $comment = \BlubberComment::buildExisting($data);
- $output['comments'][] = $comment->getJSONData();
- }
- return $output;
- }
-
- if ($modifier === 'newerthan') {
- $limit = \Request::int('limit', 50);
-
- $query = "SELECT blubber_comments.*
- FROM blubber_comments
- WHERE blubber_comments.thread_id = :thread_id
- AND blubber_comments.mkdate >= :timestamp
- ORDER BY mkdate
- LIMIT :limit";
- $comments = \DBManager::get()->fetchAll($query, [
- 'thread_id' => $thread_id,
- 'timestamp' => \Request::int('timestamp', time()),
- 'limit' => $limit + 1,
- ], function ($comment) {
- return \BlubberComment::buildExisting($comment)->getJSONData();
- });
-
- $output = ['comments' => $comments];
-
- if (count($comments) > $limit) {
- array_pop($output['comments']);
- $output['more_down'] = 1;
- } else {
- $output['more_down'] = 0;
- }
-
- return $output;
- }
-
- $query = "SELECT blubber_comments.*
- FROM blubber_comments
- WHERE blubber_comments.thread_id = :thread_id ";
- $parameters = ['thread_id' => $thread_id];
-
- if (\Request::get('search')) {
- $query .= " AND blubber_comments.content LIKE :search ";
- $parameters['search'] = '%'.\Request::get('search').'%';
- }
- $query .= " ORDER BY mkdate ASC ";
-
- $output['comments'] = \DBManager::get()->fetchAll($query, $parameters, function ($comment) {
- return \BlubberComment::buildExisting($comment)->getJSONData();
- });
- $output['more_up'] = 0;
- $output['more_down'] = 0;
-
- return $output;
- }
-
- /**
- * Does the current user follow the thread?
- *
- * @get /blubber/threads/:thread_id/follow
- */
- public function threadIsFollowed($thread_id)
- {
- return $this->requireThread($thread_id)->isFollowedByUser();
- }
-
- /**
- * User follows a thread.
- *
- * @post /blubber/threads/:thread_id/follow
- *
- * @param string $thread_id id of the blubber thread
- */
- public function followThread($thread_id)
- {
- $this->requireThread($thread_id)->addFollowingByUser();
- }
-
- /**
- * User unfollows a thread.
- *
- * @delete /blubber/threads/:thread_id/follow
- *
- * @param string $thread_id id of the blubber thread
- */
- public function unfollowThread($thread_id)
- {
- $this->requireThread($thread_id)->removeFollowingByUser();
- }
-
- /**
- * Returns a blubber thread and checks permissions.
- *
- * @param string $thread_id Id of the blubber thread
- * @return \BlubberThread
- */
- private function requireThread($thread_id)
- {
- if (!$GLOBALS['perm']->have_perm('autor')) {
- $this->error(401);
- }
-
- $thread = new \BlubberThread($thread_id);
- if (!$thread->isReadable()) {
- $this->error(401);
- }
-
- return \BlubberThread::upgradeThread($thread);
- }
-}
diff --git a/app/routes/Clipboard.php b/app/routes/Clipboard.php
deleted file mode 100644
index dfe22e0..0000000
--- a/app/routes/Clipboard.php
+++ /dev/null
@@ -1,193 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-
-/**
- * This file contains the REST class for the clipboard system.
- *
- * @author Moritz Strohm <strohm@data-quest.de>
- * @copyright 2017-2019
- * @license http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
- * @since 4.5
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class Clipboard extends \RESTAPI\RouteMap
-{
- /**
- * Adds a new clipboard.
- *
- * @post /clipboard/add
- */
- public function addClipboard()
- {
- $name = \Request::get('name');
-
- if (!$name) {
- $this->halt(400, _('Es wurde kein Name angegeben!'));
- }
-
- $clipboard = new \Clipboard();
- $clipboard->user_id = $GLOBALS['user']->id;
- $clipboard->name = $name;
- if (!$clipboard->store()) {
- $this->halt(500, _('Fehler beim Speichern des Merkzettels!'));
- }
-
- $result = $clipboard->toRawArray();
- //A special treatment for the widget_id parameter:
- //It is passed through:
- $widget_id = \Request::get('widget_id');
- if ($widget_id) {
- $result['widget_id'] = $widget_id;
- }
-
- return $result;
- }
-
-
- /**
- * Edits a clipboard.
- *
- * @put /clipboard/:clipboard_id
- */
- public function editCliboard($clipboard_id = null)
- {
- $clipboard = \Clipboard::find($clipboard_id);
- if (!$clipboard) {
- $this->notFound(_('Ungültige Merkzettel-ID!'));
- }
-
- if ($clipboard->user_id != $GLOBALS['user']->id) {
- //Thou shalt not delete clipboards
- //which don't belong to you!
- throw new \AccessDeniedException();
- }
-
- $name = $this->data['name'];
- if (!$name) {
- $this->halt(400, _('Es wurde kein Name angegeben!'));
- }
-
- $clipboard->name = $name;
-
- if ($clipboard->isDirty()) {
- $success = $clipboard->store();
- } else {
- $success = true;
- }
-
- if (!$success) {
- $this->halt(500, _('Fehler beim Bearbeiten des Merkzettels!'));
- }
-
- $result = $clipboard->toRawArray();
-
- //A special treatment for the widget_id parameter:
- //It is passed through:
- $widget_id = \Request::get('widget_id');
- if ($widget_id) {
- $result['widget_id'] = $widget_id;
- }
-
- return $result;
- }
-
-
- /**
- * Deletes a clipboard.
- *
- * @delete /clipboard/:clipboard_id
- */
- public function deleteClipboard($clipboard_id = null)
- {
- $clipboard = \Clipboard::find($clipboard_id);
- if (!$clipboard) {
- $this->notFound(_('Ungültige Merkzettel-ID!'));
- }
-
- if ($clipboard->user_id !== $GLOBALS['user']->id) {
- //Thou shalt not delete items of clipboards
- //which don't belong to you!
- throw new \AccessDeniedException();
- }
-
- if (!$clipboard->delete()) {
- $this->halt(500, _('Fehler beim Löschen des Merkzettels!'));
- }
-
- return "";
- }
-
-
- /**
- * Adds an item to a clipboard.
- *
- * @post /clipboard/:clipboard_id/item
- */
- public function addClipboardItem($clipboard_id = null)
- {
- $clipboard = \Clipboard::find($clipboard_id);
- if (!$clipboard) {
- $this->notFound(_('Ungültige Merkzettel-ID!'));
- }
-
- if ($clipboard->user_id != $GLOBALS['user']->id) {
- //Thou shalt not add items to clipboards
- //which don't belong to you!
- throw new \AccessDeniedException();
- }
-
- $range_id = \Request::get('range_id');
- $range_type = \Request::get('range_type');
- $widget_id = \Request::get('widget_id');
-
- if (!is_a($range_type, $clipboard->allowed_item_class, true)) {
- $this->halt(
- 400,
- sprintf(
- _('Die Klasse %s ist in dieser Merkzettel-Klasse nicht erlaubt!'),
- $range_type
- )
- );
- }
-
- try {
- $item = $clipboard->addItem($range_id, $range_type);
-
- $result = $item->toRawArray();
- $result['name'] = $item->__toString();
- if ($widget_id) {
- $result['widget_id'] = $widget_id;
- }
- return $result;
- } catch (\Exception $e) {
- $this->halt(500, $e->getMessage());
- }
- }
-
-
- /**
- * Removes an item (selected by its range-ID) from a clipboard.
- *
- * @delete /clipboard/:clipboard_id/item/:range_id
- */
- public function removeClipboardItem($clipboard_id = null, $range_id = null)
- {
- $clipboard = \Clipboard::find($clipboard_id);
- if (!$clipboard) {
- $this->notFound(_('Ungültige Merkzettel-ID!'));
- }
-
- if ($clipboard->user_id != $GLOBALS['user']->id) {
- //Thou shalt not delete items of clipboards
- //which don't belong to you!
- throw new \AccessDeniedException();
- }
-
- if ($clipboard->removeItem($range_id)) {
- return ['range_id' => $range_id];
- } else {
- $this->halt(500, _('Fehler beim Löschen des Eintrags!'));
- }
- }
-}
diff --git a/app/routes/Contacts.php b/app/routes/Contacts.php
deleted file mode 100644
index d7fd010..0000000
--- a/app/routes/Contacts.php
+++ /dev/null
@@ -1,302 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition user_id ^[a-f0-9]{1,32}$
- * @condition friend_id ^[a-f0-9]{1,32}$
- * @condition group_id ^[a-f0-9]{1,32}$
- */
-class Contacts extends \RESTAPI\RouteMap
-{
-
- public static function before()
- {
- require_once 'User.php';
- require_once 'lib/statusgruppe.inc.php';
- }
-
- /**
- * Lists all contacts of a user
- *
- * @get /user/:user_id/contacts
- */
- public function getUserContacts($user_id)
- {
- if ($GLOBALS['user']->id !== $user_id) {
- $this->error(401);
- }
-
- // quite degenerated as long as we can only see our own contacts
- $user = $this->requireUser($user_id);
-
- $total = count($user->contacts);
- $contacts = $user->contacts->limit($this->offset, $this->limit);
-
- $contacts_json = $this->contactsToJSON($contacts);
- $this->etag(md5(serialize($contacts_json)));
-
- return $this->paginated($contacts_json,
- $total, compact('user_id'));
- }
-
- /**
- * Adds/Updates a contact to user's list of contacts
- *
- * @put /user/:user_id/contacts/:friend_id
- */
- public function addUserContact($user_id, $buddy_user_id)
- {
- if ($GLOBALS['user']->id !== $user_id) {
- $this->error(401);
- }
-
- $user = $this->requireUser($user_id);
- $friend = $this->requireUser($buddy_user_id);
-
- // prevent duplicates
- if ($user->isFriendOf($friend)) {
- $this->error(409, sprintf('User "%s" is already a contact', htmlReady($friend->id)));
- }
-
- $user->contacts[] = $friend;
- $user->store();
-
- $this->status(201);
- }
-
- /**
- * Deletes a contact
- *
- * @delete /user/:user_id/contacts/:friend_id
- */
- public function removeUserContact($user_id, $buddy_user_id)
- {
- if ($GLOBALS['user']->id !== $user_id) {
- $this->error(401);
- }
-
- $user = $this->requireUser($user_id);
- $friend = $this->requireUser($buddy_user_id);
-
- if (!$user->isFriendOf($friend)) {
- $this->notFound("Contact not found");
- }
-
- $user->contacts->unsetByPK($friend->id);
- $user->store();
-
- $this->status(204);
- }
-
-
- /**
- * List all contact groups of a user
- *
- * @get /user/:user_id/contact_groups
- */
- public function getUserContactGroups($user_id)
- {
- if ($GLOBALS['user']->id !== $user_id) {
- $this->error(401);
- }
-
- $contact_groups = \SimpleCollection::createFromArray(
- \Statusgruppen::findByRange_id($GLOBALS['user']->id))
- ->orderBy('name ASC');
-
- $total = count($contact_groups);
- $contact_groups = $contact_groups->limit($this->offset, $this->limit);
-
- $contact_groups_json = $this->contactGroupsToJSON($contact_groups);
- $this->etag(md5(serialize($contact_groups_json)));
-
- return $this->paginated($contact_groups_json,
- $total, compact('user_id'));
- }
-
- /**
- * Create a new contact group for a user.
- *
- * @post /user/:user_id/contact_groups
- */
- public function createContactGroup($user_id)
- {
- if ($GLOBALS['user']->id !== $user_id) {
- $this->error(401);
- }
-
- if (!isset($this->data['name']) || !mb_strlen($name = trim($this->data['name']))) {
- $this->error(400, 'Contact group name required.');
- }
-
- $group = new \Statusgruppen();
- $group->range_id = $GLOBALS['user']->id;
- $group->name = $name;
- $group->size = 0;
- $group->selfassign = 0;
- $group->calendar_group = 0;
- $group->store();
- $this->redirect('contact_group/' . $group->id, 201, 'ok');
- }
-
- /**
- * Show a single contact group
- *
- * @get /contact_group/:group_id
- */
- public function showContactGroup($group_id)
- {
- $group = $this->requireContactGroup($group_id);
- $contact_group_json = $this->contactGroupToJSON($group);
- $this->etag(md5(serialize($contact_group_json)));
- return $contact_group_json;
- }
-
- /**
- * Remove a contact group
- *
- * @delete /contact_group/:group_id
- */
- public function destroyContactGroup($group_id)
- {
- $group = $this->requireContactGroup($group_id);
-
- $group->remove();
-
- $this->status(204);
- }
-
- /**
- * List all members of a contact group
- *
- * @get /contact_group/:group_id/members
- */
- public function indexOfContactGroupMembers($group_id)
- {
- $group = $this->requireContactGroup($group_id);
- $contacts = $group->members->limit($this->offset, $this->limit);
-
- $json = [];
- foreach ($contacts as $contact) {
- $url = $this->urlf('/contact_group/%s/members/%s', [$group_id, $contact->user_id]);
- $json[$url] = User::getMiniUser($this, $contact->user);
- }
-
- $this->etag(md5(serialize($json)));
-
- return $this->paginated($json, count($group->members), compact('group_id'));
- }
-
- /**
- * Add a user to a contact group
- *
- * @put /contact_group/:group_id/members/:user_id
- */
- public function addToContactGroup($group_id, $user_id)
- {
- $group = $this->requireContactGroup($group_id);
- $user = $this->requireUser($user_id);
-
- // prevent duplicates
- $exists = $group->members->findBy('user_id', $user_id)->first();
- if ($exists) {
- $this->halt(204);
- }
-
- $new_contact = [
- 'owner_id' => $GLOBALS['user']->id,
- 'user_id' => $user->id];
-
- $new_contact['group_assignments'][] = ['statusgruppe_id' => $group->id,
- 'user_id' => $user->id];
-
- $success = (bool)\Contact::import($new_contact)->store();
-
-
- if (!$success) {
- $this->error(500);
- }
-
- $this->status(201);
- }
-
- /**
- * Remove a user from a contact group
- *
- * @delete /contact_group/:group_id/members/:user_id
- */
- public function removeFromContactGroup($group_id, $user_id)
- {
- $group = $this->requireContactGroup($group_id);
- $membership = $group->members->findBy('user_id', $user_id)->first();
- if (!$membership) {
- $this->notFound();
- }
-
- $membership->delete();
-
- $this->status(204);
- }
-
-
- /**************************************************/
- /* PRIVATE HELPER METHODS */
- /**************************************************/
-
- private function requireUser($user_id)
- {
- $user = \User::find($user_id);
- // TODO: checks visibility using the global perm object!
- if (!$user || !get_visibility_by_id($user_id)) {
- $this->notFound(sprintf("Could not find user with id: %s", htmlReady($user_id)));
- }
-
- return $user;
- }
-
- private function requireContactGroup($group_id)
- {
- $group = \Statusgruppen::find($group_id);
- if (!$group) {
- $this->notFound();
- }
-
- if ($group->range_id !== $GLOBALS['user']->id) {
- $this->error(401);
- }
- return $group;
- }
-
- private function contactsToJSON($contacts) {
- $result = [];
- foreach ($contacts as $contact) {
- $result[] = User::getMiniUser($this, $contact);
- }
- return $result;
- }
-
- private function contactGroupsToJSON($contact_groups)
- {
- $result = [];
- foreach ($contact_groups as $cg) {
- $url = $this->urlf('/contact_group/%s', [htmlReady($cg->id)]);
- $result[$url] = $this->contactGroupToJSON($cg);
- }
- return $result;
- }
-
- private function contactGroupToJSON($group)
- {
- $json = [
- 'id' => $group->id,
- 'name' => (string) $group->name,
- 'contacts' => $this->urlf('/contact_group/%s/members', [htmlReady($group->id)]),
- 'contacts_count' => sizeof($group->members)
- ];
- return $json;
- }
-}
diff --git a/app/routes/Course.php b/app/routes/Course.php
deleted file mode 100644
index d1fad96..0000000
--- a/app/routes/Course.php
+++ /dev/null
@@ -1,242 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition course_id ^[a-f0-9]{1,32}$
- * @condition user_id ^[a-f0-9]{1,32}$
- */
-class Course extends \RESTAPI\RouteMap
-{
-
- public function before()
- {
- require_once 'User.php';
- }
-
- /**
- * Lists all courses of a user including the semesters in which
- * that course is active.
- * Optionally filtered by a URL parameter 'semester'.
- *
- * @get /user/:user_id/courses
- */
- public function getUserCourses($user_id)
- {
- if (($GLOBALS['user']->id !== $user_id) && !$GLOBALS['perm']->have_perm("root")) {
- $this->error(401);
- }
-
- // setting up semester to filter by
- $semester = null;
- $semester_id = \Request::get('semester');
- if ($semester_id) {
- $semester = \Semester::find($semester_id);
- if (!$semester) {
- $this->error(400, "Semester not found.");
- }
- }
-
- $memberships = $this->findMembershipsByUserId($user_id, $semester);
-
- $total = count($memberships);
- $memberships = $memberships->limit($this->offset, $this->limit);
- $memberships_json = $this->membershipsToJSON($memberships);
- $this->etag(md5(serialize($memberships_json)));
- return $this->paginated(
- $memberships_json,
- $total,
- compact('user_id'),
- ['semester' => $semester_id]
- );
- }
-
- /**
- * Show a single course
- *
- * @get /course/:course_id
- */
- public function getCourse($course_id)
- {
- if (!$course = \Course::find($course_id)) {
- $this->notFound("Course not found");
- }
-
- $course = $this->requireCourse($course_id);
- $this->lastmodified($course->chdate);
- $course_json = $this->courseToJSON($course);
- $this->etag(md5(serialize($course_json)));
- return $course_json;
- }
-
- /**
- * List all members of a course.
- * Optionally filtered by a URL parameter 'status'.
- *
- * @get /course/:course_id/members
- */
- public function getMembers($course_id)
- {
- $status_filter = \Request::get('status');
- if ($status_filter && !in_array($status_filter, words("user autor tutor dozent"))) {
- $this->error(400, "Status may be one of: user, autor, tutor, dozent");
- }
-
- $course = $this->requireCourse($course_id);
- $members = $course->members;
- if ($status_filter) {
- $members = $members->findBy('status', $status_filter);
- }
-
- $total = count($members);
- $members = $members->limit($this->offset, $this->limit);
- $members_json = $this->membersToJSON($course, $members);
- $this->etag(md5(serialize($members_json)));
- return $this->paginated(
- $members_json,
- $total,
- compact('course_id'),
- ['status' => $status_filter]
- );
- }
-
- /**
- * Get the root file folder of a course.
- *
- * @get /course/:course_id/top_folder
- */
- public function getTopFolder($course_id)
- {
- $top_folder = \Folder::findTopFolder(
- $this->requireCourse($course_id)->id,
- 'course'
- );
-
- if (!$top_folder) {
- $this->notFound("No folder found for course with id {$course_id}!");
- }
-
- return (new FileSystem())->getFolder($top_folder->id);
- }
-
- /**************************************************/
- /* PRIVATE HELPER METHODS */
- /**************************************************/
-
- private function findMembershipsByUserId($user_id, $semester)
- {
- $memberships = \SimpleORMapCollection::createFromArray(
- \CourseMember::findBySQL('user_id = ? ORDER BY mkdate ASC', [$user_id])
- );
-
- // filter by semester
- if ($semester) {
-
- $memberships = $memberships->filter(function ($m) use ($semester) {
- return $m->course->isInSemester($semester);
- });
- }
-
- return $memberships;
- }
-
- private function membershipsToJSON($memberships)
- {
- $json = [];
-
- foreach ($memberships as $membership) {
- $course_json = $this->courseToJSON($course = $membership->course);
-
- $json[$this->urlf("/course/%s", [$course->id])] = $course_json;
- }
- return $json;
- }
-
- private function courseToJSON($course)
- {
- $json = [];
-
- $json['course_id'] = $course->id;
- $json['number'] = $course->VeranstaltungsNummer;
- $json['title'] = (string) $course->Name;
- $json['subtitle'] = (string) $course->Untertitel;
- $json['type'] = $course->status;
- $json['description'] = (string) $course->Beschreibung;
- $json['location'] = (string) $course->Ort;
-
- // lecturers
- foreach ($course->getMembersWithStatus('dozent') as $lecturer) {
- $url = $this->urlf('/user/%s', [htmlReady($lecturer->user_id)]);
- $json['lecturers'][$url] = User::getMiniUser($this, $lecturer->user);
- }
-
- // other members
- foreach (words("user autor tutor dozent") as $status) {
- $json['members'][$status] = $this->urlf('/course/%s/members?status=%s', [$course->id, $status]);
- $json['members'][$status . '_count'] = $course->countMembersWithStatus($status);
- }
-
- foreach (words("start_semester end_semester") as $key) {
- $json[$key] = $course->$key ? $this->urlf('/semester/%s', [htmlReady($course->$key->id)]) : null;
- }
-
- $activated = array_map('get_class', $course->getActivatedTools());
-
- $json['modules'] = [];
- foreach (['forum' => 'forum_categories',
- 'documents' => 'top_folder',
- 'wiki' => 'wiki'] as $module => $uri)
- {
- if (in_array('Core' . ucfirst($module), $activated)) {
- $json['modules'][$module] = $this->urlf('/course/%s/%s', [htmlReady($course->id), $uri]);
- }
- }
-
- // Add group if current user is member of the group
- $json['group'] = null;
-
- $member = \CourseMember::find([$course->id, $GLOBALS['user']->id]);
- if ($member) {
- $json['group'] = (int) $member->gruppe;
- }
-
-
- return $json;
- }
-
- private function requireCourse($id)
- {
- if (!$course = \Course::find($id)) {
- $this->notFound("Course not found");
- }
-
- //This route is used in the room management system.
- //Therefore, we need not only to check if the user is in the course,
- //but also, if the user is a global resource admin. In the latter case,
- //access shall also be granted.
- if (!$GLOBALS['perm']->have_studip_perm('user', $id, $GLOBALS['user']->id)
- && !\ResourceManager::userHasGlobalPermission(\User::findCurrent(), 'admin')) {
- $this->error(401);
- }
-
- return $course;
- }
-
- private function membersToJSON($course, $members)
- {
- $json = [];
-
- foreach ($members as $member) {
- $url = $this->urlf('/user/%s', [$member->user_id]);
- $avatar = \Avatar::getAvatar($member->user_id);
- $json[$url] = [
- 'member' => User::getMiniUser($this, $member->user),
- 'status' => $member->status
- ];
- }
- return $json;
- }
-}
diff --git a/app/routes/Discovery.php b/app/routes/Discovery.php
deleted file mode 100644
index c83f524..0000000
--- a/app/routes/Discovery.php
+++ /dev/null
@@ -1,27 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class Discovery extends \RESTAPI\RouteMap
-{
- /**
- * Schnittstellenbeschreibung
- *
- * @get /discovery
- */
- public function getDiscovery()
- {
- $routes = $this->router->getRoutes(true);
- foreach ($routes as $uri_template => $methods) {
- foreach ($methods as $method => $route) {
- $routes[$uri_template][$method] = $route['description'];
- }
- }
- return $routes;
- }
-}
diff --git a/app/routes/Events.php b/app/routes/Events.php
deleted file mode 100644
index 368d615..0000000
--- a/app/routes/Events.php
+++ /dev/null
@@ -1,186 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-use Config;
-use Resource;
-use Room;
-use Seminar;
-use Issue;
-
-
-/**
- * @author André Klaßen <andre.klassen@elan-ev.de>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition course_id ^[a-f0-9]{1,32}$
- * @condition user_id ^[a-f0-9]{1,32}$
- * @condition semester_id ^[a-f0-9]{1,32}$
- */
-class Events extends \RESTAPI\RouteMap
-{
-
- /**
- * returns all upcoming events within the next two weeks for a given user
- *
- * @get /user/:user_id/events
- */
- public function getEvents($user_id)
- {
- if ($user_id !== $GLOBALS['user']->id) {
- $this->error(401);
- }
-
- $start = new \DateTime();
- $end = clone $start;
- $end = $end->add(new \DateInterval('P2W'));
-
- $list = array_merge(
- \CalendarCourseDate::getEvents($start, $end, $user_id),
- \CalendarCourseExDate::getEvents($start, $end, $user_id)
- );
-
- $json = [];
- $events = array_slice($list, $this->offset, $this->limit); ;
- foreach ($events as $event) {
-
- $course_uri = $this->urlf('/course/%s', [htmlReady($event->range_id)]);
-
- $json[] = [
- 'event_id' => $event->id,
- 'course' => $course_uri,
- 'start' => $event->date,
- 'end' => $event->end_time,
- 'title' => $event->getTitle(),
- 'description' => $event->getDescription() ?: '',
- 'categories' => $event->getTypeName(),
- 'room' => $event->getRoomName(),
- 'canceled' => $event instanceof \CourseExDate || holiday($event->date),
- ];
- }
-
- $this->etag(md5(serialize($json)));
-
- return $this->paginated($json, count($list), compact('user_id'));
- }
-
- /**
- * returns an iCAL Export of all events for a given user
- *
- * @get /user/:user_id/events.ics
- */
- public function getEventsICAL($user_id)
- {
- if ($user_id !== $GLOBALS['user']->id) {
- $this->error(401);
- }
- $end = new \DateTime();
- $end->setTimestamp(\CalendarDate::NEVER_ENDING);
- $start = new \DateTime();
- $start->modify('-4 week');
- $ical_export = new \ICalendarExport();
- $ical = $ical_export->exportCalendarDates($user_id, $start, $end)
- . $ical_export->exportCourseDates($user_id, $start, $end)
- . $ical_export->exportCourseExDates($user_id, $start, $end);
- $content = $ical_export->writeHeader() . $ical . $ical_export->writeFooter();
-
- $this->contentType('text/calendar');
- $this->headers([
- 'Content-Length' => strlen($content),
- 'Content-Disposition' => 'attachment; ' . encode_header_parameter('filename', 'studip.ics'),
- ]);
- $this->halt(200, $this->response->headers, function () use ($content) {
- echo $content;
- });
- }
-
-
- /**
- * returns events for a given course
- *
- * @get /course/:course_id/events
- */
- public function getEventsForCourse($course_id)
- {
- if (!$GLOBALS['perm']->have_studip_perm('user', $course_id, $GLOBALS['user']->id)) {
- $this->error(401);
- }
-
- $seminar = new Seminar($course_id);
- $dates = getAllSortedSingleDates($seminar);
- $total = sizeof($dates);
-
- $events = [];
- foreach (array_slice($dates, $this->offset, $this->limit) as $date) {
-
- // get issue titles
- $issue_titles = [];
- if (is_array($issues = $date->getIssueIDs())) {
- foreach ($issues as $is) {
- $issue = new Issue(['issue_id' => $is]);
- $issue_titles[] = $issue->getTitle();
- }
- }
-
- $room = self::getRoomForSingleDate($date);
- $events[] = [
- 'event_id' => $date->getSingleDateID(),
- 'start' => $date->getStartTime(),
- 'end' => $date->getEndTime(),
- 'title' => $date->toString(),
- 'description' => implode(', ', $issue_titles),
- 'categories' => $date->getTypeName() ?: '',
- 'room' => $room ?: '',
- 'deleted' => $date->isExTermin(),
- 'canceled' => $date->isHoliday() ?: false,
- ];
- }
-
- $this->etag(md5(serialize($events)));
-
- return $this->paginated($events, $total, compact('course_id'));
- }
-
- private static function getRoomForSingleDate($val) {
-
- /* css-Klasse auswählen, sowie Template-Feld für den Raum mit Text füllen */
- if (Config::get()->RESOURCES_ENABLE) {
-
- if ($val->getResourceID()) {
- $resObj = Resource::find($val->getResourceID());
- if ($resObj) {
- $room_object = $resObj->getDerivedClassInstance();
- if ($room_object instanceof Room) {
- $room = _("Raum: ");
- $room .= $room_object->getActionURL('booking_plan');
- }
- }
- } else {
- $room = _("keine Raumangabe");
-
- if ($val->isExTermin()) {
- if ($name = $val->isHoliday()) {
- $room = '('.$name.')';
- } else {
- $room = '('._('fällt aus').')';
- }
- }
-
- else {
- if ($val->getFreeRoomText()) {
- $room = '('.htmlReady($val->getFreeRoomText()).')';
- }
- }
- }
- } else {
- $room = '';
- if ($val->getFreeRoomText()) {
- $room = '('.htmlReady($val->getFreeRoomText()).')';
- }
- }
-
- return html_entity_decode(strip_tags($room));
- }
-
-}
diff --git a/app/routes/Feedback.php b/app/routes/Feedback.php
deleted file mode 100644
index 9a28347..0000000
--- a/app/routes/Feedback.php
+++ /dev/null
@@ -1,271 +0,0 @@
-<?php
-
-namespace RESTAPI\Routes;
-
-/**
- * @author Nils Gehrke <nils.gehrke@uni-goettingen.de>
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition feedback_id ^\d*$
- * @condition course_id ^[a-f0-9]{32}$
- *
- */
-class Feedback extends \RESTAPI\RouteMap
-{
- /**
- * Create feedback element for a range
- *
- * @post /feedback/range/:range_id/:range_type
- *
- */
- public function createFeedbackElement($range_id, $range_type)
- {
- $course_id = $range_type::find($range_id)->getRangeCourseId();
- if (!\Feedback::hasRangeAccess($range_id, $range_type) || !\Feedback::hasCreatePerm($course_id)) {
- $this->error(403);
- }
- $feedback = \FeedbackElement::build([
- 'range_id' => $range_id,
- 'range_type' => $range_type,
- 'user_id' => $GLOBALS['user']->id,
- 'course_id' => $course_id,
- 'question' => $this->data['question'],
- 'description' => $this->data['description'],
- 'results_visible' => intval($this->data['results_visible']),
- 'commentable' => intval($this->data['commentable']),
- 'mode' => $this->data['mode']
- ]);
- $feedback->store();
- return $feedback->toArray();
- }
-
- /**
- * Get a feedback element
- *
- * @get /feedback/:feedback_id
- *
- */
- public function getFeedbackElement($feedback_id)
- {
- if (!$feedback = \FeedbackElement::find($feedback_id)) {
- $this->error(404);
- }
- if (!\Feedback::hasRangeAccess($feedback->range_id, $feedback->range_type)) {
- $this->error(403);
- }
- return $feedback->toArray();
- }
-
-
- /**
- * Get all entries of a feedback element
- *
- * @get /feedback/:feedback_id/entries
- *
- */
- public function getFeedbackEntries($feedback_id)
- {
- if (!$feedback = \FeedbackElement::find($feedback_id)) {
- $this->error(404);
- }
- if (!\Feedback::hasRangeAccess($feedback->range_id, $feedback->range_type)) {
- $this->error(403);
- }
- if ($feedback->results_visible == 1 && !$feedback->isFeedbackable()) {
- foreach($feedback->entries as $entry) {
- $result['entries'][] = $entry->toArray();
- }
- } elseif (!$feedback->isFeedbackable()) {
- $result['entries'][] = $feedback->getOwnEntry()->toArray();
- } else {
- $result = [];
- }
-
- return $result;
- }
-
- /**
- * Edit a feedback element
- *
- * @put /feedback/:feedback_id
- *
- */
- public function editFeedbackElement($feedback_id)
- {
- if (!$feedback = \FeedbackElement::find($feedback_id)) {
- $this->error(404);
- }
- $course_id = $feedback->course_id;
- if (!\Feedback::hasRangeAccess($feedback->range_id, $feedback->range_type) || !\Feedback::hasAdminPerm($course_id)) {
- $this->error(403);
- }
- $feedback->question = $this->data['question'] !== null ? $this->data['question'] : $feedback->question;
- $feedback->description = $this->data['description'] !== null ? $this->data['description'] : $feedback->description;
- $feedback->results_visible = $this->data['results_visible'] !== null ?
- intval($this->data['results_visible']) : $feedback->results_visible;
- $feedback->store();
- return $feedback->toArray();
- }
-
- /**
- * Delete a feedback element
- *
- * @delete /feedback/:feedback_id
- *
- */
- public function deleteFeedbackElement($feedback_id)
- {
- if (!$feedback = \FeedbackElement::find($feedback_id)) {
- $this->error(404);
- }
- $course_id = $feedback->course_id;
- if (!\Feedback::hasRangeAccess($feedback->range_id, $feedback->range_type) || !\Feedback::hasAdminPerm($course_id)) {
- $this->error(403);
- }
- $feedback->delete();
- $this->halt(200);
- }
-
- /**
- * List all feedback elements for a range
- *
- * @get /feedback/range/:range_id/:range_type
- *
- * @param string $range_id
- * @param string $range_type
- */
- public function getFeedbackElementsForRange($range_id, $range_type)
- {
- if (!\Feedback::hasRangeAccess($range_id, $range_type)) {
- $this->error(403, 'You may not access the given range object.');
- }
- $feedback_elements = \FeedbackElement::findBySQL('range_id = ? AND range_type = ? ORDER BY mkdate DESC', [$range_id, $range_type]);
- foreach($feedback_elements as $feedback) {
- $result['feedback_elements'][] = $feedback->toArray();
- }
- return $result;
- }
-
- /**
- * List all feedback elements of a course
- *
- * @get /course/:course_id/feedback
- *
- */
- public function getFeedbackElementsForCourse($course_id)
- {
- if (!\Feedback::hasAdminPerm($course_id)) {
- $this->error(403, 'You may not list all feedback elements of the course. Only feedback admins can.');
- }
- $feedback_elements = \FeedbackElement::findBySQL('course_id = ? ORDER BY mkdate DESC', [$course_id]);
- foreach($feedback_elements as $feedback) {
- $result['feedback_elements'][] = $feedback->toArray();
- }
- return $result;
- }
-
- /**
- * add an entry for a feedback element
- *
- * @post /feedback/:feedback_id/entry
- *
- */
- public function addFeedbackEntry($feedback_id)
- {
- if (!$feedback = \FeedbackElement::find($feedback_id)) {
- $this->error(404);
- }
- if (!$feedback->isFeedbackable()) {
- $this->error(403, 'You may not add an entry here. Maybe you have already given feedback or you are the author of the feedback element.');
- }
- $entry = \FeedbackEntry::build([
- 'feedback_id' => $feedback->id,
- 'user_id' => $GLOBALS['user']->id
- ]);
-
- $entry->rating = $this->getRating(
- $feedback->mode,
- (int) $this->data['rating']
- );
-
- if ($feedback->commentable) {
- $entry->comment = $this->data['comment'];
- }
-
- $entry->store();
- return $entry->toArray();
- }
-
- /**
- * edit an entry of a feedback element
- *
- * @put /feedback/entry/:entry_id
- *
- */
- public function editFeedbackEntry($entry_id)
- {
- $entry = \FeedbackEntry::find($entry_id);
-
- if (!$entry) {
- $this->notFound();
- }
-
- if (!$entry->isEditable()) {
- $this->error(403);
- }
-
- $entry->rating = $this->getRating(
- $entry->feedback->mode,
- (int) $this->data['rating']
- );
-
- if ($entry->feedback->commentable) {
- $entry->comment = $this->data['comment'] ?? $entry->comment;
- }
-
- $entry->store();
- return $entry->toArray();
- }
-
- /**
- * delete an entry of a feedback element
- *
- * @delete /feedback/entry/:entry_id
- *
- */
- public function deleteFeedbackEntry($entry_id)
- {
- if (!$entry = \FeedbackEntry::find($entry_id)) {
- $this->error(404);
- }
- if ($entry->delete()){
- $this->halt(200);
- }
- }
-
- /**
- * @param int $mode
- * @param int $rating
- * @return int
- */
- private function getRating(int $mode, int $rating): int
- {
- if ($mode === 0) {
- return 0;
- }
-
- if ($rating === 0) {
- return 1;
- }
-
- if ($mode === 1) {
- return min(5, $rating);
- }
-
- if ($mode === 2) {
- return min(10, $rating);
- }
-
- throw new \InvalidArgumentException("Invalid mode {$mode}");
- }
-}
diff --git a/app/routes/FileSystem.php b/app/routes/FileSystem.php
deleted file mode 100644
index 9abd713..0000000
--- a/app/routes/FileSystem.php
+++ /dev/null
@@ -1,684 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * This class implements REST routes for the new Stud.IP file system.
- *
- * @author Moritz Strohm <strohm@data-quest.de>
- * @license GNU General Public License Version 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * Partially based upon the Files.php source code from Jan-Hendrik Willms
- * (tleilax+studip@gmail.com) and mluzena@uos.de which is also
- * licensed under the terms of the GNU General Public License Version 2
- * or later.
- */
-
-class FileSystem extends \RESTAPI\RouteMap
-{
- // FILE REFERENCE AND FILE ROUTES:
-
- /**
- * Get a file reference object (metadata)
- * @get /file/:file_ref_id
- */
- public function getFileRef($file_ref_id)
- {
- return $this->filerefToJSON(
- $this->requireFileRef($file_ref_id),
- (bool) \Request::int('extended')
- );
- }
-
- /**
- * Get the data of a file by the ID of an associated FileRef object
- *
- * @get /file/:file_ref_id/download
- */
- public function getFileRefData($file_ref_id)
- {
- $file_ref = $this->requireFileRef($file_ref_id);
-
- // check if the current user has the permissions to read this file reference:
- $user = \User::findCurrent();
- if (!$file_ref->folder->getTypedFolder()->isFileDownloadable($file_ref_id, $user->id)) {
- $this->error(403, "You may not download the file reference with the id {$file_ref_id}");
- }
-
- // check if file exists:
- if (!$file_ref->file) {
- $this->error(500, 'File reference has no associated file object!');
- }
-
- $data_path = $file_ref->file->getPath();
- if (!file_exists($data_path)) {
- $this->error(500, "File was not found in the operating system's file system!");
- }
-
- $this->lastModified($file_ref->file->chdate);
- $this->sendFile($data_path, ['filename' => $file_ref->name]);
- }
-
- /**
- * Update file data using a FileReference to it.
- *
- * @post /file/:file_ref_id/update
- */
- public function updateFileData($file_ref_id)
- {
- // We only update the first file:
- $uploaded_file = array_shift($this->data['_FILES']);
-
- // FileManager::updateFileRef handles the whole file upload
- // and does all the necessary security checks:
- $result = \FileManager::updateFileRef(
- $this->requireFileRef($file_ref_id),
- \User::findCurrent(),
- $uploaded_file,
- true,
- false
- );
-
- if (!$result instanceof \FileRef) {
- $this->error(500, 'Error while updating a file reference: ' . implode(' ', $result));
- }
-
- return $this->filerefToJSON($result);
- }
-
- /**
- * Edit a file reference.
- *
- * @put /file/:file_ref_id
- */
- public function editFileRef($file_ref_id)
- {
- $result = \FileManager::editFileRef(
- $this->requireFileRef($file_ref_id),
- \User::findCurrent(),
- $this->data['name'],
- $this->data['description'],
- $this->data['content_term_of_use_id'],
- $this->data['license']
- );
-
- if (!$result instanceof \FileRef) {
- $this->error(500, 'Error while editing a file reference: ' . implode(' ', $result));
- }
-
- return $this->filerefToJSON($result);
- }
-
- /**
- * Copies a file reference.
- *
- * @post /file/:file_ref_id/copy/:destination_folder_id
- */
- public function copyFileRef($file_ref_id, $destination_folder_id)
- {
- $result = \FileManager::copyFile(
- $this->requireFileRef($file_ref_id)->getFileType(),
- $this->requireFolder($destination_folder_id)->getTypedFolder(),
- \User::findCurrent()
- );
-
- if (!($result instanceof \FileType)) {
- $this->error(500, 'Error while copying a file reference: ' . implode(' ', $result));
- }
-
- return $this->filerefToJSON($result->getFileRef());
- }
-
- /**
- * Moves a file reference.
- *
- * @post /file/:file_ref_id/move/:destination_folder_id
- */
- public function moveFileRef($file_ref_id, $destination_folder_id)
- {
- $result = \FileManager::moveFile(
- $this->requireFileRef($file_ref_id)->getFileType(),
- $this->requireFolder($destination_folder_id)->getTypedFolder(),
- \User::findCurrent()
- );
-
- if (!($result instanceof \FileType)) {
- $this->error(500, 'Error while moving a file reference: ' . implode(' ', $result));
- }
-
- return $this->filerefToJSON($result->getFileRef());
- }
-
- /**
- * Deletes a file reference.
- *
- * @delete /file/:file_ref_id
- */
- public function deleteFileRef($file_ref_id)
- {
- $result = \FileManager::deleteFileRef(
- $this->requireFileRef($file_ref_id),
- \User::findCurrent()
- );
-
- if (!$result instanceof \FileRef) {
- $this->error(500, 'Error while deleting a file reference: ' . implode(' ', $result));
- }
-
- $this->halt(200);
- }
-
- /**
- * Upload file to given folder.
- * file data has to be attached as multipart/form-data
- *
- * @post /file/:folder_id
- */
- public function uploadFile($folder_id)
- {
- $typed_folder = $this->requireFolder($folder_id)->getTypedFolder();
- if (isset($this->data['_FILES'])) {
- $file_data = array_map(function ($a) {
- return is_array($a) ? $a : [$a];
- }, array_shift($this->data['_FILES']));
- }
- if (is_array($file_data)) {
- $validated_files = \FileManager::handleFileUpload(
- $file_data,
- $typed_folder,
- $this->requireUser()->id
- );
-
- if (count($validated_files['error']) > 0) {
- $this->error(500, 'Error while uploading files: ' . implode(' ', $validated_files['error']));
- }
-
- $uploaded_files = \SimpleCollection::createFromArray($validated_files['files']);
- $default_license = \ContentTermsOfUse::findDefault();
- $uploaded_files->setValue('content_terms_of_use_id', $default_license->id);
- $uploaded_files->store();
- if (count($uploaded_files) === 1) {
- $result = $this->filerefToJSON($uploaded_files->first());
- } else {
- $result = $uploaded_files->map(function ($f) {
- return $this->filerefToJSON($f);
- });
- }
- $this->halt(201, [], $result);
- } else {
- $this->error(400, 'No files found in request.');
- }
- }
-
- // FOLDER ROUTES:
-
- /**
- * Returns a list of defined folder types, separated by range type.
- * @get /studip/file_system/folder_types
- */
- public function getDefinedFolderTypes()
- {
- return \FileManager::getFolderTypes();
- }
-
- /**
- * Get a folder object with its file references, subdirectories and the permissions for the user who has made the API call.
- * @get /folder/:folder_id
- */
- public function getFolder($folder_id)
- {
- return $this->folderToJSON(
- $this->requireFolder($folder_id),
- true
- );
- }
-
- /**
- * Creates a new folder inside of another folder and returns the new object on success.
- * @post /folder/:parent_folder_id/new_folder
- */
- public function createNewFolder($parent_folder_id)
- {
- $user = \User::findCurrent();
- $parent = $this->requireTypedFolder($parent_folder_id);
-
- if (!$parent->isWritable($user->id)) {
- $this->error(403, 'You are not permitted to create a subfolder in the parent folder!');
- }
-
- $result = \FileManager::createSubFolder(
- $parent,
- $user,
- 'StandardFolder', //to be extended
- $this->data['name'],
- $this->data['description']
- );
-
- if (!$result instanceof \FolderType) {
- $this->error(500, 'Error while creating a folder: ' . implode(' ', $result));
- }
-
- return $this->folderToJSON(
- $this->requireFolder($result->getId())
- );
- }
-
- /**
- * Get a list with all FileRef objects of a folder.
- * @get /folder/:folder_id/files
- */
- public function getFileRefsOfFolder($folder_id)
- {
- $folder = $this->requireFolder($folder_id);
-
- $query = "folder_id = :folder_id ORDER BY name ASC";
- $parameters[':folder_id'] = $folder->id;
-
- if ($this->limit || $this->offset) {
- $query .= " LIMIT :limit OFFSET :offset";
- $parameters[':limit'] = $this->limit;
- $parameters[':offset'] = $this->offset;
- }
-
- $file_refs = \FileRef::findAndMapBySql(function (\FileRef $ref) {
- return $this->filerefToJSON($ref);
- }, $query, $parameters);
-
- return $this->paginated(
- $file_refs,
- \FileRef::countByFolder_id($folder->id),
- ['folder_id' => $folder->id]
- );
- }
-
-
- /**
- * Get a list with all FileRef objects of a folder.
- * @get /folder/:folder_id/subfolders
- */
- public function getSubfoldersOfFolder($folder_id)
- {
- $user = $this->requireUser();
- $folder = $this->requireFolder($folder_id);
-
- $query = "parent_id = :parent_id ORDER BY name ASC";
- $parameters = [':parent_id' => $folder->id];
-
- if ($this->limit || $this->offset) {
- $query .= " LIMIT :limit OFFSET :offset";
- $parameters[':limit'] = $this->limit;
- $parameters[':offset'] = $this->offset;
- }
-
- $subfolders = \Folder::findAndMapBySql(function (\Folder $subfolder) use ($user) {
- $type = $subfolder->getTypedFolder();
- if (!$type || !$type->isVisible($user->id)) {
- return false;
- }
- return $this->folderToJSON($subfolder);
- }, $query, $parameters);
-
- return $this->paginated(
- array_filter($subfolders),
- \Folder::countByParent_id($folder_id),
- ['folder_id' => $folder_id]
- );
- }
-
- /**
- * Get a list with permissions the current user has for a folder.
- * @get /folder/:folder_id/permissions
- */
- public function getFolderPermissions($folder_id)
- {
- $user = $this->requireUser();
- $folder = $this->requireFolder($folder_id);
-
- // read permissions of the user and return them:
- return array_merge([
- 'folder_id' => $folder->id,
- 'user_id' => $user->id,
- ], $this->folderPermissionsToJSON($folder));
- }
-
- /**
- * Allows editing the name or the description (or both) of a folder.
- *
- * @put /folder/:folder_id
- */
- public function editFolder($folder_id)
- {
- if (isset($this->data['name']) && !$this->data['name']) {
- $this->error(400, "The name for the folder with the id {$folder_id} must not be empty!");
- }
-
- $user = $this->requireUser();
- $typed_folder = $this->requireTypedFolder($folder_id);
-
- if (!$typed_folder->isEditable($user->id)) {
- $this->error(403, "You may not edit the folder with id {$folder_id}!");
- }
-
- if (!$typed_folder instanceof \StandardFolder) {
- $this->error(501, "Editing is only allowed for folders of type StandardFolder for now!");
- }
-
- if ($this->data['name']) {
- $typed_folder->name = $this->data['name'];
- }
- if (isset($this->data['description'])) {
- $typed_folder->description = $this->data['description'] ?: '';
- }
-
- if (!$typed_folder->store()) {
- $this->error(500, "Could not store folder with id {$folder_id}!");
- }
-
- return $this->folderToJSON(
- $this->requireFolder($folder_id)
- );
- }
-
- /**
- * Copies a folder into another folder.
- *
- * @post /folder/:folder_id/copy/:destination_folder_id
- */
- public function copyFolder($folder_id, $destination_folder_id)
- {
- $result = \FileManager::copyFolder(
- $this->requireTypedFolder($folder_id),
- $this->requireTypedFolder($destination_folder_id),
- \User::findCurrent()
- );
-
- if (!$result instanceof \FolderType) {
- $this->error(500, 'Error while copying a folder: ' . implode(' ', $result));
- }
-
- return $this->folderToJSON(
- $this->requireFolder($result->getId())
- );
- }
-
-
- /**
- * Move a folder into another folder.
- * @post /folder/:folder_id/move/:destination_folder_id
- */
- public function moveFolder($folder_id, $destination_folder_id)
- {
- $result = \FileManager::moveFolder(
- $this->requireTypedFolder($folder_id),
- $this->requireTypedFolder($destination_folder_id),
- \User::findCurrent()
- );
-
- if (!$result instanceof \FolderType) {
- $this->error(500, 'Error while moving a folder: ' . implode(' ', $result));
- }
-
- return $this->folderToJSON(
- $this->requireFolder($folder_id)
- );
- }
-
-
- /**
- * Deletes a folder.
- *
- * @delete /folder/:folder_id
- */
- public function deleteFolder($folder_id)
- {
- $result = \FileManager::deleteFolder(
- $this->requireTypedFolder($folder_id),
- \User::findCurrent()
- );
-
- if (!$result instanceof \FolderType) {
- $this->error(500, 'Error while deleting a folder: ' . implode(' ', $result));
- }
-
- $this->halt(200);
- }
-
- // RELATED OBJECT ROUTES:
-
- /**
- * Get a collection of all ContentTermsOfUse objects
- *
- * @get /studip/content_terms_of_use_list
- */
- public function getContentTermsOfUseList()
- {
- $objects = \ContentTermsOfUse::findBySql(
- '1 ORDER BY name ASC LIMIT :limit OFFSET :offset',
- ['limit' => $this->limit, 'offset' => $this->offset]
- );
-
- return $this->paginated(
- array_map([$this, 'termsOfUseToJSON'], $objects),
- \ContentTermsOfUse::countBySql('1')
- );
- }
-
- // UTILITY METHODS
-
- /**
- * Requires a valid user object.
- * @return \User object
- */
- private function requireUser()
- {
- return \User::findCurrent();
- }
-
- /**
- * Requires a valid file reference object
- * @param mixed $id_or_object Either a file reference id or object
- * @return \FileRef object
- */
- private function requireFileRef($id_or_object)
- {
- if ($id_or_object instanceof \FileRef) {
- $file_ref = $id_or_object;
- } else {
- //check if the file_id references a file reference object:
- $file_ref = \FileRef::find($id_or_object);
- if (!$file_ref) {
- $this->notFound("File reference with id {$id_or_object} not found!");
- }
- }
-
- // check if the file reference is placed inside a folder.
- // (must be present to check for permissions)
- if (!$file_ref->folder) {
- $this->error(500, "File reference with id {$file_ref->id} has no folder!");
- }
-
- $typed_folder = $file_ref->folder->getTypedFolder();
- if (!$typed_folder) {
- $this->error(500, "The folder of file reference with id {$file_ref->id} has no folder type!");
- }
-
- //check if the current user has the permissions to read this file reference:
- if (!$typed_folder->isReadable($this->requireUser()->id)) {
- $this->error(403, "You are not permitted to read the file reference with id {$file_ref->id}!");
- }
-
- return $file_ref;
- }
-
- /**
- * Converts a file reference object to JSON.
- * @param \FileRef $ref File reference object
- * @param boolean $extended Extended output? (includes folder, owner and terms of use)
- * @return array representation for json encoding
- */
- private function filerefToJSON(\FileRef $ref, $extended = false)
- {
- $user = $this->requireUser();
- $typed_folder = $ref->folder->getTypedFolder();
- $filetype = $ref->getFileType();
-
- $result = array_merge($ref->toRawArray(), [
- 'size' => (int) $ref->file->size,
- 'mime_type' => $ref->file->mime_type,
- 'storage' => $ref->file->filetype === "URLFile" ? "url" : "disk",
-
- 'is_readable' => $typed_folder->isReadable($user->id),
- 'is_downloadable' => $filetype->isDownloadable($user->id),
- 'is_editable' => $filetype->isEditable($user->id),
- 'is_writable' => $filetype->isWritable($user->id),
- ]);
-
- $result['downloads'] = (int) $result['downloads'];
- $result['mkdate'] = (int) $result['mkdate'];
- $result['chdate'] = (int) $result['chdate'];
-
- if ($result['storage'] === 'url') {
- $result['url'] = $ref->getFileType()->getDownloadURL();
- }
-
- if ($extended) {
- //folder does exist (since we checked for its existence above)
- $result['folder'] = $this->folderToJSON($ref->folder);
-
- if ($ref->owner) {
- $result['owner'] = User::getMiniUser($this, $ref->owner);
- }
-
- //$result['license'] = $file_ref->license; //to be activated when licenses are defined
-
- if ($ref->terms_of_use) {
- $result['terms_of_use'] = $this->termsOfUseToJSON($ref->terms_of_use);
- }
- }
-
- return $result;
- }
-
- /**
- * Requires a valid folder object
- * @param mixed $id_or_object Either a folder id or object
- * @return Folder object
- */
- private function requireFolder($id_or_object)
- {
- if ($id_or_object instanceof \Folder) {
- $folder = $id_or_object;
- } else {
- $folder = \Folder::find($id_or_object);
- if (!$folder) {
- $this->notFound("Folder with id {$id_or_object} not found!");
- }
- }
-
- $typed_folder = $folder->getTypedFolder();
- if (!$typed_folder) {
- $this->error(500, "Cannot find folder type of folder with id {$folder->id}!");
- return;
- }
-
- if (!$typed_folder->isReadable($this->requireUser()->id)) {
- $this->error(403, "You are not allowed to read the contents of the folder with the id {$folder->id}!");
- }
-
- return $folder;
- }
-
- /**
- * Requires a valid typed folder object
- * @param mixed $id_or_object Either a folder id or object
- * @return FolderType instance
- */
- private function requireTypedFolder($id_or_object)
- {
- return $this->requireFolder($id_or_object)->getTypedFolder();
- }
-
- /**
- * Converts a given folder to JSON.
- * @param Folder $folder Folder object
- * @param boolean $extended Extended output? (includes subfolders and file references)
- * @return array representation for json encoding
- */
- private function folderToJSON(\Folder $folder, $extended = false)
- {
- $result = $this->folderPermissionsToJSON($folder);
-
- if ($result['is_readable']) {
- $result = array_merge($folder->toRawArray(), $result);
-
- $result['mkdate'] = (int) $result['mkdate'];
- $result['chdate'] = (int) $result['chdate'];
-
- //The field "data_content" must be handled differently
- //than the other fields since it contains JSON data.
- $data_content = json_decode($folder->data_content);
- $result['data_content'] = $data_content;
-
- if ($extended) {
- $user = $this->requireUser();
-
- $result['subfolders'] = [];
- foreach ($folder->subfolders as $subfolder) {
- if (!$subfolder->getTypedFolder()->isVisible($user->id)) {
- continue;
- }
- $result['subfolders'][] = $this->folderToJSON($subfolder);
- }
-
- $result['file_refs'] = [];
- foreach ($folder->getTypedFolder()->getFiles() as $file) {
- if (method_exists($file,"getFileRef")) {
- $result['file_refs'][] = $this->filerefToJSON(
- $file->getFileRef()
- );
- }
- }
- }
- }
-
- return $result;
- }
-
- /**
- * Converts permissions of a folder to JSON.
- * @param Folder $folder Folder object
- * @param User $user User object to check permissions against
- * @return array representation for json encoding
- */
- private function folderPermissionsToJSON(\Folder $folder)
- {
- $user = $this->requireUser();
- $type = $folder = $folder->getTypedFolder();
- if (!$type) {
- $this->error(500, 'Folder type not found!');
- }
-
- return [
- 'is_visible' => $type->isVisible($user->id),
- 'is_readable' => $type->isReadable($user->id),
- 'is_writable' => $type->isWritable($user->id),
- ];
- }
-
- /**
- * Converts a terms of use object to JSON.
- * @param ContentTermsOfUse $object Object
- * @return array representation for json encoding
- */
- private function termsOfUseToJSON(\ContentTermsOfUse $object)
- {
- $result = $object->toRawArray();
-
- $result['is_default'] = (bool) $result['is_default'];
-
- $result['mkdate'] = (int) $result['mkdate'];
- $result['chdate'] = (int) $result['chdate'];
-
- return $result;
- }
-}
diff --git a/app/routes/Forum.php b/app/routes/Forum.php
deleted file mode 100644
index 35aad91..0000000
--- a/app/routes/Forum.php
+++ /dev/null
@@ -1,419 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition course_id ^[a-f0-9]{1,32}$
- */
-class Forum extends \RESTAPI\RouteMap
-{
- /**
- * List all categories of a forum
- *
- * @get /course/:course_id/forum_categories
- */
- public function getForumCategories($course_id)
- {
- if (!\ForumPerm::has('view', $course_id)) {
- $this->error(401);
- }
-
- $categories = \ForumCat::findBySeminar_id($course_id, 'ORDER BY pos ASC');
- $total = sizeof($categories);
- $categories = array_splice($categories, (int)$this->offset, (int)$this->limit ?: 10);
-
- $json = [];
- foreach ($categories as $cat) {
- $json_cat = $cat->toArray();
- $uri = $this->urlf('/forum_category/%s', [htmlReady($json_cat['category_id'])]);
- $json_cat['course_id'] = $json_cat['seminar_id'];
- $json[$uri] = $this->categoryToJson($json_cat);
- }
-
- $this->etag(md5(serialize($json)));
-
- return $this->paginated($json, $total, compact('course_id'));
- }
-
- /**
- * Create a new category
- *
- * @post /course/:course_id/forum_categories
- */
- public function createForumCategory($course_id)
- {
- if (!\ForumPerm::has("add_category", $course_id)) {
- $this->error(401);
- }
-
- if (!isset($this->data['name']) || !mb_strlen($name = trim($this->data['name']))) {
- $this->error(400, 'Category name required.');
- }
-
- $category_id = \ForumCat::add($course_id, $name);
- if (!$category_id) {
- $this->error(500, 'Error creating the forum category.');
- }
-
- $this->redirect('forum_category/' . $category_id, 201, 'ok');
- }
-
- /**
- * Read a category
- *
- * @get /forum_category/:category_id
- */
- public function getForumCategory($category_id)
- {
- $category = $this->findCategory($category_id);
- $cid = $category['course_id'];
-
- if (!\ForumPerm::has('view', $cid)) {
- $this->error(401);
- }
-
- $category_json = $this->categoryToJson($category);
- $this->etag(md5(serialize($category_json)));
- return $category_json;
- }
-
- /**
- * Update a category
- *
- * @put /forum_category/:category_id
- */
- public function updateForumCategory($category_id)
- {
- $category = $this->findCategory($category_id);
-
- if (!\ForumPerm::has("edit_category", $category['course_id'])) {
- $this->error(401);
- }
-
- if (!isset($this->data['name']) || !mb_strlen($name = trim($this->data['name']))) {
- $this->error(400, 'Category name required.');
- }
-
- \ForumCat::setName($category_id, $this->data['name']);
-
- $this->status(204);
- }
-
- /**
- * Delete a category
- *
- * @delete /forum_category/:category_id
- */
- public function deleteForumCategory($category_id)
- {
- $category = $this->findCategory($category_id);
- $cid = $category['course_id'];
-
- if (!\ForumPerm::has("remove_category", $cid)) {
- $this->error(401);
- }
-
- \ForumCat::remove($category_id, $cid);
-
- $this->status(204);
- }
-
- /**
- * Show entries of a category
- *
- * @get /forum_category/:category_id/areas
- */
- public function getCategoryEntries($category_id)
- {
- $category = $this->findCategory($category_id);
-
- if (!\ForumPerm::has('view', $category['course_id'])) {
- $this->error(401);
- }
-
- $areas = $this->getAreas($category_id, $this->offset, $this->limit);
-
- $this->etag(md5(serialize($areas)));
- return $this->paginated($areas, $this->countAreas($category_id), compact('category_id'));
- }
-
-
-
- /**
- * Add a new forum entry to an existing one
- *
- * @post /forum_category/:category_id/areas
- */
- public function appendForumEntry($category_id)
- {
- $category = $this->findCategory($category_id);
- $cid = $category['course_id'];
-
- if (!\ForumPerm::has('add_area', $cid)) {
- $this->error(401);
- }
-
- if (!isset($this->data['subject']) || !mb_strlen($subject = trim($this->data['subject']))) {
- $this->error(400, 'Subject required.');
- }
-
- if (!isset($this->data['content'])) {
- $this->error(400, 'Content required.');
- }
- $content = trim($this->data['content']);
-
- $anonymous = isset($this->data['anonymous']) ? intval($this->data['anonymous']) : 0;
-
- $entry_id = $this->createEntry($cid, $cid, $subject, $content, $anonymous);
-
- \ForumCat::addArea($category_id, $entry_id);
-
- $this->redirect('forum_entry/' . $entry_id, 201, "ok");
- }
-
- /**
- * Get a forum entry
- *
- * @get /forum_entry/:entry_id
- */
- public function getForumEntry($entry_id)
- {
- $entry = \ForumEntry::getConstraints($entry_id);
- $cid = $entry['seminar_id'];
-
- if (!\ForumPerm::has('view', $cid)) {
- $this->error(401);
- }
-
- $entry = $this->findEntry($entry_id);
- $this->lastmodified($entry->chdate);
- $this->etag(md5(serialize($entry)));
- return $entry;
- }
-
- /**
- * Add a new forum entry to an existing one
- *
- * @post /forum_entry/:entry_id
- */
- public function addForumEntry($parent_id)
- {
- $parent = \ForumEntry::getConstraints($parent_id);
- $cid = $parent['seminar_id'];
-
- $perm = self::isArea($parent) ? 'add_area' : 'add_entry';
-
- if (!\ForumPerm::has($perm, $cid)) {
- $this->error(401);
- }
-
- $subject = (string) trim($this->data['subject']);
- $content = (string) trim($this->data['content']);
-
- // areas and threads need a subject, postings do not
- if ($parent['depth'] < 3 && !$subject) {
- $this->error(400, 'Subject required.');
- }
-
- // all entries besides the area need content
- if ($parent['depth'] > 1 && !$content) {
- $this->error(400, 'Content required.');
- }
-
- if ($parent['depth'] >= 3 && $subject) {
- $this->error(400, 'Must not have subject here.');
- }
-
- $anonymous = isset($this->data['anonymous']) ? (int) $this->data['anonymous'] : 0;
-
- $entry_id = $this->createEntry($parent_id, $cid, $subject, $content, $anonymous);
-
- $this->redirect('forum_entry/' . $entry_id, 201, "ok");
- }
-
- /**
- * Update an existing one forum entry
- *
- * @put /forum_entry/:entry_id
- */
- public function updateForumEntry($entry_id)
- {
- $entry = \ForumEntry::getConstraints($entry_id);
- $cid = $entry['seminar_id'];
-
- $perm = self::isArea($entry) ? 'edit_area' : 'edit_entry';
-
- if (!\ForumPerm::hasEditPerms($entry_id) || !\ForumPerm::has($perm, $cid)) {
- $this->error(401);
- }
-
- $subject = (string) trim($this->data['subject']);
- $content = (string) trim($this->data['content']);
-
- // areas and threads need a subject, postings do not
- if ($entry['depth'] < 3 && !$subject) {
- $this->error(400, 'Subject required.');
- }
-
- // all entries besides the area need content
- if ($entry['depth'] > 1 && !$content) {
- $this->error(400, 'Content required.');
- }
-
- if ($entry['depth'] >= 3 && $subject) {
- $this->error(400, 'Must not have subject here.');
- }
-
- \ForumEntry::update($entry_id, $subject, $content);
-
- $this->status(204);
- }
-
- /**
- * Delete an entry
- *
- * @delete /forum_entry/:entry_id
- */
- public function deleteForumEntry($entry_id)
- {
- $entry = \ForumEntry::getConstraints($entry_id);
- $cid = $entry['seminar_id'];
-
- if (!\ForumPerm::hasEditPerms($entry_id) || !\ForumPerm::has('remove_entry', $cid)) {
- $this->error(401);
- }
-
- \ForumEntry::delete($entry_id);
-
- $this->status(204);
- }
-
- /*********************
- * *
- * PRIVATE FUNCTIONS *
- * *
- *********************/
-
-
- private function findEntry($entry_id)
- {
- $raw = \ForumEntry::getConstraints($entry_id);
- if ($raw === false) {
- $this->notFound();
- }
-
- $entry = $this->convertEntry($raw);
-
- $children = \ForumEntry::getEntries($entry_id, \ForumEntry::WITHOUT_CHILDS, '', 'ASC', 0, false);
-
- if (isset($children['list'][$entry_id])) {
- unset($children['list'][$entry_id]);
- }
-
- $entry['children'] = [];
- foreach (array_values($children['list']) as $childentry) {
- $entry['children'][] = $this->convertEntry($childentry);
- }
-
- return $entry;
- }
-
- public function convertEntry($raw)
- {
- $entry = [];
- foreach(words("topic_id mkdate chdate anonymous depth") as $key) {
- $entry[$key] = $raw[$key];
- }
-
- $hide_user = $entry['anonymous'] && $raw['user_id'] !== $GLOBALS['user']->id;
-
- $entry['subject'] = $raw['name'];
- $entry['user'] = $hide_user ? null : $this->urlf('/user/%s', [$raw['user_id']]);
- $entry['course'] = $this->urlf('/course/%s', [$raw['seminar_id']]);
- $entry['content_html'] = \ForumEntry::getContentAsHtml($raw['content']);
- $entry['content'] = \ForumEntry::killEdit($raw['content']);
-
- return $entry;
- }
-
-
- private static function isArea($entry)
- {
- return 1 === $entry['depth'];
- }
-
- private function createEntry($parent_id, $course_id, $subject, $content, $anonymous)
- {
- $topic_id = self::generateID();
-
- $data = [
- 'topic_id' => $topic_id,
- 'seminar_id' => $course_id,
- 'user_id' => $GLOBALS['user']->id,
- 'name' => $subject,
- 'content' => $content,
- 'author' => $GLOBALS['user']->getFullName(),
- 'author_host' => $_SERVER['REMOTE_ADDR'],
- 'anonymous' => (int) $anonymous
- ];
- \ForumEntry::insert($data, $parent_id);
-
- return $topic_id;
- }
-
- private function findCategory($category_id)
- {
- $result = [];
-
- if ($cat = \ForumCat::get($category_id)) {
- $result = $cat;
- $result['course_id'] = $cat['seminar_id'];
- $result['name'] = $cat['entry_name'];
- } else {
- $this->error(404);
- }
-
- return $result;
- }
-
- private function categoryToJson($category)
- {
- $json = $category;
-
- $json['course'] = $this->urlf('/course/%s', [htmlReady($json['course_id'])]);
- unset($json['course_id']);
-
- $json['areas'] = $this->urlf('/forum_category/%s/areas', [$json['category_id']]);
- $json['areas_count'] = $this->countAreas($json['category_id']);
-
- return $json;
- }
-
- private function countAreas($category_id)
- {
- return sizeof(\ForumCat::getAreas($category_id));
- }
-
- private function getAreas($category_id, $offset = 0, $limit = 10)
- {
- $offset = (int) $offset;
- $limit = (int) $limit;
-
- $areas = [];
-
- foreach (\ForumCat::getAreas($category_id, $offset, $limit) as $area) {
- $url = $this->urlf('/forum_entry/%s', [htmlReady($area['topic_id'])]);
- $areas[$url] = $this->convertEntry($area);
- }
-
- return $areas;
- }
-
- private static function generateID()
- {
- return md5(uniqid(rand()));
- }
-}
diff --git a/app/routes/Messages.php b/app/routes/Messages.php
deleted file mode 100644
index db9cb2e..0000000
--- a/app/routes/Messages.php
+++ /dev/null
@@ -1,301 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition message_id ^[a-f0-9]{1,32}$
- * @condition user_id ^[a-f0-9]{1,32}$
- * @condition box ^(inbox|outbox)$
- */
-class Messages extends \RESTAPI\RouteMap
-{
- /**
- * Liefert die Anzahl der vorhandenen Nachrichten des autorisierten Nutzers
- * zurück. Der Parameter bestimmt je nach Wert, auf welchen Bereich
- * (Posteingang bzw. Postausgang) zugegriffen werden soll.
- * Die Rückgabe beinhaltet jeweils die Anzahl aller Nachrichten sowie die
- * Anzahl der ungelesenen Nachrichten.
- *
- * @head /user/:user_id/:box
- */
- public function indexOfMessages($user_id, $box)
- {
- if ($user_id !== self::currentUser()) {
- $this->error(401);
- }
-
- $count = $this->countMessages($user_id, $box);
-
- $this->headers([
- 'X-Messages-Total' => $count['total'],
- 'X-Messages-Unread' => $count['unread'],
- ]);
-
- return null;
- }
-
- /**
- * Liefert die vorhandenen Nachrichten des autorisierten Nutzers zurück.
- *
- * @get /user/:user_id/:box
- */
- public function getMessages($user_id, $box)
- {
- if ($user_id !== self::currentUser()) {
- $this->error(401);
- }
-
- $ids = $this->getMessageIds($user_id, $box);
- $total = count($ids);
-
- $ids = array_slice($ids, $this->offset, $this->limit);
-
- $messages = [];
- if (count($ids) > 0) {
- \Message::findEachMany(function ($message) use (&$messages) {
- $url = $this->urlf('/message/%s', $message->id);
- $messages[$url] = $this->messageToJSON($message);
- }, $ids, 'ORDER BY mkdate DESC');
- }
-
- return $this->paginated($messages, $total, compact('user_id', 'box'));
- }
-
- /**
- * Liefert die Daten der angegebenen Nachricht zurück.
- *
- * @get /message/:message_id
- */
- public function showMessage($message_id)
- {
- $message = $this->requireMessage($message_id);
- $message_json = $this->messageToJSON($message);
- $this->etag(md5(serialize($message_json)));
- return $message_json;
- }
-
-
- /**
- * Get the root file folder of a message. The root file folder contains all
- * files that were appended to the message.
- *
- * @get /message/:message_id/file_folder
- */
- public function getTopFolder($message_id)
- {
- //first we check if the user exists:
- $message = \Message::find($message_id);
-
- $user = \User::findCurrent();
-
- if (!$user) {
- $this->halt(404, 'User not found!');
- }
-
- if(!$message->permissionToRead($user->id)) {
- $this->halt(403, 'You are not allowed to read this message or its appended files!');
- }
-
- //we can get the top folder:
- $top_folder = \Folder::findTopFolder($message->id, 'message');
-
- if($top_folder) {
- $file_system_api = new FileSystem();
- return $file_system_api->getFolder($top_folder->id);
- } else {
- $this->halt(404, 'Folder not found!');
- }
- }
-
-
- /**
- * Schreibt eine neue Nachricht.
- *
- * @post /messages
- */
- public function createMessage()
- {
- if (!mb_strlen($subject = trim($this->data['subject'] ?: ''))) {
- $this->error(400, 'No subject provided');
- }
-
- if (!mb_strlen($message = trim($this->data['message'] ?: ''))) {
- $this->error(400, 'No message provided');
- }
-
- $recipients = (array) ($this->data['recipients'] ?: null);
- if (!sizeof($recipients)) {
- $this->error(400, 'No recipient(s) provided');
- }
-
- $usernames = array_map(function ($id) { $user = \User::find($id); return @$user['username']; }, $recipients);
-
- if (sizeof($usernames) !== sizeof(array_filter($usernames))) {
- $this->error(400, "Some recipients do not exist.");
- }
-
- $message = \Message::send($GLOBALS['user']->id, $usernames, $subject, $message);
- if (!$message) {
- $this->error(500, 'Could not create message');
- }
-
- $this->redirect('message/' . $message->id, 201, "ok");
- }
-
-
- /**
- * Eine Nachricht als (un)gelesen markieren.
- *
- * @put /message/:message_id
- */
- public function updateMessage($message_id)
- {
-
- $message = $this->requireMessage($message_id);
- $user_id = $this->currentUser();
-
- if (isset($this->data['unread'])) {
- if ($this->data['unread']) {
- $message->markAsUnread($user_id);
- } else {
- $message->markAsRead($user_id);
- }
- }
-
- $this->halt(204);
- }
-
- /**
- * Löscht eine Nachricht.
- *
- * @delete /message/:message_id
- */
- public function destroyMessage($message_id)
- {
- $message = $this->requireMessage($message_id);
-
- $msgin = new \messaging();
- if (!$msgin->delete_message($message_id, self::currentUser(), true)) {
- $this->error(500);
- }
-
- $this->status(204);
- }
-
- /**************************************************/
- /* PRIVATE HELPER METHODS */
- /**************************************************/
-
- private static function currentUser()
- {
- return $GLOBALS['user']->id;
- }
-
- private function requireMessage($message_id)
- {
- if (!$message = \Message::find($message_id)) {
- $this->notFound("Message not found");
- }
-
- $current_user = self::currentUser();
- $message_user = $message->originator->user_id === $current_user
- ? $message->originator
- : $message->receivers->findOneBy('user_id', $current_user);
-
- if (!$message_user) {
- $this->error(401);
- }
-
- if ($message_user->deleted) {
- $this->notFound("Message not found");
- }
-
- return $message;
- }
-
- private function messageToJSON($message)
- {
- $user_id = self::currentUser();
-
- $my_mu = $message->receivers->filter(function ($mu) use ($user_id) {
- return $mu->user_id === $user_id;
- });
- if ($message->originator->user_id === $user_id) {
- $my_mu[] = $message->originator;
- }
-
- $my_roles = [
- 'snd' => $message->autor_id === $user_id,
- 'rec' => in_array('rec', $my_mu->pluck('snd_rec')),
- ];
-
- $json = $message->toArray(words('message_id subject message mkdate priority'));
-
- // formatted message
- $json['message_html'] = formatReady($json['message']) ?: '';
-
- // Tags
- $json['tags'] = $message->getTags($user_id);
-
- // sender
- $sender = $message->getSender();
- $json['sender'] = $this->urlf('/user/%s', [$message->author->id]);
-
- // recipients
- if ($my_roles['snd']) {
- $json['recipients'] = [];
- foreach ($message->getRecipients() as $r) {
- $json['recipients'][] = $this->urlf('/user/%s', [$r->user_id]);
- }
- } else {
- $json['recipients'] = [$this->urlf('/user/%s', [$user_id])];
- }
-
- // attachments
- if ($message->attachment_folder && count($message->attachment_folder->file_refs) > 0) {
- $json['attachments'] = [];
- foreach ($message->attachment_folder->file_refs as $ref) {
- $json['attachments'][] = $this->urlf('/file/%s', [$ref->id]);
- }
- }
-
- // unread only if in inbox
- if ($my_roles['rec']) {
- foreach ($my_mu as $mu) {
- if ($mu->snd_rec === 'rec') {
- $json['unread'] = !$mu->readed;
- break;
- }
- }
- }
-
- return $json;
- }
-
- private function countMessages($user_id, $box)
- {
- $condition = 'user_id = ? AND snd_rec = ? AND deleted = 0';
- $params = [$user_id, $box === 'inbox' ? 'rec' : 'snd'];
-
- $total = \MessageUser::countBySQL($condition, $params);
- $unread = \MessageUser::countBySQL(
- $condition . ' AND readed = 0',
- $params
- );
-
- return compact('total', 'unread');
- }
-
- private function getMessageIds($user_id, $box)
- {
- return \MessageUser::findAndMapBySQL(function ($row) {
- return $row->message_id;
- }, 'user_id = ? AND snd_rec = ? AND deleted = 0 ORDER BY mkdate DESC', [
- $user_id, $box === 'inbox' ? 'rec' : 'snd'
- ]);
- }
-
-}
diff --git a/app/routes/News.php b/app/routes/News.php
deleted file mode 100644
index c9b258b..0000000
--- a/app/routes/News.php
+++ /dev/null
@@ -1,375 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition news_id ^[0-9a-f]{1,32}$
- * @condition course_id ^[0-9a-f]{1,32}$
- * @condition user_id ^[0-9a-f]{1,32}$
- * @condition comment_id ^[0-9a-f]{1,32}$
- */
-class News extends \RESTAPI\RouteMap
-{
- public static function before()
- {
- require_once 'lib/models/StudipNews.class.php';
- }
-
- /**
- * Globale News auslesen
- *
- * @get /studip/news
- */
- public function getGlobalNews()
- {
- list($json, $total) = $this->getRangedNews('studip');
-
- $this->etag(md5(serialize($json)));
- return $this->paginated($json, $total);
- }
-
- /**
- * News einer Veranstaltung auslesen
- *
- * @get /course/:course_id/news
- */
- public function getCourseNews($course_id)
- {
- list($json, $total) = $this->getRangedNews($course_id);
-
- $this->etag(md5(serialize($json)));
- return $this->paginated($json, $total, compact('course_id'));
- }
-
- /**
- * News eines Nutzers auslesen
- *
- * @get /user/:user_id/news
- */
- public function getUserNews($user_id)
- {
- list($json, $total) = $this->getRangedNews($user_id);
-
- $this->etag(md5(serialize($json)));
- return $this->paginated($json, $total, compact('user_id'));
- }
-
-
- /**
- * News auslesen
- *
- * @get /news/:news_id
- */
- public function getNews($news_id)
- {
- $news = $this->requireNews($news_id);
- $news_json = $this->newsToJson($news);
-
- $this->lastmodified($news->chdate);
- $this->expires($news->expire);
- $this->etag(md5(serialize($news_json)));
-
- return $news_json;
- }
-
- /**
- * News löschen
- *
- * @delete /news/:news_id
- */
- public function destroyNews($news_id)
- {
- $news = $this->requireNews($news_id);
-
- if (!$news->havePermission('delete', '', $GLOBALS['user']->id)) {
- $this->error(401);
- }
-
- $news->delete();
- $this->status(204);
- }
-
-
- /**
- * News updaten
- *
- * @put /news/:news_id
- */
- public function updateNews($news_id)
- {
- $news = $this->requireNews($news_id);
- if (!$news->havePermission('edit', '', $GLOBALS['user']->id)) {
- $this->error(401);
- }
-
- if (isset($this->data['topic'])) {
- if (!mb_strlen(trim($topic = $this->data['topic']))) {
- $this->error(400, 'Topic must not be empty.');
- }
- $news->topic = $topic;
- }
-
- if (isset($this->data['body'])) {
- if (!mb_strlen(trim($body = $this->data['body']))) {
- $this->error(400, 'Body must not be empty.');
- }
- $news->body = $body;
- }
-
- if (isset($this->data['expire'])) {
- $news->expire = (int) $this->data['expire'];
- }
-
- if (isset($this->data['allow_comments'])) {
- $news->allow_comments = (int) $this->data['allow_comments'];
- }
-
- $news->chdate_uid = $GLOBALS['user']->id;
-
- if (!$news->store()) {
- $this->error(500, 'Could not update news');
-
- }
- $this->status(204);
- }
-
- /**
- * News anlegen
- *
- * @post /course/:course_id/news
- * @post /user/:user_id/news
- * @post /studip/news
- */
- public function createNews($range_id = 'studip')
- {
-
- if (!\StudipNews::haveRangePermission('edit', $range_id, $GLOBALS['user']->id)) {
- $this->error(401, "Not authorized to create a news here.");
- }
-
- $news = new \StudipNews();
- $news->setData([
- 'user_id' => $GLOBALS['user']->id,
- 'author' => $GLOBALS['user']->getFullName(),
- 'topic' => trim(@$this->data['topic']),
- 'body' => trim(@$this->data['body']),
- 'date' => time(),
- 'expire' => isset($this->data['expire']) ? intval($this->data['expire']) : 2 * 7 * 24 * 60 * 60,
- 'allow_comments' => isset($this->data['allow_comments']) ? intval($this->data['allow_comments']) : 0
- ]);
- $news->addRange($range_id);
-
- if ($errors = $this->validateNews($news)) {
- $this->error(400, compact('errors'));
- }
-
- if (!$news->store()) {
- $this->error(500);
- }
-
- $news->storeRanges();
-
- $this->redirect('news/' . $news->id, 201, "ok");
- }
-
- /**
- * News-Comments auslesen
- *
- * @get /news/:news_id/comments
- */
- public function getNewsComments($news_id)
- {
- $comments = $this->requireNews($news_id)->comments->orderBy("mkdate asc");
-
- $total = count($comments);
- $json = [];
- foreach ($comments->limit($this->offset, $this->limit) as $comment) {
- $tmp = $comment->toArray("comment_id object_id user_id content mkdate chdate");
- $tmp['content_html'] = htmlReady($comment->content);
- $json[$this->urlf('/comment/%s', [htmlReady($comment->id)])] = $tmp;
- }
-
- $this->etag(md5(serialize($json)));
-
- return $this->paginated($json, $total, compact('news_id'));
- }
-
- /**
- * News-Comment auslesen
- *
- * @get /comment/:comment_id
- */
- public function getComment($comment_id)
- {
- $comment = $this->requireComment($comment_id);
- $comment_json = $this->commentToJson($comment);
-
- $this->lastmodified($comment->chdate);
- $this->etag(md5(serialize($comment_json)));
-
- return $comment_json;
- }
-
- /**
- * News-Comment anlegen
- *
- * @post /news/:news_id/comments
- */
- public function appendComment($news_id)
- {
- $news = $this->requireNews($news_id);
-
- if (!$news->allow_comments) {
- $this->error(409, 'Comments are not allowed');
- }
-
- if (!isset($this->data['content']) || !mb_strlen($content = trim($this->data['content']))) {
- $this->error(400, 'Content required.');
- }
-
- $comment = new \StudipComment();
- $comment->setData(
- [
- 'object_id' => $news_id,
- 'user_id' => $GLOBALS['user']->id,
- 'content' => $content
- ]);
-
- if (!$comment->store()) {
- $this->halt(500, 'Could not create comment.');
- }
-
- $this->redirect('comment/' . $comment->id, 201, "ok");
- }
-
- /**
- * News-Comment löschen
- *
- * @delete /comment/:comment_id
- */
- public function destroyComment($comment_id)
- {
- $comment = $this->requireComment($comment_id);
-
- if (!$comment->delete()) {
- $this->error(500, 'Comment could not be deleted.');
- }
-
- $this->halt(204);
- }
-
-
- /**************************************************/
- /* PRIVATE HELPER METHODS */
- /**************************************************/
-
- private function getRangedNews($range_id)
- {
-
- $news = \StudipNews::getNewsByRange($range_id, true, true);
-
- if (!self::checkRangePermission($range_id, $GLOBALS['user']->id)) {
- $this->error(401);
- }
-
- $total = count($news);
- $news = array_slice($news, $this->offset, $this->limit);
-
- $json = [];
- foreach ($news as $n) {
- $json[$this->urlf('/news/%s', [$n->id])] = $this->newsToJson($n);
- }
-
- return [$json, $total];
- }
-
- private function validateNews($news)
- {
- $errors = [];
-
- $retain = $_SESSION['messages'];
- $_SESSION['messages'] = [];
-
- if (!$news->validate()) {
- foreach ($_SESSION['messages'] as $message_box) {
- $errors[] = $message_box->message;
- }
- }
-
- $_SESSION['messages'] = $retain;
- return $errors;
- }
-
- private static function checkRangePermission($range_id, $user_id)
- {
- return \StudipNews::haveRangePermission('view', $range_id, $user_id);
- }
-
-
- private function requireNews($id)
- {
- if (!$news = \StudipNews::find($id)) {
- $this->notFound("News not found");
- }
-
- if (!$news->havePermission('view', '', $GLOBALS['user']->id)) {
- $this->error(401);
- }
-
- return $news;
- }
-
- private function newsToJson($news)
- {
- $json = $news->toArray(words("news_id topic body date user_id expire allow_comments chdate chdate_uid mkdate"));
-
- $json['topic'] = (string) $news->topic;
- $json['body_html'] = formatReady((string) $news->body);
- $json['chdate_uid'] = trim($json['chdate_uid']);
-
- if ($news->allow_comments) {
- $json['comments'] = $this->urlf('/news/%s/comments', [$news->id]);
- $json['comments_count'] = sizeof($news->comments);
- }
-
- $json['ranges'] = [];
- foreach ($news->news_ranges as $range) {
- if (self::checkRangePermission($range->range_id, $GLOBALS['user']->id)) {
- switch ($range->type) {
- case 'global': $url = $this->url('/studip/news'); break;
- case 'sem': $url = $this->urlf('/course/%s/news', [$range->range_id]); break;
- case 'user': $url = $this->urlf('/user/%s/news', [$range->range_id]); break;
- case 'inst': $url = $this->urlf('/TODO/%s/news', [$range->range_id]); break;
- case 'fak': $url = $this->urlf('/TODO/%s/news', [$range->range_id]); break;
- }
-
- $json['ranges'][] = $url;
- }
- }
- return $json;
- }
-
- private function requireComment($id)
- {
- if (!$comment = \StudipComment::find($id)) {
- $this->notFound("Comment not found");
- }
- if (!$comment->news->havePermission('view', '', $GLOBALS['user']->id)) {
- $this->error(401);
- }
-
- return $comment;
- }
-
- private function commentToJson($comment)
- {
- $json = $comment->toArray(words("comment_id mkdate chdate content"));
- $json['content_html'] = formatReady($json['content']);
- $json['author'] = $this->urlf('/user/%s', [$comment->user_id]);
- $json['news'] = $this->urlf('/news/%s', [$comment->object_id]);
- return $json;
- }
-}
diff --git a/app/routes/ResourceBooking.php b/app/routes/ResourceBooking.php
deleted file mode 100644
index a5d027f..0000000
--- a/app/routes/ResourceBooking.php
+++ /dev/null
@@ -1,192 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * This file contains the REST class for the
- * room and resource management system.
- *
- * @author Moritz Strohm <strohm@data-quest.de>
- * @copyright 2017-2019
- * @license http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
- * @since 4.5
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class ResourceBooking extends \RESTAPI\RouteMap
-{
-
- /**
- * Helper method that either returns the specified data
- * or simply an empty string in case that no request result
- * is requested.
- */
- protected function sendReturnData($data)
- {
- if (\Request::submitted('quiet')) {
- //Return nothing.
- return '';
- }
-
- //Return data.
- return $data;
- }
-
-
- /**
- * Moves a resource booking, if permitted.
- *
- * @post /resources/booking/:booking_id/move
- */
- public function move($booking_id)
- {
- $booking = \ResourceBooking::find($booking_id);
- if (!$booking) {
- $this->notFound('Resource booking object not found!');
- }
-
- $current_user = \User::findCurrent();
-
- if ($booking->isReadOnlyForUser($current_user)) {
- throw new \AccessDeniedException();
- }
-
- $resource_id = \Request::get('resource_id');
- $begin_str = \Request::get('begin');
- $end_str = \Request::get('end');
- $interval_id = \Request::get('interval_id');
-
- //Try the ISO format first: YYYY-MM-DDTHH:MM:SS±ZZ:ZZ
- $begin = \DateTime::createFromFormat(\DateTime::RFC3339, $begin_str);
- $end = \DateTime::createFromFormat(\DateTime::RFC3339, $end_str);
- if (!($begin instanceof \DateTime) || !($end instanceof \DateTime)) {
- $tz = new \DateTime();
- $tz = $tz->getTimezone();
- //Try the ISO format without timezone:
- $begin = \DateTime::createFromFormat('Y-m-d\TH:i:s', $begin_str, $tz);
- $end = \DateTime::createFromFormat('Y-m-d\TH:i:s', $end_str, $tz);
- }
-
- //Check if a specific interval has been moved:
- if ($interval_id) {
- $interval = \ResourceBookingInterval::findOneBySql(
- 'interval_id = :interval_id AND booking_id = :booking_id',
- [
- 'interval_id' => $interval_id,
- 'booking_id' => $booking->id
- ]
- );
- if (!$interval) {
- $this->notFound('Resource booking interval not found!');
- }
- $interval_begin = new \DateTime();
- $interval_begin->setTimestamp($interval->begin);
- $interval_end = new \DateTime();
- $interval_end->setTimestamp($interval->end);
-
- //Calculate the difference from the interval time range
- //to the time range from the request. That difference
- //is then applied to the booking.
- $begin_diff = $interval_begin->diff($begin);
- $end_diff = $interval_end->diff($end);
-
- $new_booking_begin = new \DateTime();
- $new_booking_begin->setTimestamp($booking->begin);
- $new_booking_end = new \DateTime();
- $new_booking_end->setTimestamp($booking->end);
-
- $new_booking_begin = $new_booking_begin->add($begin_diff);
- $new_booking_end = $new_booking_end->add($end_diff);
- //We must substract the preparation time to the begin timestamp
- //to get the real begin:
- $real_begin = clone $new_booking_begin;
- if ($booking->preparation_time > 0) {
- $real_begin->sub(new \DateInterval('PT' . ($booking->preparation_time / 60 ) . 'M'));
- }
- $booking->begin = $real_begin->getTimestamp();
- $booking->end = $new_booking_end->getTimestamp();
- } else {
- //We must substract the preparation time to the begin timestamp
- //to get the real begin:
- $real_begin = clone $begin;
- if ($booking->preparation_time > 0) {
- $real_begin->sub(new \DateInterval('PT' . ($booking->preparation_time / 60 ) . 'M'));
- }
- $booking->begin = $real_begin->getTimestamp();
- $booking->end = $end->getTimestamp();
- }
- if ($resource_id) {
- //The resource-ID has changed:
- //The booking was moved from one resource to another.
- $booking->resource_id = $resource_id;
- }
-
- //Update the booking_user_id field:
- $booking->booking_user_id = \User::findCurrent()->id;
-
- try {
- $booking->store();
- return $this->sendReturnData($booking->toRawArray());
- } catch (\Exception $e) {
- $this->halt(500, $e->getMessage());
- }
- }
-
-
- /**
- * Retrieves the intervals of the resource booking.
- * These can be filtered by a time range.
- *
- * @get /resources/booking/:booking_id/intervals
- */
- public function getIntervals($booking_id)
- {
- $booking = \ResourceBooking::find($booking_id);
- if (!$booking) {
- $this->notFound('Resource booking object not found!');
- }
-
- $current_user = \User::findCurrent();
-
- $resource = $booking->resource->getDerivedClassInstance();
- if (!$resource->bookingPlanVisibleForUser($current_user)) {
- throw new \AccessDeniedException();
- }
-
- //Get begin and end:
- $begin_str = \Request::get('begin');
- $end_str = \Request::get('end');
- $begin = null;
- $end = null;
- if ($begin_str && $end_str) {
- //Try the ISO format first: YYYY-MM-DDTHH:MM:SS±ZZ:ZZ
- $begin = \DateTime::createFromFormat(\DateTime::RFC3339, $begin_str);
- $end = \DateTime::createFromFormat(\DateTime::RFC3339, $end_str);
- if (!($begin instanceof \DateTime) || !($end instanceof \DateTime)) {
- $tz = new \DateTime();
- $tz = $tz->getTimezone();
- //Try the ISO format without timezone:
- $begin = \DateTime::createFromFormat('Y-m-d\TH:i:s', $begin_str, $tz);
- $end = \DateTime::createFromFormat('Y-m-d\TH:i:s', $end_str, $tz);
- }
- }
-
- $sql = "booking_id = :booking_id ";
- $sql_data = ['booking_id' => $booking->id];
- if (($begin instanceof \DateTime) && ($end instanceof \DateTime)) {
- $sql .= "AND begin >= :begin AND end <= :end ";
- $sql_data['begin'] = $begin->getTimestamp();
- $sql_data['end'] = $end->getTimestamp();
- }
- if (\Request::submitted('exclude_cancelled_intervals')) {
- $sql .= "AND takes_place = '1' ";
- }
- $sql .= "ORDER BY begin ASC, end ASC";
- $intervals = \ResourceBookingInterval::findBySql($sql, $sql_data);
-
- $result = [];
- foreach ($intervals as $interval) {
- $result[] = $interval->toRawArray();
- }
-
- return $result;
- }
-}
diff --git a/app/routes/ResourceCategories.php b/app/routes/ResourceCategories.php
deleted file mode 100644
index bdd3d15..0000000
--- a/app/routes/ResourceCategories.php
+++ /dev/null
@@ -1,349 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * This file contains API routes related to ResourceCategory objects.
- *
- * @author Moritz Strohm <strohm@data-quest.de>
- * @copyright 2017-2019
- * @license http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
- * @since 4.5
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class ResourceCategories extends \RESTAPI\RouteMap
-{
- /**
- * Validate access to each route.
- */
- public function before()
- {
- if (!\ResourceManager::userHasGlobalPermission(\User::findCurrent(), 'admin')) {
- throw new \AccessDeniedException();
- }
- }
-
- /**
- * Returns all defined resource categories.
- *
- * @get /resources/categories
- */
- public function getAllResourceCategories()
- {
- return \ResourceCategory::findAndMapBySql(
- function (\ResourceCategory $category) {
- return $category->toRawArray();
- },
- 'TRUE ORDER BY name ASC'
- );
- }
-
-
- /**
- * Get a resource category object.
- *
- * @get /resources/category/:category_id
- */
- public function getResourceCategory($category_id)
- {
- $category = \ResourceCategory::find($category_id);
- if (!$category) {
- $this->notFound('ResourceCategory object not found!');
- }
-
- return $category->toRawArray();
- }
-
-
- /**
- * Creates a resource category object.
- *
- * @post /resources/new_category
- */
- public function addResourceCategory()
- {
- $name = \Request::get('name');
- $description = \Request::get('description');
- $class_name = \Request::get('class_name');
- $iconnr = \Request::int('iconnr');
-
- $properties_name = \Request::getArray('properties_name');
- $properties_type = \Request::getArray('properties_type');
- $properties_requestable = \Request::getArray('properties_requestable');
- $properties_protected = \Request::getArray('properties_protected');
-
- $set_properties = [];
- foreach ($properties_name as $key => $property_name) {
- $set_properties[] = [
- 'name' => $property_name,
- 'type' => $properties_type[$key],
- 'requestable' => $properties_requestable[$key],
- 'protected' => $properties_protected[$key]
- ];
- }
-
- //validation:
- if (!$name) {
- $this->halt(
- 400,
- _('Der Name der Kategorie ist leer!')
- );
- }
-
- if (!is_a($class_name, 'Resource', true)) {
- $this->halt(
- 400,
- _('Es wurde keine gültige Ressourcen-Datenklasse ausgewählt!')
- );
- }
-
- switch ($class_name) {
- case 'Location':
- $category = \ResourceManager::createLocationCategory(
- $name,
- $description
- );
- break;
- case 'Building':
- $category = \ResourceManager::createBuildingCategory(
- $name,
- $description
- );
- break;
- case 'Room':
- $category = \ResourceManager::createRoomCategory(
- $name,
- $description
- );
- break;
- default:
- $category = \ResourceManager::createCategory(
- $name,
- $description,
- $class_name,
- false,
- $iconnr
- );
- }
-
- if ($category->store() === false) {
- $this->halt(
- 500,
- _('Fehler beim Speichern der Kategorie!')
- );
- }
-
- //After we have stored the category we must store
- //the properties or create them, if necessary:
-
- foreach ($set_properties as $set_property) {
- $category->addProperty(
- $set_property['name'],
- $set_property['type'],
- $set_property['requestable'],
- $set_property['protected']
- );
- }
-
- return $category->toRawArray();
- }
-
- /**
- * Modifies a resource category.
- *
- * @put /resources/category/:category_id
- */
- public function editResourceCategory($category_id)
- {
- $category = \ResourceCategory::find($category_id);
- if (!$category) {
- $this->notFound('ResourceCategory object not found!');
- }
-
- if ($category->system) {
- $this->halt(403, 'System categories must not be modified!');
- return;
- }
-
- $name = $this->data['name'];
- $description = $this->data['description'];
- $iconnr = intval($this->data['iconnr']);
-
- //validation:
- if ($name) {
- $category->name = $name;
- }
- if ($description) {
- $category->description = $description;
- }
- if ($iconnr) {
- $category->iconnr = $iconnr;
- }
-
- if ($category->store() === false) {
- $this->halt(
- 500,
- 'Error while saving the category!'
- );
- }
-
- return $category->toRawArray();
- }
-
-
- /**
- * Deletes a resource category.
- *
- * @delete /resources/category/:category_id
- */
- public function deleteResourceCategory($category_id)
- {
- $category = \ResourceCategory::find($category_id);
- if (!$category) {
- $this->notFound('ResourceCategory object not found!');
- }
-
- if ($category->system) {
- $this->halt(403,'System resource categories must not be deleted!');
- return;
- }
-
- if ($category->delete()) {
- return 'OK';
- } else {
- $this->halt(
- 500,
- 'Error while deleting the resource category!'
- );
- }
- }
-
-
- /**
- * Get all resource category property objects for a resource category.
- *
- * @get /resources/category/:category_id/properties
- */
- public function getResourceCategoryProperties($category_id)
- {
- $category = \ResourceCategory::find($category_id);
- if (!$category) {
- $this->notFound('ResourceCategory object not found!');
- }
-
- $result = [];
- $properties = \ResourceCategoryProperty::findBySql(
- 'INNER JOIN resource_property_definitions rpd
- USING (property_id)
- WHERE category_id = :category_id ORDER BY rpd.name ASC',
- [
- 'category_id' => $category->id
- ]
- );
-
- if ($properties) {
- foreach ($properties as $property) {
- $data = $property->toRawArray();
- $data['name'] = $property->definition->name;
- $data['type'] = $property->definition->type;
- $result[] = $data;
- }
- }
-
- return $result;
- }
-
-
- /**
- * Returns all resources which belong to the specified category.
- * The result set can be limited by the parameters 'offset' and 'limit'.
- * If the parameter 'with_full_name' is set to 1, the resources full name
- * as provided by its responsible class, is added to the result set.
- *
- * @get /resources/category/:category_id/resources
- */
- public function getResourceCategoryResources($category_id)
- {
- $category = \ResourceCategory::find($category_id);
- if (!$category) {
- $this->notFound('ResourceCategory object not found!');
- }
-
- $offset = \Request::int('offset');
- $limit = \Request::int('limit');
- $with_full_name = \Request::get('with_full_name');
-
- $result = [];
-
- $sql = 'category_id = :category_id ORDER BY name ASC ';
- $sql_array = ['category_id' => $category->id];
-
- if ($limit > 0) {
- $sql .= 'limit :limit ';
- $sql_array['limit'] = $limit;
- if ($offset > 0) {
- $sql .= 'offset :offset ';
- $sql_array['offset'] = $offset;
- }
- }
-
- $resources = \Resource::findBySql($sql, $sql_array);
-
- if ($resources) {
- foreach ($resources as $r) {
- if ($with_full_name) {
- $r = $r->getDerivedClassInstance();
- $data = $r->toRawArray();
- $data['full_name'] = $r->getFullName();
- $result[] = $data;
- } else {
- $result[] = $r->toRawArray();
- }
- }
- }
-
- return $result;
- }
-
-
- /**
- * Creates a resource.
- *
- * @post /resources/category/:category_id/create_resource
- */
- public function createResource($category_id)
- {
- $category = \ResourceCategory::find($category_id);
- if (!$category) {
- $this->notFound('ResourceCategory object not found!');
- }
-
-
- $name = \Request::get('name');
- $description = \Request::get('description');
- $parent_id = \Request::get('parent_id');
- $properties = \Request::getArray('properties');
-
- if (!$name) {
- $this->halt(
- 400,
- 'The parameter \'name\' is not set!'
- );
- }
-
- try {
- $resource = $category->createResource(
- $name,
- $description,
- $parent_id,
- $properties
- );
-
- return $resource;
- } catch (\Exception $e) {
- $this->halt(
- 400,
- $e->getMessage()
- );
- }
- }
-}
diff --git a/app/routes/ResourcePermissions.php b/app/routes/ResourcePermissions.php
deleted file mode 100644
index be5c647..0000000
--- a/app/routes/ResourcePermissions.php
+++ /dev/null
@@ -1,585 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * This file contains API routes related to ResourcePermission
- * and ResourceTemporaryPermission objects.
- *
- * @author Moritz Strohm <strohm@data-quest.de>
- * @copyright 2017-2019
- * @license http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
- * @since 4.5
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class ResourcePermissions extends \RESTAPI\RouteMap
-{
-
- //Methods for permanent permissions:
-
-
- /**
- * Get the permission levels of users for the specified resource.
- *
- * @param levels: Limit the result set to the specified permission levels.
- * Allowed permission levels: user, autor, tutor, admin.
- * The permission levels have to be comma separated like in the
- * following example: "autor,tutor,admin".
- *
- * @get /resources/permissions/:resource_id
- */
- public function getResourcePermissions($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'admin')) {
- throw new \AccessDeniedException();
- }
-
- $levels_str = \Request::get('levels');
- $levels = [];
- if ($levels_str) {
- $levels = explode(',', $levels_str);
- }
-
- $sql = 'resource_id = :resource_id ';
- $sql_array = [
- 'resource_id' => $resource->id
- ];
-
- if ($levels) {
- $sql .= 'AND perms IN ( :levels ) ';
- $sql_array['levels'] = $levels;
- }
-
- $permissions = \ResourcePermission::findBySql($sql, $sql_array);
-
- $result = [];
- if ($permissions) {
- foreach ($permissions as $permission) {
- $result[] = $permission->toRawArray();
- }
- }
-
- return $result;
- }
-
-
- /**
- * Returns the permissions a specific user has on a specified resource.
- *
- * @get /resources/permissions/:resource_id/:user:_id
- */
- public function getPermission($resource_id, $user_id)
- {
- if ($resource_id !== 'global') {
- if (!\Resource::exists($resource_id)) {
- $this->halt(
- 404,
- 'Resource not found!'
- );
- }
- }
-
- $user = \User::find($user_id);
- if (!$user) {
- $this->halt(
- 400,
- 'No user was provided!'
- );
- }
-
- $current_user = \User::findCurrent();
-
- if (!\ResourceManager::userHasGlobalPermission($current_user, 'admin')) {
- if ($resource_id !== 'global') {
- $resource = \Resource::find($resource_id);
- $resource = $resource->getDerivedClassInstance();
- if (!$resource->userHasPermission($current_user, 'admin')) {
- $this->halt(403);
- }
- } else {
- //$resource_id == 'global': One must be admin
- //to perform this action!
- $this->halt(403);
- }
- }
-
- $permission = \ResourcePermission::findOneBySql(
- "resource_id = :resource_id AND user_id = :user_id",
- [
- 'resource_id' => $resource_id,
- 'user_id' => $user->id
- ]
- );
-
- if ($permission) {
- return $permission->toRawArray();
- } else {
- //The user already had no global permissions!
- return NULL;
- }
- }
-
-
- /**
- * @post /resources/permissions/:resource_id/:user_id
- */
- public function setPermission($resource_id, $user_id)
- {
- if ($resource_id !== 'global') {
- if (!\Resource::exists($resource_id)) {
- $this->halt(
- 404,
- 'Resource not found!'
- );
- return;
- }
- }
-
- $user = \User::find($user_id);
- if (!$user) {
- $this->halt(
- 400,
- 'No user was provided!'
- );
- }
-
- $current_user = \User::findCurrent();
-
- if (!\ResourceManager::userHasGlobalPermission($current_user, 'admin')) {
- if ($resource_id !== 'global') {
- $resource = \Resource::find($resource_id);
- $resource = $resource->getDerivedClassInstance();
- if (!$resource->userHasPermission($current_user, 'admin')) {
- $this->halt(403);
- }
- } else {
- //$resource_id == 'global': One must be admin
- //to perform this action!
- $this->halt(403);
- }
- }
-
- //Verify permission level:
- $perms = \Request::get('perms');
-
- if (!in_array($perms, ['user', 'autor', 'tutor', 'admin'])) {
- $this->halt(
- 400,
- 'Invalid permission level specified!'
- );
- }
-
- //Check if permissions are already present for the user.
- //If not, create a new permission object.
- $permission = \ResourcePermission::findOneBySql(
- "resource_id = :resource_id AND user_id = :user_id",
- [
- 'resource_id' => $resource_id,
- 'user_id' => $user->id
- ]
- );
-
- if (!$permission) {
- $permission = new \ResourcePermission();
- $permission->resource_id = $resource_id;
- $permission->user_id = $user->id;
- }
-
- $permission->perms = $perms;
-
- if ($permission->store() === false) {
- $this->halt(
- 500,
- 'Error while saving permissions!'
- );
- }
-
- return $permission->toRawArray();
- }
-
-
- /**
- * @delete /resources/permissions/:resource_id/:user_id
- */
- public function deletePermission($resource_id, $user_id)
- {
- if ($resource_id !== 'global' && !\Resource::exists($resource_id)) {
- $this->notFound('Resource not found!');
- }
-
- $user = \User::find($user_id);
- if (!$user) {
- $this->halt(
- 400,
- 'No user was provided!'
- );
- }
-
- $current_user = \User::findCurrent();
-
- if (!\ResourceManager::userHasGlobalPermission($current_user, 'admin')) {
- if ($resource_id !== 'global') {
- $resource = \Resource::find($resource_id);
- $resource = $resource->getDerivedClassInstance();
- if (!$resource->userHasPermission($current_user, 'admin')) {
- $this->halt(403);
- }
- } else {
- //$resource_id == 'global': One must be admin
- //to perform this action!
- $this->halt(403);
- }
- }
-
- $permission = \ResourcePermission::findOneBySql(
- "resource_id = :resource_id AND user_id = :user_id",
- [
- 'resource_id' => $resource_id,
- 'user_id' => $user->id
- ]
- );
-
- if (!$permission) {
- //The user already had no global permissions!
- return 'OK';
- }
-
- if ($permission->delete()) {
- return 'OK';
- } else {
- $this->halt(
- 500,
- 'Error while deleting global permissions!'
- );
- }
- }
-
-
- //Methods for temporary permissions:
-
-
- /**
- * Get the temporary permission levels of users for the specified resource.
- * The begin and end parameters are mandatory to determine a time range
- * to collect the temporary permissions in that range.
- *
- * @param begin: The begin timestamp of the time range.
- * @param end: The end timestamp of the time range.
- * @param levels: Limit the result set to the specified temporary permission
- * levels. Allowed permission levels: user, autor, tutor, admin.
- * The permission levels have to be comma separated like in the
- * following example: "autor,tutor,admin".
- *
- * @get /resources/temporary_permissions/:resource_id
- */
- public function getTemporaryResourcePermissions($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'admin')) {
- throw new \AccessDeniedException();
- }
-
- $begin = \Request::get('begin');
- $end = \Request::get('end');
- $levels_str = \Request::get('levels');
- $levels = [];
- if ($levels_str) {
- $levels = explode(',', $levels_str);
- }
-
- if (!$begin or !$end) {
- //Use the current day:
- $begin = strtotime('today 0:00:00');
- $end = strtotime('today 23:59:59');
- }
-
- $sql = 'resource_id = :resource_id
- AND
- ((begin >= :begin AND begin <= :end)
- OR
- (end >= :begin AND end <= :end))
- OR
- (begin < :begin AND end > :end)';
- $sql_array = [
- 'resource_id' => $resource->id,
- 'begin' => $begin,
- 'end' => $end
- ];
-
- if ($levels) {
- $sql .= 'AND perms IN ( :levels ) ';
- $sql_array['levels'] = $levels;
- }
-
- return \ResourceTemporaryPermission::findAndMapBySql(
- function (\ResourceTemporaryPermission $permission) {
- return $permission->toRawArray();
- },
- $sql,
- $sql_array
- );
- }
-
-
- /**
- * Returns the permissions a specific user has on a specified resource.
- *
- * @get /resources/temporary_permissions/:resource_id/:user:_id
- */
- public function getTemporaryPermission($resource_id, $user_id)
- {
- if ($resource_id !== 'global') {
- if (!\Resource::exists($resource_id)) {
- $this->notFound('Resource not found!');
- }
- }
-
- $user = \User::find($user_id);
- if (!$user) {
- $this->halt(
- 400,
- 'No user was provided!'
- );
- }
-
- $current_user = \User::findCurrent();
-
- $begin_str = \Request::get('begin');
- $end_str = \Request::get('end');
- $begin = null;
- $end = null;
- $with_time_range = false;
- if ($begin_str && $end_str) {
- $with_time_range = true;
- $begin = new \DateTime();
- $begin->setTimestamp($begin_str);
- $end = new \DateTime();
- $end->setTimestamp($end_str);
- }
-
- if (!\ResourceManager::userHasGlobalPermission($current_user, 'admin')) {
- if ($resource_id !== 'global') {
- $resource = \Resource::find($resource_id);
- $resource = $resource->getDerivedClassInstance();
- if (!$resource->userHasPermission($current_user, 'admin')) {
- $this->halt(403);
- }
- } else {
- //$resource_id == 'global': One must be admin
- //to perform this action!
- $this->halt(403);
- }
- }
-
- $permissions = null;
- if ($with_time_range) {
- $permissions = \ResourceTemporaryPermission::findBySql(
- "resource_id = :resource_id AND user_id = :user_id
- AND (
- (begin >= :begin AND begin <= :end)
- OR
- (end >= :begin AND end <= :end)
- )",
- [
- 'resource_id' => $resource_id,
- 'user_id' => $user->id,
- 'begin' => $begin->getTimestamp(),
- 'end' => $end->getTimestamp()
- ]
- );
- } else {
- $permissions = \ResourceTemporaryPermission::findBySql(
- "resource_id = :resource_id AND user_id = :user_id",
- [
- 'resource_id' => $resource_id,
- 'user_id' => $user->id
- ]
- );
- }
-
- if ($permissions) {
- $result = [];
- foreach ($permissions as $permission) {
- $result[] = $permission->toRawArray();
- }
- return $result;
- } else {
- //The user already had no global permissions!
- return NULL;
- }
- }
-
-
- /**
- * Sets temporary permissions for a user.
- *
- * @param begin The begin timestamp for the temporary permisssion.
- * @param end The end timestamp for the temporary permission.
- * @param perms The permission level for the temporary permission.
- *
- * @post /resources/temporary_permissions/:resource_id/:user_id
- */
- public function setTemporaryPermission($resource_id, $user_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource not found!');
- }
-
- $user = \User::find($user_id);
- if (!$user) {
- $this->notFound('User not found!');
- }
-
- $current_user = \User::findCurrent();
-
- if (!\ResourceManager::userHasGlobalPermission($current_user, 'admin')
- && !$resource->userHasPermission($current_user, 'admin')) {
- $this->halt(403);
- }
-
- $begin_str = \Request::get('begin');
- $end_str = \Request::get('end');
- if (!$begin_str || !$end_str) {
- $this->halt(
- 400,
- 'No time range specified for temporary permission!'
- );
- }
-
- $begin = new \DateTime();
- $begin->setTimestamp($begin_str);
- $end = new \DateTime();
- $end->setTimestamp($end_str);
-
- //Verify permission level:
- $perms = \Request::get('perms');
-
- if (!in_array($perms, ['user', 'autor', 'tutor', 'admin'])) {
- $this->halt(
- 400,
- 'Invalid permission level specified!'
- );
- }
-
- //Check if permissions are already present for the user.
- //If not, create a new permission object.
- $permission = \ResourceTemporaryPermission::findOneBySql(
- "resource_id = :resource_id AND user_id = :user_id
- AND begin = :begin AND end = :end",
- [
- 'resource_id' => $resource_id,
- 'user_id' => $user->id,
- 'begin' => $begin->getTimestamp(),
- 'end' => $end->getTimestamp()
- ]
- );
-
- if (!$permission) {
- $permission = new \ResourceTemporaryPermission();
- $permission->resource_id = $resource_id;
- $permission->user_id = $user->id;
- $permission->begin = $begin->getTimestamp();
- $permission->end = $end->getTimestamp();
- }
-
- $permission->perms = $perms;
-
- if ($permission->store() === false) {
- $this->halt(
- 500,
- 'Error while saving permissions!'
- );
- }
-
- return $permission->toRawArray();
- }
-
-
- /**
- * Deletes all temporary permissions of a user.
- * If a time interval is given all permissions inside the interval
- * are deleted.
- *
- * @delete /resources/temporary_permissions/:resource_id/:user_id
- */
- public function deleteTemporaryPermission($resource_id, $user_id)
- {
- if ($resource_id !== 'global') {
- if (!\Resource::exists($resource_id)) {
- $this->notFound('Resource not found!');
- }
- }
-
- $user = \User::find($user_id);
- if (!$user) {
- $this->notFound('User not found!');
- }
-
- $current_user = \User::findCurrent();
-
- if (!\ResourceManager::userHasGlobalPermission($current_user, 'admin')) {
- if ($resource_id !== 'global') {
- $resource = \Resource::find($resource_id);
- $resource = $resource->getDerivedClassInstance();
- if (!$resource->userHasPermission($current_user, 'admin')) {
- $this->halt(403);
- }
- } else {
- //$resource_id == 'global': One must be admin
- //to perform this action!
- $this->halt(403);
- }
- }
-
- $begin_str = \Request::get('begin');
- $end_str = \Request::get('end');
- $begin = null;
- $end = null;
- $with_time_range = false;
- if ($begin_str and $end_str) {
- $with_time_range = true;
- $begin = new \DateTime();
- $begin->setTimestamp($begin_str);
- $end = new \DateTime();
- $end->setTimestamp($end_str);
- }
-
- if ($with_time_range) {
- \ResourceTemporaryPermission::deleteBySql(
- "resource_id = :resource_id AND user_id = :user_id
- AND (
- (begin >= :begin AND end <= :end)
- )",
- [
- 'resource_id' => $resource_id,
- 'user_id' => $user->id,
- 'begin' => $begin->getTimestamp(),
- 'end' => $end->getTimestamp()
- ]
- );
- } else {
- \ResourceTemporaryPermission::deleteBySql(
- "resource_id = :resource_id AND user_id = :user_id",
- [
- 'resource_id' => $resource_id,
- 'user_id' => $user->id
- ]
- );
- }
-
- return 'OK';
- }
-}
diff --git a/app/routes/ResourceProperties.php b/app/routes/ResourceProperties.php
deleted file mode 100644
index 2ddbbaf..0000000
--- a/app/routes/ResourceProperties.php
+++ /dev/null
@@ -1,224 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * This file contains API routes related to ResourceProperty objects.
- *
- * @author Moritz Strohm <strohm@data-quest.de>
- * @copyright 2017-2019
- * @license http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
- * @since 4.5
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class ResourceProperties extends \RESTAPI\RouteMap
-{
- /**
- * Validate access to each route.
- */
- public function before()
- {
- if (!\ResourceManager::userHasGlobalPermission(\User::findCurrent(), 'admin')) {
- throw new \AccessDeniedException();
- }
- }
-
- /**
- * Returns all resource property definitions.
- *
- * @get /resources/properties
- */
- public function getAllResourcePropertyDefinitions()
- {
- $properties = \ResourcePropertyDefinition::findBySql('TRUE ORDER BY name ASC');
-
- $result = [];
-
- if ($properties) {
- foreach ($properties as $p) {
- $result[] = $p->toRawArray();
- }
- }
-
- return $result;
- }
-
-
- /**
- * Creates a new resource property definition.
- *
- * @post /resources/add_property
- */
- public function addResourcePropertyDefinition()
- {
- $name = \Request::get('name');
- $description = \Request::i18n('description');
- $type = \Request::get('type');
- $write_permission_level = \Request::get('write_permission_level');
- $options = \Request::get('options', '');
- $range_search = \Request::bool('range_search');
-
- if (!$name) {
- $this->halt(
- 400,
- 'The field \'name\' must not be empty!'
- );
- }
- if (!in_array($type, \ResourcePropertyDefinition::getDefinedTypes())) {
- $this->halt(
- 400,
- 'Invalid property type specified!'
- );
- }
- if (!in_array($write_permission_level, ['user', 'autor', 'tutor', 'admin'])) {
- $this->halt(
- 400,
- 'Invalid permission level in field \'write_permission_level\'!'
- );
- }
-
- $property = new \ResourcePropertyDefinition();
- $property->name = $name;
- $property->description = $description;
- $property->type = $type;
- $property->options = $options ?: '';
- $property->range_search = $range_search;
- $property->write_permission_level = $write_permission_level;
-
- if (!$property->store()) {
- $this->halt(
- 500,
- 'Error while saving the property!'
- );
- }
- return $property->toRawArray();
- }
-
-
- /**
- * Get a resource property definition object.
- *
- * @get /resources/property/:property_id
- */
- public function getResourcePropertyDefinition($property_id)
- {
- $property = \ResourcePropertyDefinition::find($property_id);
- if (!$property) {
- $this->notFound('ResourcePropertyDefinition object not found!');
- }
-
- return $property->toRawArray();
- }
-
-
- /**
- * Modifies a resource property definition.
- *
- * @put /resources/property/:property_id
- */
- public function editResourcePropertyDefinition($property_id)
- {
- $property = \ResourcePropertyDefinition::find($property_id);
- if (!$property) {
- $this->notFound('ResourcePropertyDefinition object not found!');
- }
-
- if ($property->system) {
- $this->halt(
- 403,
- 'System properties must not be edited!'
- );
- }
-
- $name = $this->data['name'];
- $description = $this->data['description'];
- $type = $this->data['type'];
- $write_permission_level = $this->data['write_permission_level'];
- $options = $this->data['options'];
- $range_search = $this->data['range_search'];
-
- if ($name) {
- $property->name = $name;
- }
-
- if ($description) {
- $property->description = $description;
- }
-
- if ($type) {
- if (!in_array($type, \ResourcePropertyDefinition::getDefinedTypes())) {
- $this->halt(
- 400,
- 'Invalid property type specified!'
- );
- }
- $property->type = $type;
- }
-
- if ($write_permission_level) {
- if (!in_array($write_permission_level, ['user', 'autor', 'tutor', 'admin'])) {
- $this->halt(
- 400,
- 'Invalid permission level in field \'write_permission_level\'!'
- );
- }
- $property->write_permission_level = $write_permission_level;
- }
-
- if ($options) {
- $property->options = $options;
- }
-
- if ($range_search) {
- $property->range_search = $range_search;
- }
-
- if ($property->isDirty()) {
- if ($property->store()) {
- return $property->toRawArray();
- } else {
- $this->halt(
- 500,
- 'Error while saving the property!'
- );
- }
- }
-
- return $property->toRawArray();
- }
-
-
- /**
- * Deletes a resource property definition object.
- *
- * @delete /resources/property/:property_id
- */
- public function deleteResourcePropertyDefinition($property_id)
- {
- $property = \ResourcePropertyDefinition::find($property_id);
- if (!$property) {
- $this->notFound('ResourcePropertyDefinition object not found!');
- }
-
- if (!\ResourceManager::userHasGlobalPermission(\User::findCurrent(), 'admin')) {
- $this->halt(403);
- }
-
- //Check if the property is in use:
-
- if ($property->isInUse()) {
- $this->halt(
- 403,
- 'The property is in use and can therefore not be deleted!'
- );
- }
-
- if ($property->delete()) {
- return "OK";
- } else {
- $this->halt(
- 500,
- 'Error while deleting resource property definition!'
- );
- }
- }
-}
diff --git a/app/routes/ResourceRequest.php b/app/routes/ResourceRequest.php
deleted file mode 100644
index 24dfd2e..0000000
--- a/app/routes/ResourceRequest.php
+++ /dev/null
@@ -1,138 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * This file contains the REST class for resource requests from the
- * room and resource management system.
- *
- * @author Moritz Strohm <strohm@data-quest.de>
- * @copyright 2017-2019
- * @license http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
- * @since 4.5
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class ResourceRequest extends \RESTAPI\RouteMap
-{
-
- /**
- * Helper method that either returns the specified data
- * or simply an empty string in case that no request result
- * is requested.
- */
- protected function sendReturnData($data)
- {
- if (\Request::submitted('quiet')) {
- //Return nothing.
- return '';
- }
-
- //Return data.
- return $data;
- }
-
-
- /**
- * Moves a resource request, if permitted.
- *
- * @post /resources/request/:request_id/move
- */
- public function move($request_id)
- {
- $request = \ResourceRequest::find($request_id);
- if (!$request) {
- $this->notFound('Resource request object not found!');
- }
-
- $current_user = \User::findCurrent();
-
- if ($request->isReadOnlyForUser($current_user)) {
- throw new \AccessDeniedException();
- }
-
- $begin_str = \Request::get('begin');
- $end_str = \Request::get('end');
-
- //Try the ISO format first: YYYY-MM-DDTHH:MM:SS±ZZ:ZZ
- $begin = \DateTime::createFromFormat(\DateTime::RFC3339, $begin_str);
- $end = \DateTime::createFromFormat(\DateTime::RFC3339, $end_str);
- if (!($begin instanceof \DateTime) || !($end instanceof \DateTime)) {
- $tz = new \DateTime();
- $tz = $tz->getTimezone();
- $begin = \DateTime::createFromFormat('Y-m-d\TH:i:s', $begin_str, $tz);
- $end = \DateTime::createFromFormat('Y-m-d\TH:i:s', $end_str, $tz);
- }
-
- $request->begin = $begin->getTimestamp();
- $request->end = $end->getTimestamp();
-
- try {
- $request->store();
- return $this->sendReturnData($request->toRawArray());
- } catch (\Exception $e) {
- $this->halt(500, $e->getMessage());
- }
- }
-
-
- /**
- * Changes the reply comment of a request.
- *
- * @post /resources/request/:request_id/edit_reply_comment
- */
- public function editReplyComment($request_id)
- {
- $request = \ResourceRequest::find($request_id);
- if (!$request) {
- $this->notFound('Resource request object not found!');
- }
-
- $current_user = \User::findCurrent();
-
- if ($request->isReadOnlyForUser($current_user)) {
- throw new \AccessDeniedException();
- }
-
- $request->reply_comment = \Request::get('reply_comment');
-
- try {
- if ($request->store() === false) {
- throw new \RuntimeException('Could not store comment');
- }
- } catch (\Exception $e) {
- $this->halt(500, $e->getMessage());
- }
-
- return $this->sendReturnData($request->toRawArray());
- }
-
-
- /**
- * Changes the reply comment of a request.
- *
- * @post /resources/request/:request_id/toggle_marked
- */
- public function toggleMarkedFlag($request_id)
- {
- $request = \ResourceRequest::find($request_id);
- if (!$request) {
- $this->notFound('Resource request object not found!');
- }
-
- $current_user = \User::findCurrent();
-
- if ($request->isReadOnlyForUser($current_user)) {
- throw new \AccessDeniedException();
- }
-
- //Switch to the next marking state or return to the unmarked state
- //if the next marking state would be after the last defined
- //marking state.
- $request->marked = (++$request->marked % \ResourceRequest::MARKING_STATES);
-
- if ($request->isDirty()) {
- $request->store();
- }
-
- return $request;
- }
-}
diff --git a/app/routes/Resources.php b/app/routes/Resources.php
deleted file mode 100644
index 7117546..0000000
--- a/app/routes/Resources.php
+++ /dev/null
@@ -1,950 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * This file contains the REST class for the
- * room and resource management system.
- *
- * @author Moritz Strohm <strohm@data-quest.de>
- * @copyright 2017-2019
- * @license http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
- * @since 4.5
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class Resources extends \RESTAPI\RouteMap
-{
-
- //Resource routes:
-
-
- /**
- * Get a resource object.
- * @param derived_class: If the URL parameter derived_class is set
- * the resource object is converted to an instance of the
- * class that does correct handling of the resource object.
- *
- * @get /resources/resource/:resource_id
- */
- public function getResource($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'user')) {
- throw new \AccessDeniedException();
- }
-
- if (\Request::submitted('derived_classes')) {
- $resource = $resource->getDerivedClassInstance();
- }
-
- $result = $resource->toRawArray();
-
- $result['full_name'] = $resource->getFullName();
- $result['has_children'] = $resource->children ? true : false;
-
- return $result;
- }
-
-
- /**
- * Modifies a resource object.
- *
- * @put /resources/resource/:resource_id
- */
- public function editResource($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'autor')) {
- $this->halt(403);
- return;
- }
-
- $name = $this->data['name'];
- $description = $this->data['description'];
- $parent_id = $this->data['parent_id'];
- $properties = $this->data['properties'];
-
- if ($name) {
- $resource->name = $name;
- }
- if ($description) {
- $resource->description = $description;
- }
- if ($parent_id) {
- if (!\Resource::exists($parent_id)) {
- $this->halt(
- 400,
- 'No resource exists with the ID \'' . $parent_id . '\'!'
- );
- }
- $resource->parent_id = $parent_id;
- }
- if ($properties) {
- foreach ($properties as $name => $value) {
- try {
- $resource->setProperty($name, $value, $GLOBALS['user']->id);
- } catch (\AccessDeniedException $e) {
- $this->halt(
- 403,
- $e->getMessage()
- );
- } catch (\Exception $e) {
- $this->halt(
- 500,
- $e->getMessage()
- );
- }
- }
- }
-
- if ($resource->isDirty()) {
- if ($resource->store()) {
- return $resource->toRawArray();
- } else {
- $this->halt(
- 500,
- 'Error while saving the resource object!'
- );
- }
- }
- return $resource->toRawArray();
- }
-
-
- /**
- * Deletes a resource object.
- *
- * @delete /resources/resource/:resource_id
- */
- public function deleteResource($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'admin')) {
- $this->halt(403);
- return;
- }
-
- if (\Request::submitted('derived_classes')) {
- $resource = $resource->getDerivedClassInstance();
- }
-
- if ($resource->delete()) {
- return 'OK';
- } else {
- $this->halt(
- 500,
- 'Error while deleting the resource object!'
- );
- }
- }
-
-
- /**
- * Returns the child resources of a resource object, if they exist.
- *
- * @get /resources/resource/:resource_id/children
- */
- public function getResourceChildren($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'user')) {
- throw new \AccessDeniedException();
- }
-
- $use_derived_classes = (bool) \Request::submitted('derived_classes');
-
- $result = [];
-
- $children = \Resource::findBySql(
- 'parent_id = :resource_id
- ORDER BY name ASC',
- [
- 'resource_id' => $resource->id
- ]
- );
- if ($children) {
- foreach ($children as $child) {
- if ($use_derived_classes) {
- $child = $child->getDerivedClassInstance();
- }
- $result[] = $child->toRawArray();
- }
- }
- return $result;
- }
-
-
- /**
- * Returns the parent resource of a resource object, if it exists.
- *
- * @get /resources/resource/:resource_id/parent
- */
- public function getResourceParent($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'user')) {
- throw new \AccessDeniedException();
- }
-
- if (!$resource->parent) {
- $this->notFound('This resource has no parent!');
- }
-
- $use_derived_classes = (bool) \Request::submitted('derived_classes');
-
- if ($use_derived_classes) {
- $parent = $resource->parent->getDerivedClassInstance();
- return $parent->toRawArray();
- }
-
- return $resource->parent->toRawArray();
- }
-
-
- /**
- * Get all property objects of a resource.
- *
- * @get /resources/resource/:resource_id/properties
- */
- public function getResourceProperties($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'user')) {
- throw new \AccessDeniedException();
- }
-
- $result = [];
- $properties = \ResourceProperty::findBySql(
- 'INNER JOIN resource_property_definitions rpd
- ON resource_properties.property_id = rpd.property_id
- WHERE
- resource_properties.resource_id = :resource_id
- ORDER BY rpd.name ASC',
- [
- 'resource_id' => $resource->id
- ]
- );
-
- if ($properties) {
- foreach ($properties as $property) {
- $data = $property->toRawArray();
- $data['name'] = $property->definition->name;
- $data['type'] = $property->definition->type;
- if ($data['type'] == 'position') {
- //position properties also get the map-URL:
- $data['map_url'] = \ResourceManager::getMapUrlForResourcePosition(
- $property
- );
- }
- $result[] = $data;
- }
- }
-
- return $result;
- }
-
-
- /**
- * Returns the booking plan of a resource for a week specified
- * by the parameters begin and end.
- *
- * @param begin: The begin timestamp of the time range for the booking plan.
- * @param end: The end timestamp of the time range for the booking plan.
- *
- * @allow_nobody
- *
- * @get /resources/resource/:resource_id/booking_plan
- */
- public function getResourceBookingPlan($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- $current_user = \User::findCurrent();
- $nobody_access = true;
-
- if ($current_user instanceof \User) {
- $nobody_access = false;
- if (!$resource->bookingPlanVisibleForUser($current_user)) {
- throw new \AccessDeniedException();
- }
- } elseif ($resource instanceof \Room) {
- if (!$resource->bookingPlanVisibleForUser($current_user)) {
- throw new \AccessDeniedException();
- }
- }
- $user_is_resource_user = false;
- if ($current_user instanceof \User) {
- $user_is_resource_user = $resource->userHasPermission(
- $current_user,
- 'user'
- );
- }
-
- $display_requests = false;
- if ($current_user instanceof \User) {
- $display_requests = \Request::get('display_requests');
- }
- $display_all_requests = \Request::get('display_all_requests');
-
- if ($display_all_requests && !$user_is_resource_user) {
- //The user is not allowed to see all requests.
- throw new \AccessDeniedException();
- }
-
- $begin_date = \Request::get('start');
- $end_date = \Request::get('end');
- if (!$begin_date || !$end_date) {
- //No time range specified.
- $this->halt(400, 'The parameters "start" and "end" are missing!');
- return;
- }
-
- //Try the ISO format first: YYYY-MM-DDTHH:MM:SS±ZZ:ZZ
- $begin = \DateTime::createFromFormat(\DateTime::RFC3339, $begin_date);
- $end = \DateTime::createFromFormat(\DateTime::RFC3339, $end_date);
-
- if (!($begin instanceof \DateTime) || !($end instanceof \DateTime)) {
- $begin = new \DateTime();
- $end = new \DateTime();
- //Assume the local timezone and use the Y-m-d format:
- $date_regex = '/[0-9]{4}-(0[1-9]|1[0-2])-([0-2][0-9]|3[0-1])/';
- if (preg_match($date_regex, $begin_date)) {
- //$begin is specified in the date formay YYYY-MM-DD:
- $begin_str = explode('-', $begin_date);
- $begin->setDate(
- intval($begin_str[0]),
- intval($begin_str[1]),
- intval($begin_str[2])
- );
- $begin->setTime(0,0,0);
- } else {
- $begin->setTimestamp($begin_date);
- }
- //Now we do the same for $end_timestamp:
- if (preg_match($date_regex, $end_date)) {
- //$begin is specified in the date formay YYYY-MM-DD:
- $end_str = explode('-', $end_date);
- $end->setDate(
- intval($end_str[0]),
- intval($end_str[1]),
- intval($end_str[2])
- );
- $end->setTime(23,59,59);
- } else {
- $end->setTimestamp($end_date);
- }
- }
-
- //Get parameters:
- $booking_types = [];
- if (!$nobody_access) {
- $booking_types = explode(',', \Request::get('booking_types'));
- }
-
- $begin_timestamp = $begin->getTimestamp();
- $end_timestamp = $end->getTimestamp();
-
- //Get the event data sources:
- $bookings = \ResourceBooking::findByResourceAndTimeRanges(
- $resource,
- [
- [
- 'begin' => $begin_timestamp,
- 'end' => $end_timestamp
- ]
- ],
- $booking_types
- );
- $requests = [];
- if ($display_all_requests) {
- $requests = \ResourceRequest::findByResourceAndTimeRanges(
- $resource,
- [
- [
- 'begin' => $begin_timestamp,
- 'end' => $end_timestamp
- ]
- ],
- 0
- );
- } elseif ($display_requests) {
- //Get the users own request only:
- $requests = \ResourceRequest::findByResourceAndTimeRanges(
- $resource,
- [
- [
- 'begin' => $begin_timestamp,
- 'end' => $end_timestamp
- ]
- ],
- 0,
- [],
- 'user_id = :user_id',
- ['user_id' => $current_user->id]
- );
- }
-
- $objects = array_merge($bookings, $requests);
- $event_data = \Studip\Fullcalendar::createData($objects, $begin_timestamp, $end_timestamp);
-
- if ($nobody_access) {
- //For nobody users, the code stops here since
- //nobody users are not allowed to include additional objects.
- return $event_data;
- }
-
- //Check if there are additional objects to be displayed:
- $additional_objects = \Request::getArray('additional_objects');
- $additional_object_colours = \Request::getArray('additional_object_colours');
- if ($additional_objects) {
- foreach ($additional_objects as $object_class => $object_ids) {
- if (!is_a($object_class, '\SimpleORMap', true)) {
- continue;
- }
- if (!is_a($object_class, '\Studip\Calendar\EventSource', true)) {
- continue;
- }
-
- $special_colours = [];
- if ($additional_object_colours[$object_class]) {
- $special_colours = $additional_object_colours[$object_class];
- }
-
- $additional_objects = $object_class::findMany($object_ids);
- foreach ($additional_objects as $additional_object) {
- $event_data = $additional_object->getFilteredEventData(
- $current_user->id,
- null,
- null,
- $begin,
- $end
- );
-
- if ($special_colours) {
- foreach ($event_data as $data) {
- $data->text_colour = $special_colours['fg'];
- $data->background_colour = $special_colours['bg'];
- $data->editable = false;
- $event_data[] = $data->toFullcalendarEvent();
- }
- }
- }
- }
- }
- return $event_data;
- }
-
-
- /**
- * Returns the booking plan of a resource for a selected semester.
- *
- * @param semester_id: The ID of the semester. Defaults to the current
- * semester, if not set.
- *
- * @get /resources/resource/:resource_id/semester_plan
- */
- public function getResourceSemesterBookingPlan($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- $current_user = \User::findCurrent();
-
- if (!$resource->bookingPlanVisibleForUser($current_user)) {
- throw new \AccessDeniedException();
- }
-
- $user_is_resource_user = $resource->userHasPermission(
- $current_user,
- 'user'
- );
-
- $display_requests = \Request::get('display_requests');
- $display_all_requests = \Request::get('display_all_requests');
-
- $begin = new \DateTime();
- $end = new \DateTime();
-
- $semester_id = \Request::get('semester_id');
- $semester = null;
-
- if ($semester_id) {
- $semester = \Semester::find($semester_id);
- if (!$semester) {
- $this->halt(404, 'Specified semester not found!');
- }
- } else {
- $semester = \Semester::findCurrent();
- if (!$semester) {
- $this->halt(500, 'Current semester not available!');
- }
- }
-
- if (\Request::get('semester_timerange') != 'fullsem') {
- $begin->setTimestamp($semester->vorles_beginn);
- $end->setTimestamp($semester->vorles_ende);
- } else {
- $begin->setTimestamp($semester->beginn);
- $end->setTimestamp($semester->ende);
- }
-
- //Get parameters:
- $booking_types = \Request::getArray('booking_types');
-
- $begin_timestamp = $begin->getTimestamp();
- $end_timestamp = $end->getTimestamp();
-
- //Get the event data sources:
- $bookings = \ResourceBooking::findByResourceAndTimeRanges(
- $resource,
- [
- [
- 'begin' => $begin_timestamp,
- 'end' => $end_timestamp
- ]
- ],
- $booking_types
- );
-
- $requests = [];
- if ($display_all_requests || $display_requests) {
- $requests_sql = "INNER JOIN seminar_cycle_dates scd
- USING (metadate_id)
- WHERE
- resource_id = :resource_id
- AND
- closed = '0' ";
- $requests_sql_params = [
- 'begin' => $begin_timestamp,
- 'end' => $end_timestamp,
- 'resource_id' => $resource->id
- ];
- if (!$display_all_requests) {
- $requests_sql .= "AND user_id = :user_id ";
- $requests_sql_params['user_id'] = $current_user->id;
- }
-
- $requests = \ResourceRequest::findBySql(
- $requests_sql,
- $requests_sql_params
- );
- }
-
- $merged_objects = [];
- $metadates = [];
-
- foreach ($bookings as $booking) {
- $booking->resource = $resource;
- $irrelevant_booking = false;
- if ($booking->getRepetitionType() != 'weekly') {
- if (!\Request::get('display_single_bookings')) {
- $irrelevant_booking = true;
- } else if ($booking->end < strtotime('today')) {
- $irrelevant_booking = true;
- }
- }
- if ($booking->getAssignedUserType() === 'course' && in_array($booking->assigned_course_date->metadate_id, $metadates)) {
- $irrelevant_booking = true;
- };
- if (!$irrelevant_booking) {
- //It is an booking with repetitions that has to be included
- //in the semester plan.
- if (in_array($booking->getRepetitionType(), ['single','weekly'])) {
- $event_list = $booking->convertToEventData([\ResourceBookingInterval::build(['interval_id' => md5(uniqid()), 'begin' => $booking->begin - $booking->preparation_time, 'end' => $booking->end])], $current_user);
- } else {
- $event_list = $booking->getFilteredEventData(null,null,null,strtotime('today'), $end_timestamp);
- }
- foreach ($event_list as $event_data) {
- if ($booking->getAssignedUserType() === 'course' && $booking->assigned_course_date->metadate_id) {
- $index = sprintf(
- '%1$s_%2$s_%3$s',
- $booking->assigned_course_date->metadate_id,
- $event_data->begin->format('NHis'),
- $event_data->end->format('NHis')
- );
- $metadates[] = $booking->assigned_course_date->metadate_id;
- } else {
- $index = sprintf(
- '%1$s_%2$s_%3$s',
- $booking->id,
- $event_data->begin->format('NHis'),
- $event_data->end->format('NHis')
- );
- }
-
- //Strip some data that cannot be used effectively in here:
- $event_data->api_urls = [];
- $event_data->editable = false;
-
- $merged_objects[$index] = $event_data;
- }
- }
- }
-
- foreach ($requests as $request) {
- if ($request->cycle instanceof \SeminarCycleDate) {
- $cycle_dates = $request->cycle->getAllDates();
- foreach ($cycle_dates as $cycle_date) {
- $relevant_request = $semester->beginn <= $cycle_date->date
- && $semester->ende >= $cycle_date->date;
- if ($relevant_request) {
- //We have found a date for the current semester
- //that makes the request relevant.
- break;
- }
- }
- if (!$relevant_request) {
- continue;
- }
- $event_data_list = $request->getFilteredEventData(
- $current_user->id
- );
-
- foreach ($event_data_list as $event_data) {
- $index = sprintf(
- '%1$s_%2$s_%3$s',
- $request->metadate_id,
- $event_data->begin->format('NHis'),
- $event_data->end->format('NHis')
- );
-
- //Strip some data that cannot be used effectively in here:
- $event_data->view_urls = [];
- $event_data->api_urls = [];
-
- $merged_objects[$index] = $event_data;
- }
- }
- }
-
- //Convert the merged events to Fullcalendar events:
- $data = [];
- foreach ($merged_objects as $obj) {
- $data[] = $obj->toFullCalendarEvent();
- }
-
- return $data;
- }
-
-
- /**
- * Gets request of a resource. At your option the requests can be
- * limited to a specific time range, specified by the parameters
- * begin and end. Furthermore the requests can be filtered by user-ID.
- *
- * @param begin: A timestamp specifying the begin of the time range.
- * @param end: A timestamp specifying the end of the time range.
- * @param user_id: This parameter limits the result set to requests
- * of the user specified by the user-ID provided in this parameter.
- *
- * @get /resources/resource/:resource_id/requests
- */
- public function getResourceRequests($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'user')) {
- throw new \AccessDeniedException();
- }
-
- $begin = $this->data['begin'];
- $end = $this->data['end'];
- $user_id = $this->data['user_id'];
-
- $sql = 'resource_id = :resource_id ';
- $sql_array = [
- 'resource_id' => $resource->id
- ];
-
- if ($begin and $end) {
- $sql .= 'AND ((begin >= :begin AND begin <= :end)
- OR
- (end >= :begin AND end <= :end)) ';
- $sql_array['begin'] = $begin;
- $sql_array['end'] = $end;
- }
-
- if ($user_id) {
- $sql .= 'AND user_id = :user_id ';
- $sql_array['user_id'] = $user_id;
- }
-
- $sql .= 'ORDER BY mkdate ASC';
-
- $requests = \ResourceRequest::findBySql($sql, $sql_array);
-
- $result = [];
- foreach ($requests as $request) {
- $result[] = $request->toRawArray();
- }
-
- return $result;
- }
-
-
- /**
- *
- * @param begin: A timestamp specifying the begin of the time range.
- * @param end: A timestamp specifying the end of the time range.
- * @param user_id: This parameter limits the result set to bookings
- * of the user specified by the user-ID provided in this parameter.
- * @param types: Limits the result to booking types specified in this
- * parameter. The allowed types are comma separated like this: "1,2,3".
- * The defined types are:
- * 0 = normal booking, 1 = reservation, 2 = lock.
- *
- * @get /resources/resource/:resource_id/bookings
- */
- public function getResourceBookings($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'user')) {
- throw new \AccessDeniedException();
- }
-
- $begin = \Request::get('begin');
- $end = \Request::get('end');
- $user_id = \Request::get('user_id');
- $types = [];
- $types_str = \Request::get('types');
- if ($types_str) {
- $types = explode(',', $types_str);
- }
-
- $sql = 'resource_id = :resource_id ';
- $sql_array = [
- 'resource_id' => $resource->id
- ];
-
- if ($begin and $end) {
- $sql .= 'AND ((begin >= :begin AND begin <= :end)
- OR
- (end >= :begin AND end <= :end)) ';
- $sql_array['begin'] = $begin;
- $sql_array['end'] = $end;
- }
-
- if ($user_id) {
- $sql .= 'AND user_id = :user_id ';
- $sql_array['user_id'] = $user_id;
- }
- if ($types) {
- $sql .= 'AND booking_type IN ( :types ) ';
- $sql_array['types'] = $types;
- }
-
- $sql .= 'ORDER BY mkdate ASC';
-
- $bookings = \ResourceBooking::findBySql($sql, $sql_array);
-
- $result = [];
- if ($bookings) {
- foreach ($bookings as $booking) {
- $result[] = $booking->toRawArray();
- }
- }
-
- return $result;
- }
-
-
- /**
- * Creates a booking/reservation/lock for a resource.
- *
- * @param begin: The begin timestamp for the booking.
- * @param end: The end timestamp for the booking.
- * @param preparation_time: The amount of seconds for preparation time
- * before the begin timestamp.
- * @param internal_comment: A comment that is only visible for some
- * parts of the staff.
- * @param booking_type: The booking type:
- * 0 = normal booking
- * 1 = reservation
- * 2 = lock
- *
- * @post /resources/resource/:resource_id/assign
- */
- public function createResourceBooking($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'user')) {
- throw new \AccessDeniedException();
- }
-
- $begin_str = \Request::get('begin');
- $end_str = \Request::get('end');
- $preparation_time = \Request::int('preparation_time');
- $internal_comment = \Request::get('internal_comment');
- $booking_type = \Request::int('booking_type');
-
- $begin = new \DateTime();
- $begin->setTimestamp($begin_str);
- $end = new \DateTime();
- $end->setTimestamp($end_str);
-
- try {
- $booking = $resource->createSimpleBooking(
- \User::findCurrent(),
- $begin,
- $end,
- $preparation_time,
- $internal_comment,
- $booking_type
- );
- return $booking;
- } catch (\Exception $e) {
- $this->halt(
- 400,
- $e->getMessage()
- );
- }
- }
-
-
- /**
- * Creates a resource request.
- *
- * @post /resources/resource/:resource_id/request_simple
- */
- public function createSimpleResourceRequest($resource_id)
- {
- $resource = \Resource::find($resource_id);
- if (!$resource) {
- $this->notFound('Resource object not found!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- $user = \User::findCurrent();
- if (!$resource->userHasPermission($user, 'user')) {
- throw new \AccessDeniedException();
- }
-
- $begin_str = \Request::get('begin');
- $end_str = \Request::get('end');
- $comment = \Request::get('comment');
-
- $begin = new \DateTime();
- $begin->setTimestamp($begin_str);
- $end = new \DateTime();
- $end->setTimestamp($end_str);
-
- try {
- $request = $resource->createSimpleRequest(
- $user,
- $begin,
- $end,
- $comment
- );
- return $request;
- } catch (\Exception $e) {
- $this->halt(
- 400,
- $e->getMessage()
- );
- }
- }
-
-
- /**
- * Change the status of a resource booking interval:
- * @post /resources/booking_interval/:interval_id/toggle_takes_place
- */
- public function toggleResourceBookingIntervalTakesPlaceField($interval_id)
- {
- $interval = \ResourceBookingInterval::find($interval_id);
- if (!$interval) {
- $this->notFound('ResourceBookingInterval object not found!');
- }
-
- //Get the resource and check the permissions of the user:
- $resource = $interval->resource;
- if (!$resource) {
- $this->halt(500, 'ResourceBookingInterval not linked with a resource!');
- }
-
- $resource = $resource->getDerivedClassInstance();
-
- if (!$resource->userHasPermission(\User::findCurrent(), 'autor', [$interval->begin, $interval->end])) {
- $this->halt(403, 'You do not have sufficient permissions to modify the interval!');
- }
-
- if (
- !$interval->takes_place
- && $resource->isAssigned(new \DateTime('@' . $interval->begin), new \DateTime('@' . $interval->end))
- ) {
- $this->halt(409, 'Already booked');
- }
- //Switch the takes_place field:
- $interval->takes_place = $interval->takes_place ? '0' : '1';
-
- if ($interval->store()) {
- return [
- 'takes_place' => $interval->takes_place
- ];
- } else {
- $this->halt(500, 'Error while storing the interval!');
- }
- }
-}
diff --git a/app/routes/RoomClipboard.php b/app/routes/RoomClipboard.php
deleted file mode 100644
index ffcafe6..0000000
--- a/app/routes/RoomClipboard.php
+++ /dev/null
@@ -1,322 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * This file contains the REST class for room clipboards
- * (clipboards containing room resources).
- *
- * @author Moritz Strohm <strohm@data-quest.de>
- * @copyright 2017-2019
- * @license http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
- * @since 4.5
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class RoomClipboard extends \RESTAPI\RouteMap
-{
- //Room clipboard routes:
-
- /**
- * Returns the request/booking plan for a room clipboard.
- *
- * @get /room_clipboard/:clipboard_id/booking_plan
- */
- public function getPlan($clipboard_id = null)
- {
- if (!$clipboard_id) {
- $this->notFound('ID of clipboard has not been provided!');
- }
-
- $clipboard = \Clipboard::find($clipboard_id);
- if (!$clipboard) {
- $this->notFound('Clipboard object not found!');
- }
-
- $current_user = \User::findCurrent();
-
- //Permission check:
- if ($clipboard->user_id !== $current_user->id) {
- throw new \AccessDeniedException();
- }
-
- $display_requests = \Request::bool('display_requests');
- $display_all_requests = \Request::bool('display_all_requests');
-
- $begin_date = \Request::get('start');
- $end_date = \Request::get('end');
- if (!$begin_date || !$end_date) {
- //No time range specified.
- $this->halt(400, 'The parameters "start" and "end" are missing!');
- return;
- }
-
- //Try the ISO format first: YYYY-MM-DDTHH:MM:SS±ZZ:ZZ
- $begin = \DateTime::createFromFormat(\DateTime::RFC3339, $begin_date);
- $end = \DateTime::createFromFormat(\DateTime::RFC3339, $end_date);
-
- if (!($begin instanceof \DateTime) || !($end instanceof \DateTime)) {
- $begin = new \DateTime();
- $end = new \DateTime();
- //Assume the local timezone and use the Y-m-d format:
- $date_regex = '/[0-9]{4}-(0[1-9]|1[0-2])-([0-2][0-9]|3[0-1])/';
- if (preg_match($date_regex, $begin_date)) {
- //$begin is specified in the date formay YYYY-MM-DD:
- $begin_str = explode('-', $begin_date);
- $begin->setDate(
- intval($begin_str[0]),
- intval($begin_str[1]),
- intval($begin_str[2])
- );
- $begin->setTime(0,0,0);
- } else {
- $begin->setTimestamp($begin_date);
- }
- //Now we do the same for $end_timestamp:
- if (preg_match($date_regex, $end_date)) {
- //$begin is specified in the date formay YYYY-MM-DD:
- $end_str = explode('-', $end_date);
- $end->setDate(
- intval($end_str[0]),
- intval($end_str[1]),
- intval($end_str[2])
- );
- $end->setTime(23,59,59);
- } else {
- $end->setTimestamp($end_date);
- }
- }
-
- //Check if a clipboard is selected:
- $selected_clipboard_id = $_SESSION['selected_clipboard_id'];
-
- $rooms = [];
- if ($clipboard_id) {
- $clipboard = \Clipboard::find($clipboard_id);
- } elseif ($selected_clipboard_id) {
- $clipboard = \Clipboard::find($selected_clipboard_id);
- } else {
- $this->halt(400, 'No clipboard selected!');
- }
- if ($clipboard) {
- $rooms = \Room::findMany($clipboard->getAllRangeIds('Room'));
- } else {
- $this->halt(404, 'Clipboard not found!');
- }
-
- $booking_types = \Request::getArray('booking_types');
-
- //Room permission check:
- $plan_objects = [];
- foreach ($rooms as $room) {
- if ($room->bookingPlanVisibleForuser($current_user)) {
- $plan_objects = array_merge(
- $plan_objects,
- \ResourceManager::getBookingPlanObjects(
- $room,
- [
- [
- 'begin' => $begin->getTimestamp(),
- 'end' => $end->getTimestamp()
- ]
- ],
- $booking_types,
- $display_all_requests ? 'all' : $display_requests
- )
- );
- }
- }
-
- $data = \Studip\Fullcalendar::createData($plan_objects, $begin, $end);
-
- return $data;
- }
-
-
- /**
- * Returns the semester plan for a room clipboard.
- *
- * @get /room_clipboard/:clipboard_id/semester_plan
- */
- public function getSemeterPlan($clipboard_id = null)
- {
- if (!$clipboard_id) {
- $this->notFound('ID of clipboard has not been provided!');
- }
-
- $clipboard = \Clipboard::find($clipboard_id);
- if (!$clipboard) {
- $this->notFound('Clipboard object not found!');
- }
-
- $current_user = \User::findCurrent();
-
- //Permission check:
- if ($clipboard->user_id !== $current_user->id) {
- throw new \AccessDeniedException();
- }
-
- $display_requests = \Request::bool('display_requests');
- $display_all_requests = \Request::bool('display_all_requests');
-
- $begin = new \DateTime();
- $end = new \DateTime();
-
- $semester_id = \Request::get('semester_id');
- $semester = null;
-
- if ($semester_id) {
- $semester = \Semester::find($semester_id);
- if (!$semester) {
- $this->halt(404, 'Specified semester not found!');
- }
- } else {
- $semester = \Semester::findCurrent();
- if (!$semester) {
- $this->halt(500, 'Current semester not available!');
- }
- }
-
- if (\Request::get('semester_timerange') == 'vorles') {
- $begin->setTimestamp($semester->vorles_beginn);
- $end->setTimestamp($semester->vorles_ende);
- } else {
- $begin->setTimestamp($semester->beginn);
- $end->setTimestamp($semester->ende);
- }
-
- //Check if a clipboard is selected:
- $selected_clipboard_id = $_SESSION['selected_clipboard_id'];
-
- $rooms = [];
- if ($clipboard_id) {
- $clipboard = \Clipboard::find($clipboard_id);
- } elseif ($selected_clipboard_id) {
- $clipboard = \Clipboard::find($selected_clipboard_id);
- } else {
- $this->halt(400, 'No clipboard selected!');
- }
- if ($clipboard) {
- $rooms = \Room::findMany($clipboard->getAllRangeIds('Room'));
- } else {
- $this->halt(404, 'Clipboard not found!');
- }
-
- //Get parameters:
- $booking_types = \Request::getArray('booking_types');
-
- //Get the event data sources:
- $plan_objects = [];
-
- foreach ($rooms as $room) {
- if ($room->bookingPlanVisibleForuser($current_user)) {
- $plan_objects = array_merge(
- $plan_objects,
- \ResourceManager::getBookingPlanObjects(
- $room,
- [
- [
- 'begin' => $begin->getTimestamp(),
- 'end' => $end->getTimestamp()
- ]
- ],
- $booking_types,
- $display_all_requests ? 'all' : $display_requests
- )
- );
- }
- }
-
- $merged_objects = [];
- $metadates = [];
- foreach ($plan_objects as $plan_object) {
- if ($plan_object instanceof \ResourceBooking) {
- $irrelevant_booking =
- $plan_object->getRepetitionType() != 'weekly' ||
- ($plan_object->getAssignedUserType() === 'course' && in_array($plan_object->assigned_course_date->metadate_id, $metadates));
- if ($irrelevant_booking) {
- continue;
- }
-
- //It is a booking with repetitions that has to be included
- //in the semester plan.
-
- $real_begin = $plan_object->begin;
- if ($plan_object->preparation_time > 0) {
- $real_begin -= $plan_object->preparation_time;
- }
- $event_data = $plan_object->convertToEventData([\ResourceBookingInterval::build(['interval_id' => md5(uniqid()), 'begin' => $real_begin, 'end' => $plan_object->end])], $current_user);
-
- //Merge event data from the same booking that have the
- //same weekday and begin and end time into one event.
- //If no repetition interval is set and the booking belongs
- //to a course date, use the corresponding metadate ID or the
- //course date ID in the index. Otherwise use the booking's
- //ID (specified by event_data->object_id).
- foreach ($event_data as $event) {
- if ($plan_object->getAssignedUserType() === 'course') {
- $index = sprintf(
- '%1$s_%2$s_%3$s',
- $plan_object->assigned_course_date->metadate_id,
- $event->begin->format('NHis'),
- $event->end->format('NHis')
- );
- $metadates[] = $plan_object->assigned_course_date->metadate_id;
- } else {
- $index = sprintf(
- '%1$s_%2$s_%3$s',
- $plan_object->id,
- $event->begin->format('NHis'),
- $event->end->format('NHis')
- );
- }
-
- //Strip some data that cannot be used effectively in here:
- $event->api_urls = [];
-
- $merged_objects[$index] = $event;
- }
- } elseif ($plan_object instanceof \ResourceRequest) {
- if ($plan_object->cycle instanceof \SeminarCycleDate) {
- $cycle_dates = $plan_object->cycle->getAllDates();
- foreach ($cycle_dates as $cycle_date) {
- $relevant_request = $semester->beginn <= $cycle_date->date
- && $semester->ende >= $cycle_date->date;
- if ($relevant_request) {
- //We have found a date for the current semester
- //that makes the request relevant.
- break;
- }
- }
- if (!$relevant_request) {
- continue;
- }
- $event_data_list = $plan_object->getFilteredEventData(
- $current_user->id
- );
-
- foreach ($event_data_list as $event_data) {
- $index = sprintf(
- '%1$s_%2$s_%3$s',
- $plan_object->metadate_id,
- $event_data->begin->format('NHis'),
- $event_data->end->format('NHis')
- );
-
- //Strip some data that cannot be used effectively in here:
- $event_data->view_urls = [];
- $event_data->api_urls = [];
-
- $merged_objects[$index] = $event_data;
- }
- }
- }
- }
-
- //Convert the merged events to Fullcalendar events:
- $data = [];
- foreach ($merged_objects as $obj) {
- $data[] = $obj->toFullCalendarEvent();
- }
-
- return $data;
- }
-}
diff --git a/app/routes/Schedule.php b/app/routes/Schedule.php
deleted file mode 100644
index 2341f73..0000000
--- a/app/routes/Schedule.php
+++ /dev/null
@@ -1,71 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @author André Klaßen <andre.klassen@elan-ev.de>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition user_id ^[a-f0-9]{1,32}$
- * @condition semester_id ^[a-f0-9]{1,32}$
- */
-class Schedule extends \RESTAPI\RouteMap
-{
- /**
- * returns schedule for a given user and semester
- *
- * @get /user/:user_id/schedule/:semester_id
- * @get /user/:user_id/schedule
- */
- public function getSchedule($user_id, $semester_id = null)
- {
- if ($user_id !== $GLOBALS['user']->id) {
- $this->error(401);
- }
-
- $current_semester = isset($semester_id)
- ? \Semester::find($semester_id)
- : \Semester::findCurrent();
-
- if (!$current_semester) {
- $this->notFound('No such semester.');
- }
-
- $schedule_settings = \UserConfig::get($user_id)->SCHEDULE_SETTINGS;
- $days = \CalendarScheduleModel::getDisplayedDays($schedule_settings['glb_days']);
-
- $entries = \CalendarScheduleModel::getEntries(
- $user_id, $current_semester,
- $schedule_settings['glb_start_time'], $schedule_settings['glb_end_time'],
- $days,
- $visible = false
- );
-
- $json = [];
- foreach ($entries as $number_of_day => $schedule_of_day) {
- $entries = [];
- foreach ($schedule_of_day->entries as $entry) {
- $entries[$entry['id']] = self::entryToJson($entry);
- }
- $json[$number_of_day] = $entries;
- }
-
- $this->etag(md5(serialize($json)));
-
- return array_reverse($json, true);
- }
-
-
- private static function entryToJson($entry)
- {
- $json = [];
- foreach (['start', 'end', 'content', 'title', 'color', 'type'] as $key) {
- $json[$key] = in_array($key, ['start', 'end'])
- ? (int) $entry[$key]
- : $entry[$key];
- }
-
- return $json;
- }
-}
diff --git a/app/routes/Semester.php b/app/routes/Semester.php
deleted file mode 100644
index bdb1ee7..0000000
--- a/app/routes/Semester.php
+++ /dev/null
@@ -1,115 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition semester_id ^[0-9a-f]{1,32}$
- */
-class Semester extends \RESTAPI\RouteMap
-{
- public function __construct()
- {
- parent::__construct();
- if (!\Request::int('limit')) {
- $this->limit = count(\Semester::getAll());
- }
- }
-
- /**
- * Returns a list of all semesters.
- *
- * @get /semesters
- * @allow_nobody
- */
- public function getSemesters()
- {
- $semesters = \Semester::getAll();
-
- // paginate
- $total = count($semesters);
- $semesters = array_slice($semesters, $this->offset, $this->limit);
-
- $json = [];
- foreach ($semesters as $semester) {
- $url = $this->urlf('/semester/%s', $semester['semester_id']);
- $json[$url] = $this->semesterToJSON($semester);
- }
-
- return $this->paginated($json, $total);
- }
-
- /**
- * Returns the semester week as string for a given string
- *
- * @get /semester/:timestamp/week
- * @allow_nobody
- */
- public function getSemesterWeek(int $timestamp)
- {
- $semester = \Semester::findByTimestamp($timestamp);
- if (!$semester) {
- return null;
- }
- $timestamp = strtotime('today', $timestamp);
- $week_begin_timestamp = strtotime('monday this week', $semester->vorles_beginn);
- $end_date = $semester->vorles_ende;
-
- $i = 0;
- $result = [
- 'semester_name' => (string)$semester->name,
- 'week_number' => sprintf(_('KW %u'), date('W', $timestamp)),
- 'current_day' => strftime('%x', $timestamp)
- ];
- while ($week_begin_timestamp < $end_date) {
- $next_week_timestamp = strtotime('+1 week', $week_begin_timestamp);
- if ($week_begin_timestamp <= $timestamp && $timestamp < $next_week_timestamp) {
- $result['sem_week'] = sprintf(
- _('%u. Vorlesungswoche (ab %s)'),
- $i + 1,
- strftime('%x', $week_begin_timestamp));
- break;
- }
- $i += 1;
-
- $week_begin_timestamp = $next_week_timestamp;
- }
-
- return $result;
- }
-
- /**
- * Returns a single semester.
- *
- * @get /semester/:semester_id
- */
- public function getSemester($id)
- {
- $semester = \Semester::find($id);
- if (!$semester) {
- $this->notFound();
- }
-
- $semester_json = $this->semesterToJSON($semester);
- $this->etag(md5(serialize($semester_json)));
-
- return $semester_json;
- }
-
- private function semesterToJSON($semester)
- {
- return [
- 'id' => $semester['semester_id'],
- 'title' => (string) $semester['name'],
- 'token' => (string) $semester['semester_token'],
- 'begin' => (int) $semester['beginn'],
- 'end' => (int) $semester['ende'],
- 'seminars_begin' => (int) $semester['vorles_beginn'],
- 'seminars_end' => (int) $semester['vorles_ende'],
- 'visible' => (int) $semester['visible'],
- ];
- }
-}
diff --git a/app/routes/Studip.php b/app/routes/Studip.php
deleted file mode 100644
index 749a53a..0000000
--- a/app/routes/Studip.php
+++ /dev/null
@@ -1,65 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-use Config;
-use SemClass;
-use SemType;
-
-/**
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class Studip extends \RESTAPI\RouteMap
-{
- /**
- * Grundlegende Systemeinstellungen
- *
- * @get /studip/settings
- */
- public function getSettings()
- {
- $sem_types = array_map(function ($item) {
- return [
- 'name' => $item['name'],
- 'class' => $item['class'],
- ];
- }, SemType::getTypes());
-
- $sem_classes = array_map(function ($item) {
- $item = (array) $item;
- return reset($item);
- }, SemClass::getClasses());
-
- return [
- 'ALLOW_CHANGE_USERNAME' => Config::get()->ALLOW_CHANGE_USERNAME,
- 'ALLOW_CHANGE_EMAIL' => Config::get()->ALLOW_CHANGE_EMAIL,
- 'ALLOW_CHANGE_NAME' => Config::get()->ALLOW_CHANGE_NAME,
- 'ALLOW_CHANGE_TITLE' => Config::get()->ALLOW_CHANGE_TITLE,
- 'INST_TYPE' => $GLOBALS['INST_TYPE'],
- 'SEM_TYPE' => $sem_types,
- 'SEM_CLASS' => $sem_classes,
- 'TERMIN_TYP' => $GLOBALS['TERMIN_TYP'],
- 'PERS_TERMIN_KAT' => $GLOBALS['PERS_TERMIN_KAT'],
- 'SUPPORT_EMAIL' => $GLOBALS['UNI_CONTACT'],
- 'TITLES' => $GLOBALS['DEFAULT_TITLE_FOR_STATUS'],
- 'UNI_NAME_CLEAN' => Config::get()->UNI_NAME_CLEAN,
- ];
- }
-
- /**
- * Farbeinstellungen
- *
- * @get /studip/colors
- */
- public function getColors()
- {
- // TODO: Move these definitions somewhere else (but where!?)
- return [
- 'background' => '#e1e4e9',
- 'dark' => '#34578c',
- 'light' => '#899ab9',
- ];
- }
-}
diff --git a/app/routes/User.php b/app/routes/User.php
deleted file mode 100644
index d3cce26..0000000
--- a/app/routes/User.php
+++ /dev/null
@@ -1,300 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @author André Klaßen <andre.klassen@elan-ev.de>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition user_id ^[0-9a-f]{1,32}$
- */
-class User extends \RESTAPI\RouteMap
-{
- /**************************************************/
- /* PUBLIC STATIC HELPER METHODS */
- /**************************************************/
-
- public static function getMiniUser($routemap, $user)
- {
- $avatar = \Avatar::getAvatar($user->id);
-
- return [
- 'id' => $user->id,
- 'href' => $routemap->urlf('/user/%s', [htmlReady($user->id)]),
- 'name' => self::getNamesOfUser($user),
- 'avatar_small' => $avatar->getURL(\Avatar::SMALL),
- 'avatar_medium' => $avatar->getURL(\Avatar::MEDIUM),
- 'avatar_normal' => $avatar->getURL(\Avatar::NORMAL),
- 'avatar_original' => $avatar->getURL(\Avatar::NORMAL)
- ];
- }
-
- public static function getNamesOfUser($user)
- {
- $name = [
- 'username' => $user->username,
- 'formatted' => $user->getFullName(),
- 'family' => $user->nachname,
- 'given' => $user->vorname,
- 'prefix' => $user->title_front,
- 'suffix' => $user->title_rear
- ];
- return $name;
- }
-
-
- /**************************************************/
- /* ROUTES */
- /**************************************************/
-
- /**
- * Searches for users by a given keyword.
- *
- * @get /users
- */
- public function searchUsers()
- {
- $needle = \Request::get('q') ?? \Request::get('needle');
- if (!$needle) {
- $this->halt(400, 'Missing search paramter ?q=');
- }
-
- $query = \GlobalSearchUsers::getSQL($needle, [], $this->offset + $this->limit);
- $result = \DBManager::get()->fetchAll($query);
- $total = (int) \DBManager::get()->fetchColumn('SELECT FOUND_ROWS() as found_rows');
-
- $user_ids = array_column($result, 'user_id');
- $users = \User::findMany($user_ids);
-
- return $this->paginated(
- array_map(function ($user) {
- return self::getMiniUser($this, $user);
- }, $users),
- $total
- );
- }
-
-
- /**
- * getUser - retrieves data of a user
- *
- * @get /user/:user_id
- * @get /user
- */
- public function getUser($user_id = '')
- {
- $user_id = $user_id ?: $GLOBALS['user']->id;
-
- $user = \User::findFull($user_id);
- if (!$user) {
- $this->halt(404, sprintf('User %s not found', $user_id));
- }
-
- $visibilities = get_local_visibility_by_id($user_id, 'homepage');
- if (is_array(json_decode($visibilities, true))) {
- $visibilities = json_decode($visibilities, true);
- } else {
- $visibilities = [];
- }
-
- $get_field = function ($field, $visibility) use ($user_id, $user, $visibilities) {
- if (!$user[$field]
- || !is_element_visible_for_user($GLOBALS['user']->id, $user_id, $visibilities[$visibility]))
- {
- return '';
- }
- return $user[$field];
- };
-
- $avatar = \Avatar::getAvatar($user_id);
-
- $user = [
- 'user_id' => $user_id,
- 'username' => $user['username'],
- 'name' => self::getNamesOfUser($user),
- 'perms' => $user['perms'],
- 'email' => get_visible_email($user_id),
- 'avatar_small' => $avatar->getURL(\Avatar::SMALL),
- 'avatar_medium' => $avatar->getURL(\Avatar::MEDIUM),
- 'avatar_normal' => $avatar->getURL(\Avatar::NORMAL),
- 'avatar_original' => $avatar->getURL(\Avatar::NORMAL),
- 'phone' => $get_field('privatnr', 'private_phone'),
- 'homepage' => $get_field('Home', 'homepage'),
- 'privadr' => strip_tags($get_field('privadr', 'privadr')),
- ];
-
- // Data fields
- $datafields = [];
- foreach (\DataFieldEntry::getDataFieldEntries($user_id, 'user') as $entry) {
- if (!$entry->isVisible()) {
- continue;
- }
- if (!\Visibility::verify($entry->getID(), $user_id)) {
- continue;
- }
- $datafields[] = [
- 'type' => $entry->getType(),
- 'id' => $entry->getId(),
- 'name' => (string) $entry->getName(),
- 'value' => $entry->getValue(),
- ];
- }
- $user['datafields'] = $datafields;
-
- $this->etag(md5(serialize($user)));
-
- return $user;
-
- }
-
-
- /**
- * deleteUser - deletes a user
- *
- * @delete /user/:user_id
- */
- public function deleteUser($user_id)
- {
- if (!$GLOBALS['perm']->have_perm('root')) {
- $this->error(401);
- }
-
- if (!$GLOBALS['user']->id === $user_id) {
- $this->error(400, 'Must not delete yourself');
- }
-
- $user = \User::find($user_id);
- $user->delete();
-
- $this->status(204);
- }
-
-
- /**
- * returns institutes for a given user
- *
- * @get /user/:user_id/institutes
- */
- public function getInstitutes($user_id)
- {
- $user = \User::find($user_id);
- if (!$user) {
- $this->notFound(sprintf('User %s not found', $user_id));
- }
-
- $query = "SELECT i0.Institut_id AS institute_id, i0.Name AS name,
- inst_perms AS perms, sprechzeiten AS consultation,
- raum AS room, ui.telefon AS phone, ui.fax,
- i0.Strasse AS street, i0.Plz AS city,
- i1.Name AS faculty_name, i1.Strasse AS faculty_street,
- i1.Plz AS faculty_city
- FROM user_inst AS ui
- JOIN Institute AS i0 USING (Institut_id)
- LEFT JOIN Institute AS i1 ON (i0.fakultaets_id = i1.Institut_id)
- WHERE visible = 1 AND user_id = :user_id
- ORDER BY priority ASC";
- $statement = \DBManager::get()->prepare($query);
- $statement->bindValue(':user_id', $user_id);
- $statement->execute();
-
- $institutes = [
- 'work' => [],
- 'study' => [],
- ];
-
- foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $row) {
- if ($row['perms'] === 'user') {
- $institutes['study'][] = $row;
- } else {
- $institutes['work'][] = $row;
- }
- }
-
- $this->etag(md5(serialize($institutes)));
-
- $result = array_slice($institutes, $this->offset, $this->limit);
- return $this->paginated(
- $result,
- count($institutes['study']) + count($institutes['work']),
- compact('user_id')
- );
- }
-
-
- /**
- * Get the root file folder of a user's file area.
- *
- * @get /user/:user_id/top_folder
- */
- public function getTopFolder($user_id)
- {
- $user = \User::find($user_id);
- if (!$user) {
- $this->notFound("User with id {$user_id} not found!");
- }
-
- if ($user->id !== \User::findCurrent()->id) {
- $this->error(403, 'You are not allowed to see another user\'s personal file area!');
- }
-
- $top_folder = \Folder::findTopFolder($user->id, 'user');
-
- if (!$top_folder) {
- $this->notFound("No folder found for user with id {$user_id}!");
- }
-
- return (new FileSystem())->getFolder($top_folder->id);
- }
-
- /**
- * Patches the course member data of a user and course. Pass data to be
- * patched via a valid json object in the body. Fields that my be patched:
- *
- * - group - the associated group in the overview of the users's courses
- * - visibility - visible state of the course
- *
- * @patch /user/:user_id/courses/:course_id
- *
- * @todo more patchable fields?
- */
- public function patchCourseGroup($user_id, $course_id)
- {
- $user = \User::find($user_id);
- if (!$user) {
- $this->notFound('User not found');
- }
-
- if ($user->id !== $GLOBALS['user']->id) {
- $this->halt(403, "You may not alter this user's data");
- }
-
- $member = \CourseMember::find([$course_id, $user->id]);
- if (!$member) {
- $this->notFound('You are not a member of the course');
- }
-
- if (isset($this->data['group'])) {
- if (!is_numeric($this->data['group']) || $this->data['group'] < 0 || $this->data['group'] > 8) {
- $this->halt(400, 'Given group is not inside the valid range 0..8');
- }
- $member->gruppe = $this->data['group'];
- }
-
- if (isset($this->data['visibility'])) {
- if (in_array($member->status, ['tutor', 'dozent'])) {
- $this->halt(400, 'You may not change the visibility status for this course since you are a teacher.');
- }
- if (!in_array($this->data['visibility'], ['yes', 'no'])) {
- $this->halt(400, 'Visibility may only be "yes" or "no".');
- }
- $member->visible = $this->data['visibility'];
- }
-
- if ($member->isDirty()) {
- $member->store();
- }
-
- $this->halt(204);
- }
-}
diff --git a/app/routes/UserConfig.php b/app/routes/UserConfig.php
deleted file mode 100644
index ba01538..0000000
--- a/app/routes/UserConfig.php
+++ /dev/null
@@ -1,99 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-use RESTAPI\RouteMap;
-use RESTAPI\Router;
-
-/**
- * API routes for accessing user config values.
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @license GPL2 or any later version
- * @since Stud.IP 3.4
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition user_id ^[0-9a-f]{1,32}$
- *
- * @status 404 if user does not exist
- * @status 403 if user may access the request config item
- */
-class UserConfig extends RouteMap
-{
- // Stores the user's config instance
- private $config;
-
- /**
- * Performs checks if the user exists and may actually access the
- * requested config.
- *
- * @param Router $router Instance of the api router
- * @param array $handler Detected handler router
- * @param array $parameters Parameters of the called route
- */
- public function before(Router $router, array $handler, array $parameters)
- {
- // Check whether user exist
- if (\User::find($parameters['user_id']) === null) {
- $this->error(404, sprintf('User %s not found', $parameters['user_id']));
- }
-
- // Check whether user accesses own config or user is root
- if ($parameters['user_id'] !== $GLOBALS['user']->id && $GLOBALS['user']->perms !== 'root') {
- $this->error(403, 'User may only access own config');
- }
-
- $this->config = \UserConfig::get($parameters['user_id']);
- }
-
- /**
- * Returns the value of a specific config entry for a given user
- *
- * @get /user/:user_id/config/:field
- *
- * @return mixed Value for the request config item
- * @status 404 if config item does not exist
- */
- public function getConfig($user_id, $field)
- {
- // Check whether key exists in config
- if (!isset($this->config[$field])) {
- $this->error(404, sprintf('No config item for field %s and user %s',
- $field, $user_id));
- }
-
- return $this->config[$field];
- }
-
- /**
- * Stored the value of a specific config entry for a given user
- *
- * @put /user/:user_id/config/:field
- *
- * @status 204 on success
- * @status 400 if no value is given
- */
- public function setConfig($user_id, $field)
- {
- if (!isset($this->data['value'])) {
- $this->error(400, 'No value given in request');
- }
-
- $this->config->store($field, $this->data['value']);
-
- $this->status(204);
- }
-
- /**
- * Removes a specific config entry for a given user
- *
- * @delete /user/:user_id/config/:field
- *
- * @status 204 on success
- */
- public function deleteConfig($user_id, $field)
- {
- $this->config->delete($field);
-
- $this->status(204);
- }
-}
diff --git a/app/routes/Wiki.php b/app/routes/Wiki.php
deleted file mode 100644
index 7f54628..0000000
--- a/app/routes/Wiki.php
+++ /dev/null
@@ -1,148 +0,0 @@
-<?php
-namespace RESTAPI\Routes;
-
-/**
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- *
- * @condition range_id ^[0-9a-f]{1,32}$
- */
-class Wiki extends \RESTAPI\RouteMap
-{
- public function before()
- {
- require_once 'User.php';
- }
-
- /**
- * Wikiseitenindex einer Veranstaltung
- *
- * @get /course/:range_id/wiki
- */
- public function getCourseWiki($range_id)
- {
- $pages = \WikiPage::findBySQL("`range_id` = ? ORDER BY `name` ASC", [$range_id]);
-
- if (!$pages[0]->isReadable()) {
- $this->error(401);
- }
-
- $total = sizeof($pages);
- $pages = $pages->limit($this->offset, $this->limit);
-
- $linked_pages = [];
- foreach ($pages as $page) {
- $url = $this->urlf('/course/%s/wiki/%s', [$range_id, htmlReady($page['keyword'])]);
- $linked_pages[$url] = $this->wikiPageToJson($page, ["content"]);
- }
-
- $this->etag(md5(serialize($linked_pages)));
-
- return $this->paginated($linked_pages, $total, compact('range_id'));
- }
-
- /**
- * Wikiseite auslesen
- *
- * @get /course/:range_id/wiki/:keyword
- * @get /course/:range_id/wiki/:keyword/:version
- */
- public function getCourseWikiKeyword($range_id, $keyword, $version = null)
- {
- $page = $this->requirePage($range_id, $keyword, $version);
- $wiki_json = $this->wikiPageToJson($page);
- $this->etag(md5(serialize($wiki_json)));
- $this->lastmodified($page->chdate);
- return $wiki_json;
- }
-
- /**
- * Wikiseite ändern/hinzufügen
- *
- * @put /course/:range_id/wiki/:keyword
- */
- public function putCourseWikiKeyword($range_id, $keyword)
- {
- if (!isset($this->data['content'])) {
- $this->error(400, 'No content provided');
- }
-
- $page =\WikiPage::findOneBySQL("`range_id` = ? AND `name` = ?", [$range_id, $keyword]);
- if (!$page) {
- $page = new \WikiPage();
- $page->range_id = $range_id;
- $page->name = $keyword;
- }
-
- if (!$page->isEditable()) {
- $this->error(401);
- }
-
- $page->content = $this->data['content'];
- $page->store();
-
- $url = sprintf('course/%s/wiki/%s/%d', htmlReady($range_id), htmlReady($keyword), count($page->versions) + 1);
- $this->redirect($url, 201, 'ok');
- }
-
- /**************************************************/
- /* PRIVATE HELPER METHODS */
- /**************************************************/
-
- private function requirePage($range_id, $keyword, $version = null)
- {
- $page = \WikiPage::findOneBySQL("`range_id` = ? AND `name` = ?", [$range_id, $keyword]);
-
- if (!$page) {
- $this->notFound();
- }
-
- if (!$page->isReadable($GLOBALS['user']->id)) {
- $this->error(401);
- }
- if ($version !== null && $version !== count($page->versions) + 1) {
- return $page->versions[count($page->versions) - 1 - $version];
- } else {
- return $page;
- }
- }
-
- private function wikiPageToJson($page, $without = [])
- {
- $json = [
- 'range_id' => $page->range_id,
- 'keyword' => $page->name,
- 'chdate' => $page->chdate,
- 'version' => 1
- ];
-
- // (pre-rendered) content
- if (!in_array('content', $without)) {
- $json['content'] = $page->content;
- $json['content_html'] = wikiReady($page->content, true, $page->range_id, $page->id);
- }
- if (!in_array('user', $without)) {
- if ($page->author) {
- $json['user'] = User::getMiniUser($this, $page->user_id);
- }
- }
-
- foreach ($without as $key) {
- if (isset($json[$key])) {
- unset($json[$key]);
- }
- }
-
- // string to int conversions as SORM does not know about ints
- foreach (['chdate', 'mkdate', 'filesize', 'downloads'] as $key) {
- if (isset($json[$key])) {
- $json[$key] = (int) $json[$key];
- }
- }
-
- return $json;
- }
-
-
-}
diff --git a/app/views/admin/api/config.php b/app/views/admin/api/config.php
deleted file mode 100644
index 83d2ae5..0000000
--- a/app/views/admin/api/config.php
+++ /dev/null
@@ -1,35 +0,0 @@
-<?php
-/**
- * @var Admin_ApiController $controller
- * @var array $config
- */
-use Studip\Button, Studip\LinkButton;
-?>
-
-<form class="default" action="<?= $controller->url_for('admin/api/config') ?>" method="post">
- <fieldset>
- <legend><?= _('Konfiguration') ?></legend>
-
- <input type="hidden" name="active" value="0">
- <label>
- <input type="checkbox" name="active" value="1" <? if ($config['API_ENABLED']) echo 'checked'; ?>>
- <?= _('REST-API aktiviert') ?>
- </label>
-
-
- <label class="caption" for="auth">
- <?= _('Standard-Authentifizierung beim Login') ?>
- <select name="auth" id="auth">
- <? foreach ($GLOBALS['STUDIP_AUTH_PLUGIN'] as $plugin): ?>
- <option <? if ($config['API_OAUTH_AUTH_PLUGIN'] === $plugin) echo 'selected'; ?>>
- <?= $plugin ?>
- </option>
- <? endforeach; ?>
- </select>
- </label>
- </fieldset>
- <footer>
- <?= Button::createAccept(_('Speichern')) ?>
- <?= LinkButton::createCancel(_('Abbrechen'), $controller->url_for('admin/api')) ?>
- </footer>
-</form>
diff --git a/app/views/admin/api/edit.php b/app/views/admin/api/edit.php
deleted file mode 100644
index f1c7e03..0000000
--- a/app/views/admin/api/edit.php
+++ /dev/null
@@ -1,136 +0,0 @@
-<?php
-/**
- * @var Admin_ApiController $controller
- * @var RESTAPI\Consumer\Base $consumer
- * @var array $types
- */
-use Studip\Button, Studip\LinkButton;
-?>
-
-<? if ($consumer->id): ?>
- <h1>
- <?= sprintf(
- _('Registrierte Applikation "%s" bearbeiten'),
- htmlReady($consumer->title)
- ) ?>
- </h1>
-<? else: ?>
- <h1 class="hide-in-dialog">
- <?= _('Neue Applikation registrieren') ?>
- </h1>
-<? endif; ?>
-
-<form class="settings default"
- action="<?= $controller->url_for('admin/api/edit', $consumer->id) ?>" method="post">
- <?= CSRFProtection::tokenTag() ?>
-
- <fieldset>
- <legend><?= _('Grundeinstellungen') ?></legend>
-
- <label for="active">
- <input type="checkbox" class="switch" id="active" name="active" value="1"
- <?= $consumer->active ? 'checked' : '' ?>>
- <?= _('Aktiviert') ?>
- </label>
-
-
- <label for="title">
- <?= _('Titel') ?>
- <input required type="text" id="title" name="title"
- placeholder="<?= _('Beispiel-Applikation') ?>"
- value="<?= htmlReady($consumer->title) ?>"
- maxlength="128">
- </label>
-
- <label for="contact">
- <?= _('Kontaktperson') ?>
- <input required type="text" id="contact" name="contact"
- placeholder="John Doe"
- value="<?= htmlReady($consumer->contact) ?>"
- maxlength="255">
- </label>
-
- <label for="email">
- <?= _('Kontaktadresse') ?>
- <input required type="text" id="email" name="email"
- placeholder="support@appsite.tld"
- value="<?= htmlReady($consumer->email) ?>"
- maxlength="255">
- </label>
-
- <label for="callback">
- <?= _('Callback URL') ?>
- <input required type="text" id="callback" name="callback"
- placeholder="http://appsite.tld/auth"
- value="<?= htmlReady($consumer->callback) ?>"
- maxlength="255">
- </label>
-
- <? if ($consumer->id): ?>
- <label for="consumer_key">
- <?= _('Consumer Key') ?>
- <input readonly type="text" id="consumer_key"
- value="<?= htmlReady($consumer->auth_key) ?>">
- </label>
-
- <label for="consumer_secret">
- <?= _('Consumer Secret') ?>
- <input readonly type="text" id="consumer_secret"
- value="<?= htmlReady($consumer->auth_secret) ?>">
- </label>
-
- <div class="centered">
- <?= strftime(_('Erstellt am %d.%m.%Y %H:%M:%S'), $consumer->mkdate) ?><br>
- <? if ($consumer->mkdate != $consumer->chdate): ?>
- <?= strftime(_('Zuletzt geändert am %d.%m.%Y %H:%M:%S'), $consumer->chdate) ?>
- <? endif; ?>
- </div>
- <? endif; ?>
- </fieldset>
-
- <fieldset>
- <legend><?= _('Applikation-Details') ?></legend>
-
- <label for="commercial">
- <input type="checkbox" class="switch" id="commercial" name="commercial" value="1"
- <?= $consumer->commercial ? 'checked' : '' ?>>
- <?= _('Kommerziell') ?>
- </label>
-
- <label for="description">
- <?= _('Beschreibung') ?>
- <textarea id="description" name="description" maxlength="65535"><?= htmlReady($consumer->description) ?></textarea>
- </label>
-
- <label for="url">
- <?= _('URL') ?>
- <input type="text" id="url" name="url"
- placeholder="http://appsite.tld"
- value="<?= htmlReady($consumer->url) ?>"
- maxlength="255">
- </label>
-
- <label for="type">
- <?= _('Typ') ?>
- <select name="type" id="type">
- <option value="">- <?= _('Keine Angabe') ?> -</option>
- <? foreach ($types as $type => $label): ?>
- <option value="<?= $type ?>" <?= $consumer->type == $type ? 'selected' : '' ?>>
- <?= $label ?>
- </option>
- <? endforeach; ?>
- </select>
- </label>
-
-
- <label for="notes">
- <?= _('Notizen') ?>
- <textarea id="notes" name="notes" maxlength="65535"><?= htmlReady($consumer->notes) ?></textarea>
- </label>
- </fieldset>
-
- <footer data-dialog-button>
- <?= Button::createAccept(_('Speichern'), 'store') ?>
- <?= LinkButton::createCancel(_('Abbrechen'), $controller->url_for('admin/api')) ?>
- </footer>
-</form>
diff --git a/app/views/admin/api/index.php b/app/views/admin/api/index.php
deleted file mode 100644
index 132deac..0000000
--- a/app/views/admin/api/index.php
+++ /dev/null
@@ -1,77 +0,0 @@
-<?php
-/**
- * @var Admin_ApiController $controller
- * @var RESTAPI\Consumer\Base[] $consumers
- * @var array $types
- */
-?>
-<? if (!empty($consumers)): ?>
-<form action="#" method="post" class="default">
-<table class="default">
- <caption><?= _('Registrierte Applikationen') ?></caption>
- <thead>
- <tr>
- <th><?= ('Aktiv') ?></th>
- <th><?= _('Name') ?></th>
- <th><?= _('Typ') ?></th>
- <th><?= _('Kontakt') ?></th>
- <th><?= _('Kommerziell') ?></th>
- <th>&nbsp;</th>
- </tr>
- </thead>
- <tbody>
-<? foreach ($consumers as $consumer): ?>
- <tr>
- <td id="<?= $consumer->id ?>">
- <a href="<?= $controller->url_for('admin/api/toggle', $consumer->id, $consumer->active ? 'off' : 'on') ?>">
- <?= Icon::create('checkbox-' . ($consumer->active ? '' : 'un') . 'checked', 'clickable')->asImg() ?>
- </a>
- </td>
- <td>
- <? if ($consumer->url): ?>
- <a href="<?= htmlReady($consumer->url) ?>" target="_blank" rel="noopener noreferrer">
- <?= htmlReady($consumer->title) ?>
- </a>
- <? else: ?>
- <?= htmlReady($consumer->title) ?>
- <? endif; ?>
- </td>
- <td><?= $types[$consumer->type] ?? '&nbsp;' ?></td>
- <td>
- <a href="mailto:<?= htmlReady($consumer->email) ?>">
- <?= htmlReady($consumer->contact) ?>
- </a>
- </td>
-
- <td><?= Icon::create('checkbox-' . ($consumer->commercial ? '' : 'un') . 'checked', 'clickable')->asImg() ?></td>
- <td class="actions">
- <a href="<?= $controller->url_for('admin/api/keys', $consumer->id) ?>"
- data-dialog="size=auto"
- title="<?= htmlReady(sprintf(_('Schlüssel anzeigen für Applikation "%s"'), $consumer->title)) ?>">
- <?= Icon::create('info-circle', 'clickable')->asImg() ?>
- </a>
- <a href="<?= $controller->url_for('admin/api/edit', $consumer->id) ?>" title="<?= _('Applikation bearbeiten') ?>" data-dialog>
- <?= Icon::create('edit', 'clickable')->asImg() ?>
- </a>
- <a href="<?= $controller->url_for('admin/api/permissions', $consumer->id) ?>" title="<?= _('Zugriffsberechtigungen verwalten') ?>">
- <?= Icon::create('admin', 'clickable')->asImg() ?>
- </a>
- <?= Icon::create('trash')->asInput([
- 'formaction' => $controller->url_for('admin/api/delete/', $consumer->id),
- 'title' => sprintf(_('Applikation "%s" entfernen'), $consumer->title),
- 'data-confirm' => '',
- 'style' => 'vertical-align: middle'
- ]) ?>
- </td>
- </tr>
-<? endforeach; ?>
- </tbody>
-</table>
-</form>
-
-<? else: ?>
-<p>
- <?= MessageBox::info(_('Es wurde noch keine Applikation registriert.'),
- [sprintf(_('Klicken Sie <a href="%s">hier</a>, um eine Applikation zu registrieren.'), $controller->url_for('admin/api/edit'))]) ?>
-</p>
-<? endif; ?>
diff --git a/app/views/admin/api/permissions.php b/app/views/admin/api/permissions.php
deleted file mode 100644
index 9eb48e3..0000000
--- a/app/views/admin/api/permissions.php
+++ /dev/null
@@ -1,62 +0,0 @@
-<?php
-/**
- * @var Admin_ApiController $controller
- * @var RESTAPI\ConsumerPermissions $permissions
- * @var string $consumer_id
- * @var array $routes
- * @var bool $global
- */
-?>
-<form action="<?= $controller->url_for('admin/api/permissions', $consumer_id) ?>" method="post" class="default">
-<table class="default">
- <thead>
- <tr>
- <th><?= _('Zugriff') ?></th>
- <th><?= _('Route') ?></th>
- <th><?= _('Methoden') ?></th>
- <th><?= _('Zugriff auf') ?></th>
- <th><?= _('Quelle') ?></th>
- </tr>
- </thead>
-<? foreach ($routes as $route => $methods): ?>
- <tbody>
-
- <? $i = 0; ?>
- <? foreach ($methods as $method => $info): ?>
- <tr style="vertical-align: top;">
- <td>
- <input type="hidden" name="permission[<?= urlencode($route) ?>][<?= urlencode($method) ?>]" value="0">
- <input type="checkbox" name="permission[<?= urlencode($route) ?>][<?= urlencode($method) ?>]"
- <? if (!$global || $global->check($route, $method)): ?>
- <? if ($permissions->check($route, $method)) echo 'checked'; ?>
- <? else: ?>
- disabled
- <? endif; ?>
- value="1">
- </td>
- <? if ($i++): ?>
- <td>&nbsp;</td>
- <? else: ?>
- <td><?= htmlReady($route) ?></td>
- <? endif; ?>
- <td><?= htmlReady($method) ?></td>
- <td><?= htmlReady($info['description']) ?></td>
- <td><?= $info['source'] ?></td>
- </tr>
- <? endforeach; ?>
- </tbody>
-<? endforeach; ?>
- <tfoot>
- <tr>
- <td>
- <label>
- <input type="checkbox" data-proxyfor="[name^=permission]:checkbox"> <?= _('Alle') ?>
- </label>
- </td>
- <td colspan="4">
- <?= Studip\Button::createAccept(_('Speichern'), 'store') ?>
- </td>
- </tr>
- </tfoot>
-</table>
-</form>
diff --git a/app/views/api/authorizations/index.php b/app/views/api/authorizations/index.php
deleted file mode 100644
index 95645f4..0000000
--- a/app/views/api/authorizations/index.php
+++ /dev/null
@@ -1,44 +0,0 @@
-<? use Studip\Button, Studip\LinkButton; ?>
-
-<? if (empty($consumers)): ?>
-<?= MessageBox::info(_('Sie haben noch keinen Apps Zugriff auf Ihren Account gewährt.')) ?>
-<? else: ?>
-<table class="oauth-apps default">
- <caption><?= _('Applikationen') ?></caption>
- <thead>
- <tr>
- <th><?= _('Name') ?></th>
- <th>&nbsp;</th>
- </thead>
- <tbody>
- <? foreach ($consumers as $consumer): ?>
- <tr>
- <td>
- <h3>
- <? if ($consumer->url): ?>
- <a href="<?= htmlReady($consumer->url) ?>" target="_blank" rel="noopener noreferrer">
- <?= htmlReady($consumer->title) ?>
- </a>
- <? else: ?>
- <?= htmlReady($consumer->title) ?>
- <? endif; ?>
- <? if (isset($types[$consumer->type])): ?>
- <small>(<?= htmlReady($types[$consumer->type]) ?>)</small>
- <? endif; ?>
- </h3>
- <? if ($consumer->description): ?>
- <p><?= htmlReady($consumer->description) ?></p>
- <? endif; ?>
- </td>
- <td class="actions">
- <?= LinkButton::createCancel(
- _('App entfernen'),
- $controller->url_for('api/authorizations/revoke', $consumer->id),
- ['data-confirm' => _('Wollen Sie der App wirklich den Zugriff auf Ihre Daten untersagen?')]
- ) ?>
- </td>
- </tr>
-<? endforeach; ?>
- </tbody>
-</table>
-<? endif; ?>
diff --git a/app/views/api/oauth/authorize.php b/app/views/api/oauth/authorize.php
deleted file mode 100644
index 6c66532..0000000
--- a/app/views/api/oauth/authorize.php
+++ /dev/null
@@ -1,34 +0,0 @@
-<section class="oauth authorize">
- <p>
- <?= sprintf(
- _('Die Applikation <strong>%s</strong> möchte auf Ihre Daten zugreifen.'),
- htmlReady($consumer->title)
- ) ?>
- </p>
-
- <form action="<?= $controller->url_for('api/oauth/authorize?oauth_token=' . $token) ?>" method="post">
- <input type="hidden" name="oauth_callback" value="<?= htmlReady($oauth_callback) ?>">
- <p>
- <?= Studip\Button::createAccept(_('Erlauben'), 'allow') ?>
- <?= Studip\LinkButton::createCancel(_('Verweigern'), $consumer->callback) ?>
- </p>
- </form>
-
- <p>
- <?= Avatar::getAvatar($GLOBALS['user']->id)->getImageTag(Avatar::SMALL) ?>
-
- <?= sprintf(
- _('Angemeldet als <strong>%s</strong> (%s)'),
- htmlReady($GLOBALS['user']->getFullName()),
- htmlReady($GLOBALS['user']->username)
- ) ?><br>
- <small>
- <a href="<?= URLHelper::getLink('logout.php') ?>">
- <?= sprintf(
- _('Sind sie nicht <strong>%s</strong>, so melden Sie sich bitte ab und versuchen es erneut.'),
- htmlReady($GLOBALS['user']->getFullName())
- ) ?>
- </a>
- </small>
- </p>
-</section>
diff --git a/app/views/api/oauth/authorized.php b/app/views/api/oauth/authorized.php
deleted file mode 100644
index e69de29..0000000
--- a/app/views/api/oauth/authorized.php
+++ /dev/null
diff --git a/composer.json b/composer.json
index 7098965..dfb4fe1 100644
--- a/composer.json
+++ b/composer.json
@@ -112,7 +112,6 @@
"league/oauth2-server": "8.5.4",
"willdurand/negotiation": "^3.1",
"monolog/monolog": "^2.8",
- "phpowermove/docblock": "^2.0",
"ksubileau/color-thief-php": "^2.0",
"symfony/polyfill-php82": "1.29.0",
"symfony/polyfill-php83": "1.29.0",
diff --git a/composer.lock b/composer.lock
index e4b114b..b41c344 100644
--- a/composer.lock
+++ b/composer.lock
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
- "content-hash": "d524d0543302bb6f60235cbdecb3f811",
+ "content-hash": "ffcafdbc6269da0a1c7581f0129d6f1b",
"packages": [
{
"name": "algo26-matthias/idna-convert",
@@ -2279,109 +2279,6 @@
"time": "2020-10-15T08:29:30+00:00"
},
{
- "name": "phootwork/collection",
- "version": "v2.1.3",
- "source": {
- "type": "git",
- "url": "https://github.com/phootwork/collection.git",
- "reference": "d58a0d7186074b601b016b9878b6fb65f6c23648"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/phootwork/collection/zipball/d58a0d7186074b601b016b9878b6fb65f6c23648",
- "reference": "d58a0d7186074b601b016b9878b6fb65f6c23648",
- "shasum": ""
- },
- "require": {
- "phootwork/lang": "^2.0",
- "php": ">=7.2"
- },
- "type": "library",
- "autoload": {
- "psr-4": {
- "phootwork\\collection\\": ""
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Thomas Gossmann",
- "homepage": "http://gos.si"
- }
- ],
- "description": "The phootwork library fills gaps in the php language and provides better solutions than the existing ones php offers.",
- "homepage": "https://phootwork.github.io/collection/",
- "keywords": [
- "Array object",
- "Text object",
- "collection",
- "collections",
- "json",
- "list",
- "map",
- "queue",
- "set",
- "stack",
- "xml"
- ],
- "support": {
- "issues": "https://github.com/phootwork/phootwork/issues",
- "source": "https://github.com/phootwork/collection/tree/v2.1.3"
- },
- "time": "2020-09-17T16:04:53+00:00"
- },
- {
- "name": "phootwork/lang",
- "version": "v2.1.3",
- "source": {
- "type": "git",
- "url": "https://github.com/phootwork/lang.git",
- "reference": "77402690535452da745cf11df33adc51a4ad89a1"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/phootwork/lang/zipball/77402690535452da745cf11df33adc51a4ad89a1",
- "reference": "77402690535452da745cf11df33adc51a4ad89a1",
- "shasum": ""
- },
- "require": {
- "php": ">=7.2",
- "symfony/polyfill-mbstring": "^1.12"
- },
- "type": "library",
- "autoload": {
- "psr-4": {
- "phootwork\\lang\\": ""
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Thomas Gossmann",
- "homepage": "http://gos.si"
- }
- ],
- "description": "Missing PHP language constructs",
- "homepage": "https://phootwork.github.io/lang/",
- "keywords": [
- "array",
- "comparator",
- "comparison",
- "string"
- ],
- "support": {
- "issues": "https://github.com/phootwork/phootwork/issues",
- "source": "https://github.com/phootwork/lang/tree/v2.1.3"
- },
- "time": "2021-02-15T17:24:43+00:00"
- },
- {
"name": "php-di/invoker",
"version": "2.3.4",
"source": {
@@ -2689,58 +2586,6 @@
"time": "2023-11-12T21:59:55+00:00"
},
{
- "name": "phpowermove/docblock",
- "version": "v2.0.1",
- "source": {
- "type": "git",
- "url": "https://github.com/phpowermove/docblock.git",
- "reference": "b96e2c9a14a6014fd8d932643c95b4d20638756a"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/phpowermove/docblock/zipball/b96e2c9a14a6014fd8d932643c95b4d20638756a",
- "reference": "b96e2c9a14a6014fd8d932643c95b4d20638756a",
- "shasum": ""
- },
- "require": {
- "phootwork/collection": "^2.0",
- "phootwork/lang": "^2.0",
- "php": ">=7.2"
- },
- "require-dev": {
- "phootwork/php-cs-fixer-config": "^0.2.2",
- "phpunit/phpunit": "^8.0",
- "psalm/phar": "^4.3"
- },
- "type": "library",
- "autoload": {
- "psr-4": {
- "gossi\\docblock\\": "src/"
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Thomas Gossmann",
- "homepage": "http://gos.si"
- }
- ],
- "description": "PHP Docblock parser and generator. An API to read and write Docblocks.",
- "keywords": [
- "docblock",
- "generator",
- "parser"
- ],
- "support": {
- "issues": "https://github.com/gossi/docblock/issues",
- "source": "https://github.com/phpowermove/docblock/tree/v2.0.1"
- },
- "time": "2021-02-17T11:36:51+00:00"
- },
- {
"name": "phpseclib/phpseclib",
"version": "3.0.37",
"source": {
diff --git a/db/migrations/1.127_setup_api.php b/db/migrations/1.127_setup_api.php
index 7cae3f9..73b36f6 100644
--- a/db/migrations/1.127_setup_api.php
+++ b/db/migrations/1.127_setup_api.php
@@ -1,12 +1,46 @@
<?php
class SetupApi extends Migration
{
- function description()
+ public function description()
{
return 'Creates api tables in database and according config entries';
}
- function up()
+ public function up()
+ {
+ $this->createTables();
+
+ // Add config entries
+ $query = "INSERT IGNORE INTO `config`
+ (`config_id`, `field`, `value`, `is_default`, `type`, `range`, `section`,
+ `mkdate`, `chdate`, `description`)
+ VALUES (MD5(:field), :field, :value, 1, :type, 'global', 'global',
+ UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), :description)";
+ $statement = DBManager::get()->prepare($query);
+
+ $statement->execute([
+ ':field' => 'API_ENABLED',
+ ':value' => (int)false,
+ ':type' => 'boolean',
+ ':description' => 'Schaltet die REST-API an',
+ ]);
+
+ $statement->execute([
+ ':field' => 'API_OAUTH_AUTH_PLUGIN',
+ ':value' => 'Standard',
+ ':type' => 'string',
+ ':description' => 'Definiert das für OAuth verwendete Authentifizierungsverfahren',
+ ]);
+ }
+
+ public function down()
+ {
+ DBManager::get()->exec("DELETE FROM config WHERE field IN ('API_ENABLED', 'API_OAUTH_AUTH_PLUGIN')");
+
+ $this->dropTables();
+ }
+
+ public function createTables(): void
{
// Add vendor tables
$query = "CREATE TABLE IF NOT EXISTS `oauth_consumer_registry` (
@@ -29,7 +63,7 @@ class SetupApi extends Migration
KEY `ocr_usa_id_ref` (`ocr_usa_id_ref`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
DBManager::get()->exec($query);
-
+
$query = "CREATE TABLE IF NOT EXISTS `oauth_consumer_token` (
`oct_id` int(11) NOT NULL AUTO_INCREMENT,
`oct_ocr_id_ref` int(11) NOT NULL,
@@ -47,7 +81,7 @@ class SetupApi extends Migration
CONSTRAINT `oauth_consumer_token_ibfk_1` FOREIGN KEY (`oct_ocr_id_ref`) REFERENCES `oauth_consumer_registry` (`ocr_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
DBManager::get()->exec($query);
-
+
$query = "CREATE TABLE IF NOT EXISTS `oauth_log` (
`olg_id` int(11) NOT NULL AUTO_INCREMENT,
`olg_osr_consumer_key` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
@@ -80,7 +114,7 @@ class SetupApi extends Migration
UNIQUE KEY `osn_consumer_key` (`osn_consumer_key`,`osn_token`,`osn_timestamp`,`osn_nonce`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
DBManager::get()->exec($query);
-
+
$query = "CREATE TABLE IF NOT EXISTS `oauth_server_registry` (
`osr_id` int(11) NOT NULL AUTO_INCREMENT,
`osr_usa_id_ref` int(11) DEFAULT NULL,
@@ -176,39 +210,16 @@ class SetupApi extends Migration
PRIMARY KEY (`user_id`,`consumer_id`)
) ENGINE=MyISAM";
DBManager::get()->exec($query);
-
- // Add config entries
- $query = "INSERT IGNORE INTO `config`
- (`config_id`, `field`, `value`, `is_default`, `type`, `range`, `section`,
- `mkdate`, `chdate`, `description`)
- VALUES (MD5(:field), :field, :value, 1, :type, 'global', 'global',
- UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), :description)";
- $statement = DBManager::get()->prepare($query);
-
- $statement->execute([
- ':field' => 'API_ENABLED',
- ':value' => (int)false,
- ':type' => 'boolean',
- ':description' => 'Schaltet die REST-API an',
- ]);
-
- $statement->execute([
- ':field' => 'API_OAUTH_AUTH_PLUGIN',
- ':value' => 'Standard',
- ':type' => 'string',
- ':description' => 'Definiert das für OAuth verwendete Authentifizierungsverfahren',
- ]);
}
- function down()
+ public function dropTables(): void
{
- DBManager::get()->exec("DELETE FROM config WHERE field IN ('API_ENABLED', 'API_OAUTH_AUTH_PLUGIN')");
DBManager::get()->exec("DROP TABLE IF EXISTS `oauth_consumer_registry`,
`oauth_consumer_token`,
`oauth_log`,
`oauth_server_nonce`,
`oauth_server_registry`,
- `oauth_server_token`
+ `oauth_server_token`,
`api_consumer_permissions`,
`api_consumers`,
`api_oauth_user_mapping`,
diff --git a/db/migrations/5.1.34_activate_semester_routes.php b/db/migrations/5.1.34_activate_semester_routes.php
index 082a5db..21cbb64 100644
--- a/db/migrations/5.1.34_activate_semester_routes.php
+++ b/db/migrations/5.1.34_activate_semester_routes.php
@@ -8,7 +8,9 @@ class ActivateSemesterRoutes extends Migration
public function up()
{
- require_once 'app/routes/Semester.php';
- RESTAPI\ConsumerPermissions::get()->activateRouteMap(new RESTAPI\Routes\Semester());
+ // Deactivated since the restapi was removed in Stud.IP 6.0
+
+ # require_once 'app/routes/Semester.php';
+ # RESTAPI\ConsumerPermissions::get()->activateRouteMap(new RESTAPI\Routes\Semester());
}
}
diff --git a/db/migrations/6.0.10_remove_restapi.php b/db/migrations/6.0.10_remove_restapi.php
new file mode 100644
index 0000000..5062916
--- /dev/null
+++ b/db/migrations/6.0.10_remove_restapi.php
@@ -0,0 +1,63 @@
+<?php
+final class RemoveRestapi extends Migration
+{
+ private Migration $other_migration;
+
+ public function __construct($verbose = false)
+ {
+ parent::__construct($verbose);
+
+ require_once __DIR__ . '/1.127_setup_api.php';
+ $this->other_migration = new SetupApi($verbose);
+ }
+
+ public function description()
+ {
+ return 'Removes the deprecated REST API (essentially reverts migration 1.127)';
+ }
+
+ protected function up()
+ {
+ $this->other_migration->dropTables();
+
+ // Delete config
+ $query = "DELETE `config`, `config_values`
+ FROM `config`
+ LEFT JOIN `config_values` USING(`field`)
+ WHERE `field` IN ('API_ENABLED', 'API_OAUTH_AUTH_PLUGIN')";
+ DBManager::get()->exec($query);
+
+ // Disable all RESTAPI-Plugins
+ $query = "UPDATE `plugins`
+ SET `enabled` = 'no'
+ WHERE FIND_IN_SET('RESTAPIPlugin', `plugintype`)";
+ DBManager::get()->exec($query);
+ }
+
+ protected function down()
+ {
+ // Add config entries
+ $query = "INSERT IGNORE INTO `config`
+ (`field`, `value`, `type`, `range`, `section`,
+ `mkdate`, `chdate`, `description`)
+ VALUES (:field, :value, :type, 'global', 'global',
+ UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), :description)";
+ $statement = DBManager::get()->prepare($query);
+
+ $statement->execute([
+ ':field' => 'API_ENABLED',
+ ':value' => 0,
+ ':type' => 'boolean',
+ ':description' => 'Schaltet die REST-API an',
+ ]);
+
+ $statement->execute([
+ ':field' => 'API_OAUTH_AUTH_PLUGIN',
+ ':value' => 'Standard',
+ ':type' => 'string',
+ ':description' => 'Definiert das für OAuth verwendete Authentifizierungsverfahren',
+ ]);
+
+ $this->other_migration->createTables();
+ }
+}
diff --git a/lib/activities/DocumentsProvider.php b/lib/activities/DocumentsProvider.php
index 0a770de..fae5df2 100644
--- a/lib/activities/DocumentsProvider.php
+++ b/lib/activities/DocumentsProvider.php
@@ -29,7 +29,6 @@ class DocumentsProvider implements ActivityProvider
if ($activity->context == "course") {
$url = \URLHelper::getUrl("dispatch.php/course/files/flat?cid={$activity->context_id}");
- $route = \URLHelper::getURL('api.php/file/' . $activity->object_id, NULL, true);
$activity->object_url = [
$url => _('Zum Dateibereich der Veranstaltung')
@@ -43,8 +42,6 @@ class DocumentsProvider implements ActivityProvider
];
}
- $activity->object_route = $route;
-
return true;
}
diff --git a/lib/activities/ForumProvider.php b/lib/activities/ForumProvider.php
index f543947..6a958eb 100644
--- a/lib/activities/ForumProvider.php
+++ b/lib/activities/ForumProvider.php
@@ -30,14 +30,10 @@ class ForumProvider implements ActivityProvider
.'?cid='. $post['seminar_id'] .'&highlight_topic='. $post['topic_id']
.'#'. $post['topic_id']);
- $route = \URLHelper::getURL('api.php/forum_entry/' . $post['topic_id'], NULL, true);
-
$activity->object_url = [
$url => _('Zum Forum der Veranstaltung')
];
- $activity->object_route = $route;
-
return true;
}
diff --git a/lib/activities/MessageProvider.php b/lib/activities/MessageProvider.php
index 9d16831..0db2ad8 100644
--- a/lib/activities/MessageProvider.php
+++ b/lib/activities/MessageProvider.php
@@ -30,14 +30,10 @@ class MessageProvider implements ActivityProvider
$url = \URLHelper::getUrl("dispatch.php/messages/read/{$message->id}", ['cid' => null]);
- $route = \URLHelper::getURL('api.php/message/' . $message->id, NULL, true);
-
$activity->object_url = [
$url => _('Zur Nachricht')
];
- $activity->object_route = $route;
-
return true;
}
diff --git a/lib/activities/NewsProvider.php b/lib/activities/NewsProvider.php
index eed7fe7..8f1c5f4 100644
--- a/lib/activities/NewsProvider.php
+++ b/lib/activities/NewsProvider.php
@@ -116,10 +116,8 @@ class NewsProvider implements ActivityProvider
.'</b><br>'. formatReady((string) $news->body);
$url = self::getUrlForContext($news, $activity);
- $route = \URLHelper::getURL('api.php/news/' . $news->id, NULL, true);
$activity->object_url = $url;
- $activity->object_route = $route;
return true;
}
diff --git a/lib/activities/ParticipantsProvider.php b/lib/activities/ParticipantsProvider.php
index 50bad46..7dc71fd 100644
--- a/lib/activities/ParticipantsProvider.php
+++ b/lib/activities/ParticipantsProvider.php
@@ -62,14 +62,10 @@ class ParticipantsProvider implements ActivityProvider
$url = \URLHelper::getUrl("dispatch.php/course/members/index", ['cid' => $activity->context_id]);
- $route = \URLHelper::getURL('api.php/course/' . $activity->context_id, NULL, true);
-
$activity->object_url = [
$url => _('Zur Veranstaltung')
];
- $activity->object_route = $route;
-
return true;
}
diff --git a/lib/activities/ScheduleProvider.php b/lib/activities/ScheduleProvider.php
index 208b9b3..73ca7f5 100644
--- a/lib/activities/ScheduleProvider.php
+++ b/lib/activities/ScheduleProvider.php
@@ -20,14 +20,11 @@ class ScheduleProvider implements ActivityProvider
$activity->content = htmlReady($activity->content);
$url = \URLHelper::getUrl("dispatch.php/course/dates?cid={$activity->context_id}");
- $route = \URLHelper::getURL('api.php/course/' . $activity->context_id . '/events', NULL, true);
$activity->object_url = [
$url => _('Zum Ablaufplan der Veranstaltung')
];
- $activity->object_route = $route;
-
return true;
}
diff --git a/lib/activities/WikiProvider.php b/lib/activities/WikiProvider.php
index f3a8bbf..7a5266f 100644
--- a/lib/activities/WikiProvider.php
+++ b/lib/activities/WikiProvider.php
@@ -27,23 +27,17 @@ class WikiProvider implements ActivityProvider
if ($activity->context === 'course') {
$url = \URLHelper::getURL('dispatch.php/course/wiki/page/' . $page->id, ['cid' => $activity->context_id]);
- $route = \URLHelper::getURL("api.php/course/{$activity->context_id}/wiki/{$activity->object_id}", null, true);
$activity->object_url = [
$url => _('Zum Wiki der Veranstaltung'),
];
- $activity->object_route = $route;
-
} elseif ($activity->context === 'institute') {
$url = \URLHelper::getURL('dispatch.php/course/wiki/page/' . $page->id, ['cid' => $activity->context_id]);
- $route= null;
$activity->object_url = [
$url => _('Zum Wiki der Einrichtung')
];
-
- $activity->object_route = $route;
}
return true;
diff --git a/lib/bootstrap-api.php b/lib/bootstrap-api.php
deleted file mode 100644
index ffa0b40..0000000
--- a/lib/bootstrap-api.php
+++ /dev/null
@@ -1,40 +0,0 @@
-<?php
-/**
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-
-namespace {
- StudipAutoloader::addAutoloadPath($GLOBALS['STUDIP_BASE_PATH'] . '/vendor/oauth-php/library');
-
- // Set base url for URLHelper class
- URLHelper::setBaseUrl($GLOBALS['CANONICAL_RELATIVE_PATH_STUDIP']);
-}
-
-namespace RESTAPI {
- use Studip, OAuthStore;
-
- // Define api version
- const VERSION = '2';
-
- $router = Router::getInstance();
-
- // Register JSON content renderer
- $router->registerRenderer(new Renderer\JSONRenderer, true);
-
- // If in development mode, register debug content renderer
- if (defined('Studip\\ENV') && Studip\ENV === 'development') {
- $router->registerRenderer(new Renderer\DebugRenderer);
- }
-
- OAuthStore::instance('PDO', [
- 'dsn' => 'mysql:host=' . $GLOBALS['DB_STUDIP_HOST']
- . ';dbname=' . $GLOBALS['DB_STUDIP_DATABASE'],
- 'username' => $GLOBALS['DB_STUDIP_USER'],
- 'password' => $GLOBALS['DB_STUDIP_PASSWORD']
- ]);
-
- // Register default consumers
- Consumer\Base::addType('http', 'RESTAPI\\Consumer\\HTTP');
- Consumer\Base::addType('studip', 'RESTAPI\\Consumer\\Studip');
- Consumer\Base::addType('oauth', 'RESTAPI\\Consumer\\OAuth');
-}
diff --git a/lib/classes/restapi/ConsumerPermissions.php b/lib/classes/restapi/ConsumerPermissions.php
deleted file mode 100644
index 8fc2252..0000000
--- a/lib/classes/restapi/ConsumerPermissions.php
+++ /dev/null
@@ -1,212 +0,0 @@
-<?php
-namespace RESTAPI;
-use DBManager, PDO;
-
-/**
- * REST API routing permissions
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class ConsumerPermissions
-{
- /**
- * Create a permission object (for a certain consumer).
- * Permissions object will be cached for each consumer.
- *
- * @param mixed $consumer_id Id of consumer (optional, defaults to global)
- * @return ConsumerPermissions Returns permissions object
- */
- public static function get($consumer_id = null)
- {
- static $cache = [];
- if (!isset($cache[$consumer_id])) {
- $cache[$consumer_id] = new self($consumer_id);
- }
-
- return $cache[$consumer_id];
- }
-
- private $consumer_id;
- private $permissions = [];
-
- /**
- * Creates the actual permission object (for a certain consumer).
- *
- * @param mixed $consumer_id Id of consumer (optional, defaults to global)
- */
- private function __construct($consumer_id = null)
- {
- $this->consumer_id = $consumer_id;
-
- // Init with global permissions
- $this->loadPermissions('global', true);
-
- // Specific consumers permissions?
- if ($consumer_id) {
- $this->loadPermissions($consumer_id, false);
- }
- }
-
- /**
- * Defines whether access if allowed for the current consumer to the
- * passed route via the passed method.
- *
- * @param String $route_id Route template (hash)
- * @param String $method HTTP method
- * @param mixed $granted Granted state (PHP'ish boolean)
- * @param bool $overwrite May values be overwritten
- * @return bool Indicates if value could be changed.
- */
- public function set($route_id, $method, $granted, $overwrite = false)
- {
- // If route_id is not an md5 hash, convert it
- if (!preg_match('/^[0-9a-f]{32}$/', $route_id)) {
- $route_id = md5($route_id);
- }
-
- if (!isset($this->permissions[$route_id])) {
- // Skip if not globally set and not allowed to overwrite
- if (!$overwrite) {
- return false;
- }
- $this->permissions[$route_id] = [];
- }
-
- // overwrite only if globally allowed
- if (!$overwrite && empty($this->permissions[$route_id][$method])) {
- return false;
- }
-
- $this->permissions[$route_id][$method] = (bool) $granted;
-
- return true;
- }
-
- /**
- * Convenience method for activating all routes in a route map.
- *
- * @param \RESTAPI\RouteMap $routemap RouteMap to activate
- */
- public function activateRouteMap(RouteMap $routemap)
- {
- foreach ($routemap->getRoutes() as $method => $routes) {
- foreach (array_keys($routes) as $route) {
- $this->set($route, $method, true, true);
- }
- }
-
- $this->store();
- }
-
- /**
- * Removes stored permissions for a given route and method.
- *
- * @param String $route_id Route template
- * @param String $method HTTP method
- * @return bool
- */
- public function remove($route_id, $method)
- {
- if (!isset($this->permissions[$route_id][$method])) {
- return false;
- }
-
- unset($this->permissions[$route_id][$method]);
-
- if (count($this->permissions[$route_id]) === 0) {
- unset($this->permissions[$route_id]);
- }
-
- return true;
- }
-
- /**
- * Convenience method for deactivating all routes in a route map.
- *
- * @param \RESTAPI\RouteMap $routemap RouteMap to activate
- */
- public function deactivateRouteMap(RouteMap $routemap)
- {
- foreach ($routemap->getRoutes() as $method => $routes) {
- foreach (array_keys($routes) as $route) {
- $this->remove($route, $method);
- }
- }
-
- $this->store();
- }
-
- /**
- * Loads permissions for passed consumer.
- *
- * @param String $consumer_id Id of the consumer in question
- * @param bool $overwrite May values be overwritten
- * @return ConsumerPermissions Returns instance of self to allow chaining
- */
- protected function loadPermissions($consumer_id, $overwrite = false)
- {
- $query = "SELECT route_id, method, granted
- FROM api_consumer_permissions
- WHERE consumer_id = IFNULL(:consumer_id, 'global')";
- $statement = DBManager::get()->prepare($query);
- $statement->bindValue(':consumer_id', $consumer_id);
- $statement->execute();
- $permissions = $statement->fetchAll(PDO::FETCH_ASSOC);
-
- // Init with global permissions
- foreach ($permissions as $permission) {
- extract($permission);
-
- $this->set($route_id, $method, $granted, $overwrite);
- }
-
- return $this;
- }
-
- /**
- * Checks if access to passed route via passed method is allowed for
- * the current consumer.
- *
- * @param String $route Route template
- * @param String $method HTTP method
- * @return bool Indicates whether access is allowed
- */
- public function check($route, $method)
- {
- $route_id = md5($route);
-
- return isset($this->permissions[$route_id][$method])
- && $this->permissions[$route_id][$method];
- }
-
- /**
- * Stores the set permissions.
- *
- * @return bool Returns true if permissions were stored successfully
- */
- public function store()
- {
- $result = true;
-
- $query = "INSERT INTO api_consumer_permissions (route_id, consumer_id, method, granted)
- VALUES (:route, IFNULL(:consumer_id, 'global'), :method, :granted)
- ON DUPLICATE KEY UPDATE granted = VALUES(granted)";
- $statement = DBManager::get()->prepare($query);
- $statement->bindValue(':consumer_id', $this->consumer_id);
-
- foreach ($this->permissions as $route_id => $methods) {
- $statement->bindParam(':route', $route_id);
- foreach ($methods as $method => $granted) {
- $statement->bindParam(':method', $method);
- $granted = (int) !empty($granted);
- $statement->bindParam(':granted', $granted);
- $result = $result && $statement->execute();
- }
- }
-
- return $result;
- }
-}
diff --git a/lib/classes/restapi/Response.php b/lib/classes/restapi/Response.php
deleted file mode 100644
index 56d9b65..0000000
--- a/lib/classes/restapi/Response.php
+++ /dev/null
@@ -1,148 +0,0 @@
-<?php
-namespace RESTAPI;
-
-/**
- * Response class for the rest api
- *
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class Response implements \ArrayAccess
-{
- public $body, $status, $headers;
-
- /**
- * Constructor, sets vital information if provided.
- *
- * @param String $body Body contents of the response, optional,
- * defaults to empty string
- * @param int $status HTTP status code, optional, defaults to 200
- * @param Array $headers HTTP headers, optional, defaults to no headers
- */
- public function __construct($body = '', $status = 200, $headers = [])
- {
- $this->body = $body;
- $this->status = (int) $status;
- $this->headers = (array) $headers;
- }
-
- /**
- * Detects whether the response status is of success type (HTTP status 2xx)
- *
- * @return bool True if status is of success type, false otherwise
- */
- public function isSuccess()
- {
- return 200 <= $this->status && $this->status <= 299;
- }
-
- /**
- * Finishes the response with the given response renderer.
- *
- * @param Renderer\DefaultRenderer $content_renderer Used response renderer,
- * only applied if body is
- * not a callable closure
- */
- public function finish($content_renderer)
- {
- if (!is_callable($this->body)) {
- $content_renderer->render($this);
- }
- }
-
- /**
- * Sends the response.
- */
- public function output()
- {
- if (isset($this->status)) {
- if (mb_strpos(PHP_SAPI, 'cgi') === 0) {
- $this->sendHeader(sprintf('Status: %d %s', $this->status, $this->reason()));
- } else {
- $this->sendHeader(sprintf('HTTP/1.1 %d %s', $this->status, $this->reason()));
- }
- }
-
- foreach ($this->headers as $k => $v) {
- $this->sendHeader("$k: $v", false, $this->status);
- }
-
- if (is_callable($this->body)) {
- call_user_func($this->body);
- } else {
- echo $this->body;
- }
- }
-
- /**
- * Internally used function to actually send headers
- *
- * @param string the HTTP header
- * @param bool optional; TRUE if previously sent header should be
- * replaced - FALSE otherwise (default)
- * @param integer optional; the HTTP response code
- *
- * @return void
- */
- public function sendHeader($header, $replace = FALSE, $status = NULL) {
- if (isset($status)) {
- header($header, $replace, $status);
- }
- else {
- header($header, $replace);
- }
- }
-
- /**
- * Returns the reason phrase of this response according to RFC2616.
- *
- * @return string the reason phrase for this response's status
- */
- public function reason() {
- $reason = [
- 100 => 'Continue', 'Switching Protocols',
- 200 => 'OK', 'Created', 'Accepted', 'Non-Authoritative Information',
- 'No Content', 'Reset Content', 'Partial Content',
- 300 => 'Multiple Choices', 'Moved Permanently', 'Found', 'See Other',
- 'Not Modified', 'Use Proxy', '(Unused)', 'Temporary Redirect',
- 400 => 'Bad Request', 'Unauthorized', 'Payment Required','Forbidden',
- 'Not Found', 'Method Not Allowed', 'Not Acceptable',
- 'Proxy Authentication Required', 'Request Timeout', 'Conflict',
- 'Gone', 'Length Required', 'Precondition Failed',
- 'Request Entity Too Large', 'Request-URI Too Long',
- 'Unsupported Media Type', 'Requested Range Not Satisfiable',
- 'Expectation Failed',
- 500 => 'Internal Server Error', 'Not Implemented', 'Bad Gateway',
- 'Service Unavailable', 'Gateway Timeout',
- 'HTTP Version Not Supported'];
-
- return isset($reason[$this->status]) ? $reason[$this->status] : '';
- }
-
- // array access methods for headers
-
- public function offsetExists($offset): bool
- {
- return isset($this->headers[$offset]);
- }
-
- /**
- * @param $offset
- */
- public function offsetGet($offset): mixed
- {
- return @$this->headers[$offset];
- }
-
- public function offsetSet($offset, $value): void
- {
- $this->headers[$offset] = $value;
- }
-
- public function offsetUnset($offset): void
- {
- unset($this->headers[$offset]);
- }
-}
diff --git a/lib/classes/restapi/RouteMap.php b/lib/classes/restapi/RouteMap.php
deleted file mode 100644
index b8ad2f4..0000000
--- a/lib/classes/restapi/RouteMap.php
+++ /dev/null
@@ -1,1060 +0,0 @@
-<?php
-namespace RESTAPI;
-
-use Config;
-use Request;
-use gossi\docblock\Docblock;
-
-/**
- * RouteMaps define and group routes to resources.
- *
- * Instances of RouteMaps are registered with the RESTAPI\Router to
- * participate in the routing business.
- *
- * A RouteMap defines at least one handler method which has to be
- * annotated with one of these annotations correlating to HTTP request
- * methods:
- *
- * @code
- * / * *
- * * An example handler method
- * *
- * * @get /foo
- * * @post /bar/:id
- * * @put /baz/:id/:other_id
- * * @delete /
- * * /
- * public function anyMethodName($id, $other_id = null) {}
- * @endcode
- *
- * By default, all API routes are unaccessible for nobody users.
- * To explicitly allow access for nobody users, add the allow_nobody
- * tag to the handler method's doc block. Example:
- *
- * @code
- * / * *
- * * Another example handler method
- * *
- * * @get /foo
- * *
- * * @allow_nobody
- * * /
- * @endcode
- *
- * As soon as the Router matches a HTTP request to a handler defined
- * in a RouteMap, it calls RouteMap::init to initialize it and
- * especially the instance field `$this->response` of type
- * RESTAPI\Response. You do not call RouteMap::init on your own.
- *
- * After the router has initialized this RouteMap, the router tries to
- * call a method `before` of this signature:
- *
- * @code
- * public function before(Router $router, Array $handler, Array $parameters);
- * @endcode
- *
- * The parameter `$handler` is a callable (as in function is_callable)
- * consisting of the instance of this RouteMap and the name of a
- * method of this instance. You may change the values of this array to
- * redirect to another handler.
- *
- * The parameter `$parameters` is an associative array whose keys
- * correlate to the placeholders in the matched URI template. The
- * values are the actual values of that placeholders in regard to the
- * HTTP request.
- *
- *
- * After calling RouteMap::before control is transfered to the actual
- * handler method. The values of the placeholders in the URI template
- * of the annotation are send as arguments to the handler.
- *
- * Example: We have got this handler method defined:
- *
- * @code
- * / * *
- * * @get /foo/:id/bar/:other_id
- * * /
- * public function fooHandler($id, $other_id) {
- * }
- * @endcode
- *
- * The router receives a request like this: `http://[..]/foo/1/bar/2`
- * and matches it to our `fooHandler` which is then called something
- * like that:
- *
- * @code
- * $result = $routeMap->fooHandler(1, 2);
- * @endcode
- *
- * In your handler methods you have to process the input and return
- * some output data, which is then rendered in an appropriate way
- * after negotiating the content format in the Router.
- *
- * Thus the return value of your handler method becomes the body of
- * the HTTP response.
- *
- *
- * The RouteMap class defines several methods to ease up your work
- * with the HTTP specifica.
- *
- * The methods RouteMap::status, RouteMap::headers and RouteMap::body
- * correlate to the components of a HTTP response.
- *
- * There are helpers for returning paginated collections, see
- * RouteMap::paginated.
- *
- * If you encounter an error or have to stop further processing, see
- * methods RouteMap::halt, RouteMap::error and RouteMap::notFound.
- *
- * These methods are \a DISRUPTIVE as they immediately stop the control
- * flow in your handler:
- *
- * @code
- * public function fooHandler($id)
- * {
- * // do something
- *
- * $this->halt();
- *
- * // this line will never be reached
- * }
- * @endcode
- *
- * If you want to simply send a redirection response (HTTP status code
- * of 302 or 303), you may find calling RouteMap::redirect helpful.
- *
- * To generate a URL to a handler, use RouteMap::url
- *
- * When you find the need to return the content of a file, please see
- * RouteMap::sendFile which will help you with streaming it to the
- * client. For custom streaming just return a Closure from your
- * handler method.
- *
- * There are several other methods which you may find useful each
- * matching a HTTP header:
- *
- * - RouteMap::contentType
- * - RouteMap::etag
- * - RouteMap::expires
- * - RouteMap::cacheControl
- * - RouteMap::lastModified
- *
- * You can access the data sent in the body of the current HTTP
- * request using the `$this->data` instance variable.
- *
- * - If the request was of Content-Type `application/json`, the
- * body of the request is decoded using `json_decode`.
- * - If the request was of Content-Type
- * `application/x-www-form-urlencoded`, the body of the request is
- * decoded using `parse_str`.
- * - Otherwise the request will not be parsed and `$this->data` will
- * just contain the raw string.
- *
- * NOTE: The result of the described parsing will always contain
- * strings encoded in windows-1252. If the original body
- * was UTF-8 encoded, it is automatically re-encoded to windows-1252.
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-abstract class RouteMap
-{
- protected $router;
- protected $route;
- protected $data = null;
- protected $response;
-
- /**
- * Internal property which is used by RouteMap::paginated and
- * contains everything about a paginated collection.
- */
- protected $pagination = false;
-
- /**
- * The offset into a RouteMap::paginated collection as requested
- * by the client.
- */
- protected $offset;
-
- /**
- * The limit of a RouteMap::paginated collection as requested
- * by the client.
- */
- protected $limit;
-
- /**
- * Constructor of the route map. Initializes neccessary offset and limit
- * parameters for pagination.
- */
- public function __construct()
- {
- $this->offset = Request::int('offset', 0);
- $this->limit = Request::int('limit', Config::get()->ENTRIES_PER_PAGE);
- }
-
- /**
- * Initializes the route map by binding it to a router and passing in
- * the current route.
- *
- * @param Router $router Router to bind this route map to
- * @param array $route The matched route out of Router::matchRoute;
- * an array with keys 'handler', 'conditions' and
- * 'source'
- */
- public function init($router, $route)
- {
- $this->router = $router;
- $this->route = $route;
- $this->response = new Response();
-
- if ($mediaType = $this->getRequestMediaType()) {
- $this->data = $this->parseRequestBody($mediaType);
- }
- }
-
- /**
- * Marks this chunk of data as a slice of a larger data set with
- * a sum of "total" entries.
- *
- * @param mixed $data Chunk of data (should be sliced according
- * to current offset and limit parameters).
- * @param int $total The total number of data entries in the
- * according set.
- * @param array $uri_params Neccessary parameters when generating uris
- * for the current route.
- * @param array $query_params Optional query parameters.
- */
- public function paginated($data, $total, $uri_params = [], $query_params = [])
- {
- $uri = $this->url($this->route['uri_template']->inject($uri_params), $query_params);
-
- $this->paginate($uri, $total);
- return $this->collect($data);
- }
-
-
- /**
- * Low level method for paginating collections. You better use
- * RouteMap::paginated instead of this.
- *
- * Set the pagination data used by the RouteMap::collect.
- *
- * @param String $uri_format
- * @param int $total
- * @param mixed $offset
- * @param mixed $limit
- *
- * @return Routemap Returns instance of self to allow chaining
- */
- public function paginate($uri_format, $total, $offset = null, $limit = null)
- {
- $total = (int)$total;
- $offset = (int)($offset ?: $this->offset ?: 0);
- $limit = (int)($limit ?: $this->limit);
-
- $this->pagination = compact('uri_format', 'total', 'offset', 'limit');
-
- return $this;
- }
-
- /**
- * Low level method for paginating collections. You better use
- * RouteMap::paginated instead of this.
- *
- * Adjusts the result set to return a collection. A collection consists
- * of the passed data array and the associated pagination information
- * if available.
- *
- * Be aware that the passed data has to be already sliced according to
- * the pagination information.
- *
- * @param array $data Actual dataset
- * @return array Collection "object"
- */
- public function collect($data)
- {
- $collection = [
- 'collection' => $data
- ];
- if (is_array($this->pagination)) {
- extract($this->pagination);
-
- $offset = $offset - $offset % $limit;
- $max = ($total % $limit)
- ? $total - $total % $limit
- : $total - $limit;
-
- $pagination = compact('total', 'offset', 'limit');
- if ($total > $limit) {
- $links = [];
-
- foreach ([
- 'first' => 0,
- 'previous' => max(0, $offset - $limit),
- 'next' => min($max, $offset + $limit),
- 'last' => $max]
- as $key => $offset)
- {
- $links[$key] = \URLHelper::getURL($uri_format, compact('offset', 'limit'));
- }
-
- $pagination['links'] = $links;
- }
- $collection['pagination'] = $pagination;
- }
- return $collection;
- }
-
- /************************/
- /* REQUEST BODY METHODS */
- /************************/
-
- // find the requested media type
- private function getRequestMediaType()
- {
- if (!empty($_SERVER['CONTENT_TYPE'])) {
- $contentTypeParts = preg_split('/\s*[;,]\s*/', $_SERVER['CONTENT_TYPE']);
- return mb_strtolower($contentTypeParts[0]);
- }
- }
-
- // media-types that we know how to process
- private static $mediaTypes = [
- 'application/json' => 'parseJson',
- 'application/x-www-form-urlencoded' => 'parseFormEncoded',
- 'multipart/form-data' => 'parseMultipartFormdata'
- ];
-
- // cache the request body
- private static $_request_body;
-
- // reads the HTTP request body
- private function parseRequestBody($mediaType)
- {
- // read it only once
- if (!isset(self::$_request_body)) {
- self::$_request_body = file_get_contents('php://input');
- }
-
- if (isset(self::$mediaTypes[$mediaType])) {
- $result = call_user_func([__CLASS__, self::$mediaTypes[$mediaType]], self::$_request_body);
- if ($result) {
- return $result;
- }
- }
- return self::$_request_body;
- }
-
- // strategy to decode JSON strings
- private static function parseJson($input)
- {
- return json_decode($input, true);
- }
-
- // strategy to decode form encoded strings
- private static function parseFormEncoded($input)
- {
- parse_str($input, $result);
- return $result;
- }
-
- // strategy to decode a multipart message. Used for file-uploads.
- private static function parseMultipartFormdata($input)
- {
-
- $data = [];
- if (Request::isPost()) {
- foreach ($_POST as $key => $value) {
- $data[$key] = $value;
- }
- $data['_FILES'] = $_FILES;
- return $data;
- }
- $boundary = self::getMultipartBoundary();
- if (!$boundary) {
- return $data;
- }
- $input = explode("--".$boundary, $input);
-
- array_pop($input);
- array_shift($input);
-
- foreach ($input as $part) {
- $part = ltrim($part, "\r\n");
- [$head, $body] = explode("\r\n\r\n", $part, 2);
-
- $tmpheaders = $headers = [];
- foreach (explode("\r\n", $head) as $headline) {
- if (preg_match('/^[^\s]/', $headline)) {
- $lineIsHeader = preg_match('/([^:]+):\s*(.*)$/', $headline, $matches);
- if ($lineIsHeader) {
- $tmpheaders[] = ['index' => mb_strtolower(trim($matches[1])), 'value' => trim($matches[2])];
- }
- } else {
- //noch zur letzten Zeile hinzuzählen
- end($tmpheaders);
- $lastkey = key($tmpheaders);
- $tmpheaders[$lastkey]['value'] .= " ".mb_substr($headline, 1);
- }
- }
- foreach ($tmpheaders as $header) {
- $headers[$header['index']] = $header['value'];
- }
-
- $contentType = "";
- if (isset($headers['content-type'])) {
- preg_match("/^([^;\s]*)/", $headers['content-type'], $matches);
- $contentType = mb_strtolower($matches[1]);
- }
- switch ($headers["transfer-encoding"]) {
- case "quoted-printable":
- $body = quoted_printable_decode($body);
- break;
- case "base64":
- $body = base64_decode(preg_replace("/(\r?\n|\r)/", "", trim($body)));
- break;
- case "7bit":
- case "8bit":
- default:
- //nothing to do
- }
- $matches = [];
- preg_match("/name=([^;\s]*)/i", $headers['content-disposition'], $matches);
- $name = str_replace(["'", '"'], '', $matches[1]);
- if (!$contentType) {
- $data[$name] = mb_substr($body, 0, mb_strlen($body) - 2);
- } else {
- switch ($contentType) {
- case 'application/json':
- $data = array_merge($data, self::parseJson($body));
- break;
- case 'application/x-www-form-urlencoded':
- $data = array_merge($data, self::parseFormEncoded($body));
- break;
- default:
- $matches = [];
- preg_match("/filename=([^;\s]*)/i", $headers['content-disposition'], $matches);
- if (!$matches[1]) {
- preg_match('/filename=([^;\s]*)/i', $headers['content-type'], $matches);
- }
- $filename = str_replace(["'", '"'], '', $matches[1]);
- $tmp_name = $GLOBALS['TMP_PATH']."/uploadfile_".md5(uniqid());
- $handle = fopen($tmp_name, 'wb');
- $filesize = fwrite($handle, $body, (mb_strlen($body) - 2));
- fclose($handle);
- $data['_FILES'][$name] = [
- 'name' => $filename,
- 'type' => $contentType,
- 'tmp_name' => $tmp_name,
- 'size' => $filesize
- ];
- }
- }
- }
- return $data;
- }
-
- private static function getMultipartBoundary()
- {
- if ($contentType = $_SERVER['CONTENT_TYPE']) {
- foreach (preg_split('/\s*[;,]\s*/', $contentType) as $part) {
- if (mb_strtolower(mb_substr($part, 0, 8)) === "boundary") {
- $part = explode("=", $part);
- return $part[1];
- }
- }
- }
- return null;
- }
-
-
- /**
- * Set the HTTP status of the current response.
- *
- * @param integer $status the HTTP status of the response
- */
- public function status($status)
- {
- $this->response->status = $status;
- }
-
- /**
- * Set multiple response headers of the current response by
- * merging them with already set ones.
- *
- * @code
- * $routemap->headers(array('X-example' => "yep"));
- * @endcode
- *
- * @param array $headers the headers to set
- *
- * @return array the headers of the current response
- */
- public function headers($headers = [])
- {
- if (sizeof($headers)) {
- $this->response->headers = array_merge($this->response->headers, $headers);
- }
- return $this->response->headers;
- }
-
- /**
- * Set the HTTP body of the current response.
- *
- * @param string $body the body to send back
- */
- public function body($body)
- {
- $this->response->body = $body;
- }
-
-
- /**
- * Set the Content-Type of the HTTP response given a mime type and
- * optionally further parameters as discusses in RFC 2616 14.17.
- *
- * If no charset is given, it defaults to Stud.IP's 'windows-1252'.
- *
- * Examples:
- *
- * @code
- * // results in "Content-Type: image/gif"
- * $this->contentType('image/gif);
- *
- * // results in "Content-Type: text/html;charset=ISO-8859-4"
- * $this->contentType('text/html;charset=ISO-8859-4');
- *
- * // results in "Content-Type: text/html;charset=ISO-8859-4"
- * $this->contentType('text/html', array('charset' => 'ISO-8859-4'));
- *
- * // results in "Content-type: multipart/byteranges; boundary=THIS_STRING_SEPARATES"
- * $this->contentType('multipart/byteranges', array('boundary' => 'THIS_STRING_SEPARATES'));
- *
- * @endcode
- *
- * @param string $mime_type a string describing a MIME type like 'application/json'
- * @param array $params optional parameters as described above
- */
- public function contentType($mime_type, $params = [])
- {
- if (!isset($params['charset'])) {
- $params['charset'] = 'utf-8';
- }
-
- if (mb_strpos($mime_type, 'charset') !== FALSE) {
- unset($params['charset']);
- }
-
- if (sizeof($params)) {
- $mime_type .= mb_strpos($mime_type, ';') !== FALSE ? ', ' : ';';
- $ps = [];
- foreach ($params as $k => $v) {
- $ps[] = $k . '=' . $v;
- }
- $mime_type .= join(', ', $ps);
- }
-
- $this->response['Content-Type'] = $mime_type;
- }
-
- /**
- * (Nice) sugar for calling RouteMap::halt and therefore
- * as \a DISRUPTIVE. Code after calling RouteMap::error will not
- * be evaluated.
- *
- * @see RouteMap::halt
- *
- * @param integer $status a number indicating the HTTP status
- * code; probably something 4xx or 5xx-ish
- * @param string $body optional; the body of the HTTP response
- *
- */
- public function error($status, $body = null)
- {
- $this->halt($status, [], $body);
- }
-
-
- /**
- * Sets the HTTP response's Etag header and halts, if the incoming
- * HTTP request was a matching conditional GET using an
- * 'If-None-Match' header. Thus it is a possibly \a DISRUPTIVE
- * method as it will stop evaluation in that case and send a '304
- * Not Modified'.
- *
- * Detail: If the request contains an If-Match or If-None-Match
- * header set to `*`, a RouteMap assumes a match on safe
- * (e.g. GET) and idempotent (e.g. PUT) requests. (In those cases
- * it thinks that the resource already exists and therefore
- * matches a wildcard.). This can be changed by passing an
- * appropriate value for the `$new_resource` parameter.
-
- * Details of this can be found in RFC 2616 14.24 and 14.26
- *
- * @param string $value an identifier uniquely identifying the
- * current state of a resource
- * @param bool $strong_etag optional; indicates whether the etag
- * is a weak or strong (which is the
- * default) cache validator. Have a look
- * at the RFC for details.
- * @param bool $new_resource optional; a way to tell the RouteMap
- * that this is a new or existing
- * resource. See above.
- */
-
- public function etag($value, $strong_etag = true, $new_resource = null)
- {
- // Before touching this code, please double check RFC 2616
- // 14.24 and 14.26.
-
- if (!isset($new_resource)) {
- $new_resource = Request::isPost();
- }
-
- $value = '"' . $value . '"';
- if (!$strong_etag) {
- $value = 'W/' . $value;
- }
- $this->response['ETag'] = $value;
-
- if ($this->response->isSuccess() || $this->response->status === 304) {
- if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $this->etagMatches($_SERVER['HTTP_IF_NONE_MATCH'], $new_resource)) {
- $this->halt($this->isRequestSafe() ? 304 : 412);
- }
- if (isset($_SERVER['HTTP_IF_MATCH'])
- && !$this->etagMatches($_SERVER['HTTP_IF_MATCH'], $new_resource)) {
- $this->halt(412);
- }
- }
- }
-
- // Helper method checking if a ETag value list includes the current ETag.
- private function etagMatches($list, $new_resource)
- {
- if ($list === '*') {
- return !$new_resource;
- }
-
- return in_array($this->response['ETag'],
- preg_split('/\s*,\s*/', $list));
- }
-
- // Helper method checking if the request is safe
- private function isRequestSafe()
- {
- $method = Request::method();
- return $method === 'GET' or $method === 'HEAD' or $method === 'OPTIONS' or $method === 'TRACE';
- }
-
- /**
- * This sets the `Expires` header and the `Cache-Control`
- * directive `max-age`.
- *
- * Amount is an integer number of seconds in the future indicating
- * when the response should be considered "stale". The
- * `$cache_control` parameter is passed to RouteMap#cacheControl
- * along with the automatically generated `max_age` directive.
- *
- * @param int $amount an integer specifying the number of seconds
- * this resource will go stale.
- * @param array $cache_control optional; more directives for
- * RouteMap::cacheControl which is always
- * automatically called using the computed max_age
- */
- public function expires($amount, $cache_control = [])
- {
- $time = time() + $amount;
- $max_age = $amount;
-
- $cache_control[] = "max-age=$max_age";
- $this->cacheControl($cache_control);
-
- $this->response['Expires'] = $this->httpDate($time);
- }
-
- /**
- * This sets the Cache-Control header of the HTTP response.
- *
- * Example:
- *
- * @code
- * $this->cacheControl(array('public', 'must-revalidate'));
- * @endcode
- *
- * @param array $values an array containing Cache-Control
- * directives.
- */
- public function cacheControl($values)
- {
- if (is_array($values) && sizeof($values)) {
- $this->response['Cache-Control'] = join(', ', $values);
- }
- }
-
- /**
- * This very important method stops further execution of your
- * code. You may specify a status code, headers and the body of
- * the resulting response. As the name implies, this method is \a
- * DISRUPTIVE and will not return.
- *
- * @code
- * // stops any further code of a route
- * $this->halt();
- *
- * // you may specify an HTTP status
- * $this->halt(409):
- *
- * // you may specify the HTTP response's body
- * $this->halt('my ethereal body')
- *
- * // or even both
- * $this->halt(100, 'Yes, pleazze!')
- *
- * // giving headers
- * $this->halt(417, array('Content-Type' => 'x-not-a-cat'), 'Cats only!')
- * @endcode
- *
- * This method is called by every single \a DISRUPTIVE method.
- *
- * @param integer $status optional; the response's status code
- * @param array $headers optional; (additional) header lines
- * which get merged with already set headers
- * @param string $body optional; the response's body
- */
- public function halt(/* [status], [headers], [body] */)
- {
- $args = func_get_args();
- $result = [];
-
- $constraints = [
- 'status' => 'is_int',
- 'headers' => 'is_array',
- 'body' => function ($i) { return isset($i); } // #existy
- ];
- foreach ($constraints as $state => $constraint) {
- if ($constraint(current($args))) {
- call_user_func([$this, $state], array_shift($args));
- }
- }
-
- throw new RouterHalt($this->response);
- }
-
- /**
- * This method sets the Last-Modified header of the HTTP response
- * and halts on matching conditional GET requests. Thus this
- * method is \a DISRUPTIVE in certain circumstances.
- *
- * You have to give an integer typed timestamp (in seconds since
- * epoch) to specify the data of the last modification to the
- * requested resource.
- *
- * If the current HTTP request contains an `If-Modified-Since`
- * header, its value is compared to the specified `$time`
- * parameter. Unless the header's value is sooner than the given
- * `$time`, further execution is precluded and the RouteMap
- * returns with a '304 Not Modified'.
- *
- * @param integer $time a timestamp described in seconds since epoch
- */
- public function lastModified($time)
- {
-
- $this->response['Last-Modified'] = $this->httpDate($time);
-
- if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
- return;
- }
-
- if ($this->response->status === 200
- && isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
- // compare based on seconds since epoch
- $since = $this->httpdate($_SERVER['HTTP_IF_MODIFIED_SINCE']);
- if ($since >= (int) $time) {
- $this->halt(304);
- }
- }
-
- if (($this->response->isSuccess() || $this->response->status === 412)
- && isset($_SERVER['HTTP_IF_UNMODIFIED_SINCE'])) {
-
- // compare based on seconds since epoch
- $since = $this->httpdate($_SERVER['HTTP_IF_UNMODIFIED_SINCE']);
-
- if ($since < (int) $time) {
- $this->halt(412);
- }
- }
- }
-
- private function httpDate($timestamp)
- {
- return gmdate('D, d M Y H:i:s \G\M\T', (int) $timestamp);
- }
-
- /**
- * Halts execution and returns a '404 Not Found' response.
- *
- * Sugar for calling RouteMap::error(404) and therefore
- * \a DISRUPTIVE. Code after calling RouteMap::notFound will
- * not be evaluated.
- *
- * @see RouteMap::error
- * @see RouteMap::halt
- *
- * @param string $body optional; the body of the HTTP response
- */
- public function notFound($body = null)
- {
- $this->halt(404, $body);
- }
-
- /**
- * Stops your code and redirects to the URL provided. This method
- * is \a DISRUPTIVE like RouteMap#halt
- *
- * In addition to the URL you may provide the status code,
- * (additional) headers and a request body as you would when
- * calling RouteMap#halt.
- *
- * @code
- * $this->redirect('/foo', 201, array('X-Some-Header' => 1234), 'and even a body');
- * @endcode
- *
- * @see RouteMap::halt
- *
- * @param string $url the URL to redirect to; it will be filtered
- * using RouteMap#url, so you may call it with
- * those nice and small strings used in the
- * annotations
- * @param mixed $args optional; any combinations of the three
- * parameters as in RouteMap::halt
- */
- public function redirect($url, $args = null)
- {
- $this->status($_SERVER["SERVER_PROTOCOL"] === 'HTTP/1.1' && !Request::isGet() ? 303 : 302);
- $this->response['Location'] = $this->url($url);
-
- $args = array_slice(func_get_args(), 1);
- call_user_func_array([$this, 'halt'], $args);
- }
-
-
- /**
- * Stops execution of your code and starts sending the specified
- * file. This method is \a DISRUPTIVE.
- *
- * Using the `$opts` parameter you may specify the file's mime
- * content type, sending an appropriate 'Content-Type' header, and
- * you may specify the 'Content-Disposition' of the file transfer.
- *
- * Example:
- *
- * @code
- * $this->sendFile('/tmp/c29tZSB0ZXh0', array(
- * 'type' => 'image/png',
- * 'disposition' => 'inline',
- * 'filename' => 'cutecats.png'));
- * @endcode
- *
- * @param string $_path the filesystem path to the file to send
- * @param array $opts optional; specify the content type,
- * disposition and filename
- */
- public function sendFile($_path, $opts = [])
- {
- $path = realpath($_path);
-
- if (!file_exists($path)) {
- $this->notFound('File to send does not exist');
- }
-
- if (isset($opts['type'])) {
- $this->contentType($opts['type']);
- } else if (!isset($this->response['Content-Type'])) {
- $this->contentType(get_mime_type($path));
- }
-
- if ($opts['disposition'] === 'attachment' || isset($opts['filename'])) {
- $this->response['Content-Disposition'] = 'attachment; ';
- $filename = $opts['filename'] ?: $path;
- $this->response['Content-Disposition'] .= encode_header_parameter('filename', basename($filename));
- }
-
- elseif ($opts['disposition'] === 'inline') {
- $this->response['Content-Disposition'] = 'inline';
- }
-
- // TODO add HTTP 'Range' support
-
- $size = filesize($path);
- $this->response['Content-Length'] = $size;
-
- // End all potential output buffers
- while (ob_get_level() > 0) {
- ob_end_clean();
- }
-
- // Send file
- $this->halt(200, $this->response->headers, function () use ($path) {
- readfile($path);
- });
- }
-
-
- /**
- * Generate a URL to a given handler using a URL fragment and URL
- * parameters.
- *
- * Example:
- * @code
- * // result in something like "/some/path/api.php/course/123/members?status=student"
- * $this->url('course/123/members', array('status' => 'student'));
- * @endcode
- *
- * @param string $addr a URL fragment to a handler
- * @param array $url_params optional; URL parameters to add to
- * the generated URL
- *
- * @return string the resulting URL
- */
- public function url($addr, $url_params = null)
- {
- $addr = ltrim($addr, '/');
- return \URLHelper::getURL("api.php/$addr", $url_params, true);
- }
-
- /**
- * A `vsprintf` like variant to the RouteMap::url method.
- *
- * Example:
- * @code
- * // results in "[...]/api.php/foo/some_id?status=student"
- * $this->urlf("foo/%s", array("some_id"), array('status' => 'student'));
- * @endcode
- *
- * @param string $addr_f a URL fragment to a handler
- * containing sprintf-ish format sequences
- * @param array $format_params values to fill into the format markers
- * @param array $url_params optional; URL parameters to add to
- * the generated URL
- *
- * @return string the resulting URL
- */
-
- public function urlf($addr_f, $format_params, $url_params = null)
- {
- if (!is_array($format_params)) {
- $format_params = [$format_params];
- }
- return $this->url(vsprintf($addr_f, $format_params), $url_params);
- }
-
- /**
- * Returns a list of all the routes this routemap provides.
- *
- * @param string $http_method Return only the routes for this specific
- * http method (optional)
- *
- * @return array of all routes grouped by method
- */
- public function getRoutes($http_method = null)
- {
- $ref = new \ReflectionClass($this);
-
- if ($ref->getDocComment()) {
- $docblock = new Docblock($ref);
- $class_conditions = $this->extractConditions($docblock);
- } else {
- $class_conditions = [];
- }
-
-
- // Create result array by creating an associative array from all
- // supported methods as keys
- $routes = array_fill_keys(Router::getSupportedMethods(), []);
-
- // Restrict routes to given http method (if given)
- if ($http_method !== null) {
- $routes = [$http_method => []];
- }
-
- // Iterate through all methods of the routemap
- foreach ($ref->getMethods( \ReflectionMethod::IS_PUBLIC) as $ref_method) {
- // No docblock? Not an api route!
- if (!$ref_method->getDocComment()) {
- continue;
- }
-
- // Parse docblock
- $docblock = new Docblock($ref_method);
-
- // No docblock tags? Not an api route!
- if ($docblock->getTags()->isEmpty()) {
- continue;
- }
-
- // Any specific condition to consider?
- $conditions = $this->extractConditions($docblock, $class_conditions);
-
- // Iterate through all possible methods in order to identify
- // any according docblock tags
- $allow_nobody = $docblock->hasTag('allow_nobody');
- foreach (array_keys($routes) as $http_method) {
- if (!$docblock->hasTag($http_method)) {
- //The tag for the current HTTP method cannot be found
- //in the route's DocBlock tags.
- continue;
- }
-
- // Route all defined method and uri template combinations to
- // the according methods of the object.
- foreach ($docblock->getTags($http_method) as $tag) {
- $uri_template = trim($tag->getDescription());
- $routes[$http_method][$uri_template] = [
- 'handler' => [$this, $ref_method->name],
- 'conditions' => $conditions,
- 'description' => trim($docblock->getShortDescription()) ?: false,
- 'allow_nobody' => $allow_nobody
- ];
- }
- }
- }
-
- // Return all routes grouped or just the routes for the wanted method
- return func_num_args() === 1
- ? reset($routes)
- : $routes;
- }
-
- /**
- * Extracts defined conditions from a given docblock.
- *
- * @param Docblock $docblock DocBlock to examine
- * @param array $conditions Optional array of already defined
- * conditions to extend
- * @return array of all extracted conditions with the variable name
- * as key and pattern to match as value
- */
- protected function extractConditions($docblock, $conditions = [])
- {
- foreach ($docblock->getTags('condition') as $condition) {
- [$var, $pattern] = explode(' ', $condition->getDescription(), 2);
- $conditions[$var] = $pattern;
- }
-
- return $conditions;
- }
-
- /**
- * Returns the response object
- * @return Response
- */
- public function getResponse(): Response
- {
- return $this->response;
- }
-}
diff --git a/lib/classes/restapi/Router.php b/lib/classes/restapi/Router.php
deleted file mode 100644
index df7a6b9..0000000
--- a/lib/classes/restapi/Router.php
+++ /dev/null
@@ -1,665 +0,0 @@
-<?php
-/** @namespace RESTAPI
- *
- * Im Namensraum RESTAPI sind alle Klassen und Funktionen versammelt,
- * die für die RESTful Web Services von Stud.IP benötigt werden.
- */
-namespace RESTAPI;
-use RESTAPI\Renderer\DefaultRenderer;
-
-/**
- * Die Aufgabe des Routers ist das Anlegen und Auswerten eines
- * Mappings von sogenannten Routen (Tupel aus HTTP-Methode und Pfad)
- * auf Code.
- *
- * Dazu werden zunächst Routen mittels der Funktion
- * Router::registerRoutes registriert.
- *
- * Wenn dann ein HTTP-Request eingeht, kann mithilfe von
- * Router::dispatch und HTTP-Methode bzw. Pfad der zugehörige Code
- * gefunden und ausgeführt werden. Der Router bildet aus dem
- * Rückgabewert des Codes ein Response-Objekt, das er als Ergebnis
- * zurück meldet.
- *
- * @code
- * $router = Router::getInstance();
- *
- * // register a sample Route
- * $router->registerRoutes(new ExampleRoute);
- *
- * // dispatch to therein defined Routes
- * $response = $router->dispatch('/example', 'GET');
- *
- * // render response
- * $response->output();
- *
- * @endcode
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @see Inspired by http://blog.sosedoff.com/2009/07/04/simpe-php-url-routing-controller/
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class Router
-{
- // instances are cached here
- protected static $instances = [];
-
- /**
- * Holds the user object of the user that is accessing the API.
- * This is null for nobody users.
- */
- protected $user = null;
-
- /**
- * Returns (and if neccessary, initializes) a (cached) router object for an
- * optional consumer id.
- *
- * @param mixed $consumer_id ID of the consumer (defaults to 'global')
- *
- * @return Router returns the Router instance associated to the
- * consumer ID (or to the 'global' ID)
- */
- public static function getInstance($consumer_id = null)
- {
- $consumer_id = $consumer_id ?: 'global';
-
- if (!isset(self::$instances[$consumer_id])) {
- self::$instances[$consumer_id] = new self($consumer_id);
- }
- return self::$instances[$consumer_id];
- }
-
- // All supported method need to be defined here
- protected static $supported_methods = [
- 'get', 'post', 'put', 'delete', 'patch', 'options', 'head'
- ];
-
- /**
- * Returns a list of all supported methods.
- *
- * @return array of methods as strings
- */
- public static function getSupportedMethods()
- {
- return self::$supported_methods;
- }
-
- // registered routes by method and uri template
- protected $routes = [];
-
- // registered content renderers
- protected $renderers = [];
-
- // identified or forced content renderer
- protected $content_renderer = false;
-
- // default renderer
- protected $default_renderer = false;
-
- // registered conditions
- protected $conditions = [];
-
- // registered descriptions
- protected $descriptions = [];
-
- // registered consumers
- protected $consumers = [];
-
- // associated permissions
- protected $permissions = false;
-
- /**
- * Constructs the router.
- *
- * @param mixed $consumer_id the ID of the consumer this router
- * should associate to
- */
- protected function __construct($consumer_id)
- {
- $this->permissions = ConsumerPermissions::get($consumer_id);
- $this->registerRenderer(new Renderer\DefaultRenderer);
- }
-
- /**
- * Registers a handler for a specific combination of request method
- * and uri template.
- *
- * @param String $request_method expected HTTP request method
- * @param String $uri_template expected URI template, for
- * example: \code "/user/:user_id/events" \endcode
- * @param Array $handler request handler array:
- * \code array($object, "methodName") \endcode
- * @param Array $conditions (optional) an associative
- * array using the name of
- * parameters as keys and regexps
- * as value
- * @param string $source (optional) this denotes the
- * origin of a route. Usually
- * either 'core' or 'plugin', but
- * defaults to 'unknown'.
- * @param bool $allow_nobody Whether the route can be accessed
- * as nobody user (true) or not (false).
- * Defaults to false.
- *
- * @return Router returns itself to allow chaining
- * @throws \Exception if passed HTTP request method is not supported
- */
- public function register($request_method, $uri_template, $handler, $conditions = [], $source = 'unknown', $allow_nobody = false)
- {
- // Normalize method and test whether it's supported
- $request_method = mb_strtolower($request_method);
- if (!in_array($request_method, self::$supported_methods)) {
- throw new \Exception('Method "' . $request_method . '" is not supported.');
- }
-
- // Initialize routes storage for this method if neccessary
- if (!isset($this->routes[$request_method])) {
- $this->routes[$request_method] = [];
- }
-
- // Normalize uri template (always starts with a slash)
- if ($uri_template[0] !== '/') {
- $uri_template = '/' . $uri_template;
- }
-
- // Sanitize conditions
- foreach ($conditions as $var => $pattern) {
- if ($pattern[0] !== $pattern[mb_strlen($pattern) - 1] || ctype_alnum($pattern[0])) {
- $conditions[$var] = '/' . $pattern . '/';
- }
- }
-
- $this->routes[$request_method][$uri_template] = compact(
- 'handler', 'conditions', 'source', 'allow_nobody'
- );
-
- // Return instance to allow chaining
- return $this;
- }
-
- /**
- * Registers the routes defined in a RouteMap instance using
- * docblock annotations (like @get) of its methods.
- *
- * \code
- * $router = \RESTAPI\Router::getInstance();
- *
- * $router->registerRoutes(new ExampleRouteMap());
- * \endcode
- *
- * @param RouteMap $map the RouteMap instance to register
- *
- * @return Router returns itself to allow chaining
- */
- public function registerRoutes(RouteMap $map)
- {
- // Investigate object, define whether it's located in the core system
- // or a plugin, respect any defined class conditions and iterate
- // through it's methods to find any defined route
- $ref = new \ReflectionClass($map);
- $filename = $ref->getFilename();
- $source = mb_strpos($filename, 'plugins_packages') !== false
- ? 'plugin'
- : 'core';
-
- foreach (self::$supported_methods as $http_method) {
- foreach ($map->getRoutes($http_method) as $uri_template => $data) {
- // Register (and describe) route
- $this->register(
- $http_method, $uri_template,
- $data['handler'], $data['conditions'],
- $source,
- $data['allow_nobody']
- );
- if ($data['description']) {
- $this->describe(
- $uri_template,
- $data['description'],
- $http_method
- );
- }
- }
- }
-
- return $this;
- }
-
- /**
- * Describe one or more routes.
- *
- * \code
- * $router = \RESTAPI\Router::getInstance();
- *
- * // describe a single route
- * $router->describe('/foo', 'returns everything about foo', 'get');
- *
- * // describe several routes that use the same path
- * $router->describe('/foo', array(
- * 'get' => 'returns everything about foo',
- * 'put' => 'updates all of foo',
- * 'delete' => 'empty up foo'
- * ));
- *
- * // describe several routes
- * $router->describe(array(
- * '/foo' => array(
- * 'get' => 'returns everything about foo',
- * 'put' => 'updates all of foo',
- * 'delete' => 'empty up foo'),
- * '/bar' => array(...),
- * ));
- * \endcode
- *
- * @param String|Array $uri_template URI template to describe or pass an
- * array to describe multiple routes.
- * @param String|null $description description of the route
- * @param String $method method to describe.
- *
- * @return Router returns instance of itself to allow chaining
- */
- public function describe($uri_template, $description = null, $method = 'get')
- {
- // describe multiple routes at once
- if (func_num_args() === 1 && is_array($uri_template)) {
- foreach ($uri_template as $template => $description) {
- $this->describe($template, $description);
- }
- }
-
- // describe routes that use the same URI template
- elseif (func_num_args() === 2 && is_array($description)) {
- foreach ($description as $method => $desc) {
- $this->describe($uri_template, $desc, $method);
- }
- }
-
- // describe a single route
- else {
- if (!isset($this->descriptions[$uri_template])) {
- $this->descriptions[$uri_template] = [];
- }
- if (isset($this->routes[$method][$uri_template])) {
- $this->descriptions[$uri_template][$method] = $description;
- } else {
- // Try to find route with different method
- foreach ($this->routes as $m => $templates) {
- if (isset($templates[$uri_template])) {
- $this->descriptions[$uri_template][$m] = $description;
- break;
- }
- }
- }
- }
- return $this;
- }
-
- /**
- * Get list of registered routes - optionally with their descriptions.
- *
- * @param bool $describe (optional) include descriptions,
- * defaults to `false`
- * @param bool $check_access (optional) only show methods this router's
- * consumer is authorized to,
- * defaults to `true`
- *
- * @return array list of registered routes
- */
- public function getRoutes($describe = false, $check_access = true)
- {
- $this->setupRoutes();
-
- $result = [];
- foreach ($this->routes as $method => $routes) {
- foreach ($routes as $uri => $route) {
- if ($check_access && !$this->permissions->check($uri, $method)) {
- continue;
- }
- if (!isset($result[$uri])) {
- $result[$uri] = [];
- }
- if ($describe) {
- $result[$uri][$method] = [
- 'description' => $this->descriptions[$uri][$method] ?? null,
- 'source' => $route['source'] ?? 'unknown',
- ];
- } else {
- $result[$uri][] = $method;
- }
- }
- }
- ksort($result);
- if ($describe) {
- $result = array_map(function ($item) {
- ksort($item);
- return $item;
- }, $result);
- }
- return $result;
- }
-
- /**
- * Dispatches an URI across the defined routes and produces a
- * Response object which may then be send back (using #output).
- *
- * @param mixed $uri URI to dispatch (defaults to `$_SERVER['PATH_INFO']`)
- * @param String $method Request method (defaults to the method
- * of the actual HTTP request or "GET")
- *
- * @return Response a Response object containing status, headers
- * and body
- * @throws RouterException may throw such an exception if there
- * is no matching route (404) or if there
- * is one, but the consumer is not
- * authorized to it (403)
- */
- public function dispatch($uri = null, $method = null)
- {
- $this->setupRoutes();
-
- $uri = $this->normalizeDispatchURI($uri);
- $method = $this->normalizeRequestMethod($method);
-
- $content_renderer = $this->negotiateContent($uri);
-
- $match_result = $this->matchRoute($uri, $method, $content_renderer);
- $route = $match_result[0];
- $parameters = $match_result[1];
- $allow_nobody = $match_result[2] ?? false;
- if (!$route) {
- //No route found for the combination of URI and method.
- //We return the allowed methods for the route in the HTTP header:
- $methods = $this->getMethodsForUri($uri);
- if (count($methods) > 0) {
- header('Allow: ' . implode(', ', $methods));
- throw new RouterException(405);
- } else {
- //Route not found.
- throw new RouterException(404);
- }
- }
- //At this point, a route is found.
- //We need to check if it can be used as nobody user or not.
- if (!$route['allow_nobody'] && !$this->user) {
- //Nobody users aren't allowed for this route.
- throw new RouterException(401, 'Unauthorized (no consumer)');
- }
-
- try {
- $response = $this->execute($route, $parameters);
- } catch (RouterHalt $halt) {
- $response = $halt->response;
- }
-
- $response->finish($content_renderer);
-
- return $response;
- }
-
- /**
- * Searches and registers available routes.
- */
- private function setupRoutes()
- {
- // A bit ugly, I confess
- static $was_setup = false;
- if ($was_setup) {
- return;
- }
- $was_setup = true;
-
- // Register default routes
- $routes = [
- 'Activity',
- 'Blubber',
- 'Clipboard',
- 'Contacts',
- 'Course',
- 'Discovery',
- 'Events',
- 'Feedback',
- 'FileSystem',
- 'Forum',
- 'Messages',
- 'News',
- 'ResourceBooking',
- 'Resources',
- 'ResourceCategories',
- 'ResourcePermissions',
- 'ResourceProperties',
- 'ResourceRequest',
- 'RoomClipboard',
- 'Schedule',
- 'Semester',
- 'Studip',
- 'User',
- 'UserConfig',
- 'Wiki'
- ];
-
- foreach ($routes as $route) {
- require_once "app/routes/$route.php";
- $class = "\\RESTAPI\\Routes\\$route";
- $this->registerRoutes(new $class);
- }
-
- // Register plugin routes
- $router = $this;
- $routes = array_flatten(\PluginEngine::sendMessage('RESTAPIPlugin', 'getRouteMaps'));
- array_walk(
- $routes,
- function ($route) use ($router) {
- $router->registerRoutes($route);
- }
- );
- }
-
- /**
- * Takes a route and the parameters out of the requested path and
- * executes the handler of the route.
- *
- * @param array $route the matched route out of
- * Router::matchRoute; an array with keys
- * 'handler', 'conditions' and 'source'
- * @param array $parameters the matched parameters out of
- * Router::matchRoute; something like:
- * `array('user_id' => '23a21d...e78f')`
- * @return Response the resulting Response object which is then
- * polished in Router::dispatch
- */
- protected function execute($route, $parameters)
- {
- $handler = $route['handler'];
-
- if (!is_object($handler[0])) {
- throw new \RuntimeException("Handler is not a method.");
- }
-
- $handler[0]->init($this, $route);
-
- if (method_exists($handler[0], 'before')) {
- $handler[0]->before($this, $handler, $parameters);
- }
-
- $result = call_user_func_array($handler, $parameters);
-
- if (is_object($result) && method_exists($result, 'toArray')) {
- $result = $result->toArray();
- }
-
- // $result is stronger than $response->body
- if (isset($result)) {
- $handler[0]->body($result);
- }
-
- if (method_exists($handler[0], 'after')) {
- $handler[0]->after($this, $parameters);
- }
-
- return $handler[0]->getResponse();
- }
-
- /**
- * Registers a content renderer.
- *
- * @param DefaultRenderer $renderer instance of a content renderer
- * @param boolean $is_default (optional) set this
- * renderer as default?;
- * defaults to `false`
- *
- * @return Router returns itself to allow chaining
- */
- public function registerRenderer($renderer, $is_default = false)
- {
- $this->renderers[$renderer->extension()] = $renderer;
- if ($is_default) {
- $this->default_renderer = $renderer;
- }
-
- return $this;
- }
-
- private function normalizeDispatchURI($uri)
- {
- return $uri ?? \Request::pathInfo();
- }
-
- private function normalizeRequestMethod($method)
- {
- return mb_strtolower($method ?: \Request::method() ?: 'get');
- }
-
- /**
- * Negotiate content using the registered content renderers. The
- * first ContentRenderer that returns `true` when calling
- * ContentRenderer::shouldRespondTo gets the job.
- *
- * @param String $uri the URI to which the content renderers may respond
- *
- * @return ContentRenderer either a ContentRenderer that responds
- * to the URI or the default
- * ContentRenderer of this router.
- */
- protected function negotiateContent($uri)
- {
- $content_renderer = null;
- foreach ($this->renderers as $renderer) {
- if ($renderer->shouldRespondTo($uri)) {
- $content_renderer = $renderer;
- break;
- }
- }
- if (!$content_renderer) {
- $content_renderer = $this->default_renderer ?: reset($this->renderers);
- }
- return $content_renderer;
- }
-
- /**
- * Tries to match a route given a URI and a HTTP request method.
- *
- * @param String $uri the URI to match
- * @param String $method the HTTP request method to match
- * @param DefaultRenderer $content_renderer the used
- * ContentRenderer which
- * is needed to remove
- * a file extension
- *
- * @return array an array containing the matched route and the
- * found parameters
- */
- protected function matchRoute($uri, $method, $content_renderer)
- {
- $matched = null;
- $parameters = [];
- if (isset($this->routes[$method])) {
- if ($content_renderer->extension() && mb_strpos($uri, $content_renderer->extension()) !== false) {
- $uri = mb_substr($uri, 0, -mb_strlen($content_renderer->extension()));
- }
-
- foreach ($this->routes[$method] as $uri_template => $route) {
- if (!isset($route['uri_template'])) {
- $route['uri_template'] = new UriTemplate($uri_template, $route['conditions']);
- }
-
- $prmtrs = null; // Will be filled by a successful match()
- if ($route['uri_template']->match($uri, $prmtrs)) {
- if (!$this->permissions->check($uri_template, $method)) {
- throw new RouterException(403, "Route not activated");
- }
- $matched = $route;
- $parameters = $prmtrs;
- break;
- }
- }
- }
- return [$matched, $parameters];
- }
-
- /**
- * Returns all methods the given uri responds to.
- *
- * @param String $uri the URI to match
- *
- * @return array of all of responding methods
- */
- protected function getMethodsForUri($uri)
- {
- $methods = [];
-
- foreach ($this->routes as $method => $templates) {
- foreach ($templates as $uri_template => $route) {
- if (!isset($route['uri_template'])) {
- $route['uri_template'] = new UriTemplate($uri_template, $route['conditions']);
- }
-
- if ($route['uri_template']->match($uri)
- && $this->permissions->check($uri_template, $method))
- {
- $methods[] = $method;
- }
- }
- }
-
- return array_map('strtoupper', $methods);
- }
-
-
- /**
- * Sets up the authentication for the router.
- */
- public function setupAuth()
- {
- // Detect consumer
- $consumer = Consumer\Base::detectConsumer();
- if (!$consumer) {
- return null;
- }
-
- $this->user = $consumer->getUser();
-
- // Set authentication if present
- if ($this->user) {
- // Skip fake authentication if user is already logged in
- if ($GLOBALS['user']->id !== $this->user->id) {
-
- $GLOBALS['auth'] = new \Seminar_Auth();
- $GLOBALS['auth']->auth = [
- 'uid' => $this->user->user_id,
- 'uname' => $this->user->username,
- 'perm' => $this->user->perms,
- ];
-
- $GLOBALS['user'] = new \Seminar_User($this->user);
-
- $GLOBALS['perm'] = new \Seminar_Perm();
- $GLOBALS['MAIL_VALIDATE_BOX'] = false;
- }
- setTempLanguage($GLOBALS['user']->id);
- }
-
- return $this->user;
- }
-}
diff --git a/lib/classes/restapi/RouterException.php b/lib/classes/restapi/RouterException.php
deleted file mode 100644
index 1ce2afc..0000000
--- a/lib/classes/restapi/RouterException.php
+++ /dev/null
@@ -1,31 +0,0 @@
-<?php
-namespace RESTAPI;
-use \Exception;
-
-/**
- * Router exception.
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class RouterException extends Exception
-{
- protected static $error_messages = [
- 400 => 'Bad Request',
- 401 => 'Unauthorized',
- 403 => 'Forbidden',
- 404 => 'Not Found',
- 405 => 'Method Not Allowed',
- 500 => 'Internal Server Error',
- 501 => 'Not implemented',
- ];
-
- public function __construct($code = 500, $message = '', $previous = null)
- {
- $message = $message ?: self::$error_messages[$code] ?: '';
- parent::__construct($message, $code, $previous);
- }
-}
diff --git a/lib/classes/restapi/RouterHalt.php b/lib/classes/restapi/RouterHalt.php
deleted file mode 100644
index 55a2ca1..0000000
--- a/lib/classes/restapi/RouterHalt.php
+++ /dev/null
@@ -1,19 +0,0 @@
-<?php
-namespace RESTAPI;
-
-/**
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class RouterHalt extends \Exception
-{
- public $response;
-
- public function __construct($response)
- {
- parent::__construct();
- $this->response = $response;
- }
-}
diff --git a/lib/classes/restapi/UriTemplate.php b/lib/classes/restapi/UriTemplate.php
deleted file mode 100644
index 67161de..0000000
--- a/lib/classes/restapi/UriTemplate.php
+++ /dev/null
@@ -1,115 +0,0 @@
-<?php
-namespace RESTAPI;
-
-/**
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class UriTemplate
-{
- public $uri_template;
- public $conditions;
-
- public function __construct($uri_template, $conditions = [])
- {
- $this->uri_template = $uri_template;
- $this->conditions = $conditions;
- }
-
- /**
- * Tests whether an uri matches a template.
- *
- * The template may contain placeholders by prefixing an appropriate,
- * unique placeholder name with a colon (:).
- *
- * <code>$template = '/hello/:name';</code>
- *
- * If the uri matches the template, all evaluated placeholders will
- * be stored in the parameters array.
- *
- * @param String $uri The uri to test
- * @param array $parameters Stores evaluated parameters on match (optional)
- *
- * @return bool Returns true if the uri matches the template
- */
- public function match($uri, &$parameters = null)
- {
- // Initialize parameters array
- $parameters = [];
-
- // Split and normalize uri and template
- $given = array_filter(explode('/', $uri), 'mb_strlen');
- $rules = array_filter(explode('/', $this->uri_template));
-
- // Leave if uri and template do not contain the same number of
- // elements
- if (count($given) !== count($rules)) {
- return false;
- }
-
- // Combine uri and template element-wise (simplifies iteration)
- $combined = array_combine($rules, $given);
-
- // Iterate over uri and template and compare element by element
- foreach ($combined as $rule => $actual) {
- if ($rule[0] === ':') {
- // Rule is a placeholder
- $parameter_name = mb_substr($rule, 1);
-
- if (isset($this->conditions[$parameter_name])
- && !preg_match($this->conditions[$parameter_name], $actual)) {
- return false;
- }
-
- $parameters[$parameter_name] = $actual;
-
- } elseif ($actual !== $rule) {
- // Elements do not match
- $parameters = [];
- return false;
- }
- }
-
- return true;
- }
-
-
- public function inject($params)
- {
- // Initialize parameters array
- $parameters = [];
-
- // Split and normalize template
- $rules = array_filter(explode('/', $this->uri_template));
-
- foreach ($rules as &$rule) {
-
- // Rule is a placeholder
- if ($rule[0] === ':') {
- $parameter_name = mb_substr($rule, 1);
-
- if (!isset($params[$parameter_name])) {
- $reason = sprintf('UriTemplate parameter :%s missing.',
- htmlReady($parameter_name));
- throw new \RuntimeException($reason);
- }
-
- $actual = $params[$parameter_name];
-
- if (isset($this->conditions[$parameter_name])
- && !preg_match($this->conditions[$parameter_name], $actual)) {
- $reason = sprintf('UriTemplate parameter :%s did not satisfy its condition.',
- htmlReady($parameter_name));
- throw new \RuntimeException($reason);
- }
-
- $rule = htmlReady($actual);
- }
- }
-
- return join('/', $rules);
- }
-}
diff --git a/lib/classes/restapi/UserPermissions.php b/lib/classes/restapi/UserPermissions.php
deleted file mode 100644
index dcf1601..0000000
--- a/lib/classes/restapi/UserPermissions.php
+++ /dev/null
@@ -1,144 +0,0 @@
-<?php
-namespace RESTAPI;
-use DBManager, PDO;
-
-/**
- * REST API routing permissions
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @license GPL 2 or later
- * @since Stud.IP 2.6
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class UserPermissions
-{
- /**
- * Create a permission object (for a certain user).
- * Permissions object will be cached for each user.
- *
- * @param mixed $user_id Id of user (optional, defaults to global)
- * @return UserPermissions Returns permissions object
- */
- public static function get($user_id = null)
- {
- $user_id = $user_id ?: $GLOBALS['user']->id;
-
- static $cache = [];
- if (!isset($cache[$user_id])) {
- $cache[$user_id] = new self($user_id);
- }
-
- return $cache[$user_id];
- }
-
- private $user_id;
- private $permissions = [];
-
- /**
- * Creates the actual permission object (for a certain user).
- *
- * @param mixed $user_id Id of user (optional, defaults to global)
- */
- private function __construct($user_id = null)
- {
- $this->user_id = $user_id;
-
- // Init with global permissions
- $this->loadPermissions();
- }
-
- /**
- * Defines whether access is allowed for the current user to the
- * passed route via the passed method.
- *
- * @param String $user_id Id of the user
- * @param mixed $granted Granted state (PHP'ish boolean)
- * @return UserPermissions Returns instance of self to allow chaining
- */
- public function set($user_id, $granted = true)
- {
- $this->permissions[$user_id] = (bool)$granted;
-
- return $this;
- }
-
- /**
- * Loads permissions for passed user.
- *
- * @return UserPermissions Returns instance of self to allow chaining
- */
- protected function loadPermissions()
- {
- $query = "SELECT consumer_id, granted
- FROM api_user_permissions
- WHERE user_id = :user_id";
- $statement = DBManager::get()->prepare($query);
- $statement->bindValue(':user_id', $this->user_id);
- $statement->execute();
- $permissions = $statement->fetchAll(PDO::FETCH_ASSOC);
-
- // Init with global permissions
- foreach ($permissions as $permission) {
- extract($permission);
-
- $this->set($permission['consumer_id'], $permission['granted']);
- }
-
- return $this;
- }
-
- /**
- * Checks if access to consumer is allowed for the current user.
- *
- * @param String $consumer_id Id of the consumer
- * @return bool Indicates whether access is allowed
- */
- public function check($consumer_id)
- {
- return isset($this->permissions[$consumer_id])
- && $this->permissions[$consumer_id];
- }
-
- /**
- * Stores the set permissions.
- *
- * @return bool Returns true if permissions were stored successfully
- */
- public function store()
- {
- $result = true;
-
- $query = "INSERT INTO api_user_permissions (user_id, consumer_id, granted, mkdate, chdate)
- VALUES (:user_id, :consumer_id, :granted, UNIX_TIMESTAMP(), UNIX_TIMESTAMP())
- ON DUPLICATE KEY UPDATE granted = VALUES(granted),
- chdate = UNIX_TIMESTAMP()";
- $statement = DBManager::get()->prepare($query);
- $statement->bindValue(':user_id', $this->user_id);
-
- foreach ($this->permissions as $consumer_id => $granted) {
- $statement->bindValue(':consumer_id', $consumer_id);
- $statement->bindValue(':granted', (int) !empty($granted));
-
- $result = $result && $statement->execute();
- }
-
- return $result;
- }
-
- /**
- * Get a list of all consumer the user has granted acces to.
- *
- * @return array List of consumer objects
- */
- public function getConsumers()
- {
- $result = [];
- foreach ($this->permissions as $consumer_id => $granted) {
- if (!$granted) {
- continue;
- }
- $result[$consumer_id] = Consumer\Base::find($consumer_id);
- }
- return $result;
- }
-}
diff --git a/lib/classes/restapi/consumer/Base.php b/lib/classes/restapi/consumer/Base.php
deleted file mode 100644
index 50f3150..0000000
--- a/lib/classes/restapi/consumer/Base.php
+++ /dev/null
@@ -1,226 +0,0 @@
-<?php
-namespace RESTAPI\Consumer;
-
-use AuthUserMd5;
-use DBManager;
-use DBManagerException;
-use PDO;
-
-/**
- * Base consumer class for the rest api
- *
- * Consumers provide means for authenticating a user and the access
- * permissions for routes are bound to specific consumers.
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-abstract class Base extends \SimpleORMap
-{
- /**
- * Each consumer type has to implement a detect feature which
- * should extract crucial information from the request and return
- * an instance of itself if the consumer detects a valid signature
- * it can respond to.
- *
- * @param mixed $request_type Type of request (optional; defaults to any)
- * @return mixed Detected consumer object or false
- */
- abstract public static function detect($request_type = null);
-
- /* Concrete */
-
- /**
- * Configures the model.
- *
- * @param array $config Configuration array
- */
- protected static function configure($config = [])
- {
- $config['db_table'] = 'api_consumers';
-
- parent::configure($config);
- }
-
- /**
- * Stores all known consumer types
- */
- protected static $known_types = [];
-
- /**
- * Add a consumer type to the list of consumer types
- *
- * @param String $type Name of the type
- * @param String $class Associated consumer class
- */
- public static function addType($type, $class)
- {
- self::$known_types[$type] = $class;
- }
-
- /**
- * Removes a consumer type from the list of consumer types
- *
- * @param String $type Name of the type
- */
- public static function removeType($type)
- {
- unset(self::$known_types[$type]);
- }
-
- /**
- * Overloaded find method. Will return a concrete specialized consumer
- * object of the associated type.
- *
- * @param String $id Id of the consumer
- * @return \RESTAPI\Consumer\Base Associated consumer object (derived
- * from consumer base type)
- * @throws \Exception if either consumer id or consumer type is invalid
- */
- public static function find($id)
- {
- $query = "SELECT consumer_type
- FROM api_consumers
- WHERE consumer_id = :id";
- $statement = DBManager::get()->prepare($query);
- $statement->bindValue(':id', $id);
- $statement->execute();
- $type = $statement->fetchColumn();
-
- if (!isset(self::$known_types[$type])) {
- throw new \Exception('Consumer #' . $id . ' is of unknown type "' . $type . '"');
- }
-
- return new self::$known_types[$type]($id);
- }
-
- /**
- * Returns a list of all known consumers.
- *
- * @return array List of all known consumers (as specialized consumer
- * objects)
- */
- public static function findAll()
- {
- $query = "SELECT consumer_id FROM api_consumers";
- $statement = DBManager::get()->query($query);
- $ids = $statement->fetchAll(PDO::FETCH_COLUMN);
-
- return array_map([self::class, 'find'], $ids);
- }
-
- /**
- * Creates a new consumer of the given type.
- *
- * @param String $type Name of the type
- * @return \RESTAPI\Consumer\Base Consumer object of the given (derived
- * from consumer base type)
- * @throws \Exception if type is invalid
- */
- public static function create($type)
- {
- if (!isset(self::$known_types[$type])) {
- throw new \Exception('Consumer is of unknown type "' . $type . '"');
- }
-
- return new self::$known_types[$type];
- }
-
- /**
- * This method is used to detect a consumer (of a specific type) by
- * executing the detect method on all known consumer types.
- *
- * @param mixed $type Name of the type (optional; defaults to all types)
- * @param mixed $request_type Type of request (optional; defaults to any)
- * @return mixed Either the detected consumer or false if no consumer
- * was detected
- * @throws \Exception if type is invalid
- */
- public static function detectConsumer($type = null, $request_type = null)
- {
- $needles = $type === null
- ? array_keys(self::$known_types)
- : [$type];
- foreach ($needles as $needle) {
- if (!isset(self::$known_types)) {
- throw new \Exception('Trying to detect consumer of unkown type "' . $needle . '"');
- }
- $consumer_class = self::$known_types[$needle];
- if ($consumer = $consumer_class::detect($request_type)) {
- return $consumer;
- }
- }
- return false;
- }
-
- /**
- * Contains user information
- */
- protected $user = null;
-
- /**
- * Extended SimpleORMap constructor. A certain user can be injected upon
- * creation.
- *
- * @param mixed $id Id of the consumer or null to create a new one
- * @param mixed $user Either a user object or id to inject to the consumer
- * or null if no user should be injected
- */
- public function __construct($id = null, $user = null)
- {
- parent::__construct($id);
-
- if ($user !== null) {
- $this->setUser($user);
- }
- }
-
- /**
- * Retrieve the api permissions associated with this consumer.
- *
- * @return \RESTAPI\ConsumerPermissions Permission object for this consumer
- */
- public function getPermissions()
- {
- return \RESTAPI\ConsumerPermissions::get($this->id);
- }
-
- /**
- * Inject a user to this consumer. Injecting in this context refers to
- * "having a user authenticated by this consumer".
- *
- * @param mixed $user Either a user object or a user id
- * @return \RESTAPI\Consumer\Base Returns instance of self to allow
- * chaining
- */
- public function setUser($user)
- {
- if (!is_object($user)) {
- $user = \User::findFull($user);
- }
- $this->user = $user;
- return $this;
- }
-
- /**
- * Returns whether the consumer has an injected user or not.
- *
- * @return bool True if a valid user is found, false otherwise
- */
- public function hasUser()
- {
- return $this->user !== null && $this->user->id && $this->user->id !== 'nobody';
- }
-
- /**
- * Return the injected user.
- *
- * @param mixed User object or false if no user was injected
- */
- public function getUser()
- {
- return $this->user;
- }
-}
diff --git a/lib/classes/restapi/consumer/HTTP.php b/lib/classes/restapi/consumer/HTTP.php
deleted file mode 100644
index 97b0657..0000000
--- a/lib/classes/restapi/consumer/HTTP.php
+++ /dev/null
@@ -1,50 +0,0 @@
-<?php
-namespace RESTAPI\Consumer;
-use StudipAuthAbstract, RESTAPI\RouterException;
-
-/**
- * Basic HTTP Authentication consumer for the rest api
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class HTTP extends Base
-{
- /**
- * Detects if a user is authenticated via basic http authentication.
- * The only supported authentication for now is via the url:
- *
- * http://username:password@host/path?query
- *
- * @param mixed $request_type Type of request (optional; defaults to any)
- * @return mixed Instance of self if authentication was detected, false
- * otherwise
- * @throws RouterException if authentication fails
- * @todo Integrate and test HTTP_AUTHORIZATION header authentication
- */
- public static function detect($request_type = null)
- {
- if (
- isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])
- || isset($_SERVER['HTTP_AUTHORIZATION'])
- ) {
- $user_id = false;
-
- if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
- $username = $_SERVER['PHP_AUTH_USER'];
- $password = $_SERVER['PHP_AUTH_PW'];
- } elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) {
- list($username, $password) = explode(':', base64_decode(mb_substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
- }
-
- $check = StudipAuthAbstract::CheckAuthentication($username, $password);
- if ($check['uid'] && $check['uid'] !== 'nobody') {
- return new self(null, $check['uid']);
- }
-
- }
- return false;
- }
-}
diff --git a/lib/classes/restapi/consumer/OAuth.php b/lib/classes/restapi/consumer/OAuth.php
deleted file mode 100644
index caf51c2..0000000
--- a/lib/classes/restapi/consumer/OAuth.php
+++ /dev/null
@@ -1,231 +0,0 @@
-<?php
-namespace RESTAPI\Consumer;
-use StudipAutoloader, DBManager, OAuthRequestVerifier, OAuthStore, OAuthServer, Exception;
-use \RESTAPI\UserPermissions;
-
-StudipAutoloader::addAutoloadPath($GLOBALS['STUDIP_BASE_PATH'] . DIRECTORY_SEPARATOR . 'vendor/oauth-php/library/');
-
-/**
- * OAuth consumer for the rest api
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class OAuth extends Base
-{
- /**
- * Configures the model.
- *
- * @param array $config Configuration array
- */
- protected static function configure($config = [])
- {
- $config['default_values']['consumer_type'] = 'oauth';
-
- $config['registered_callbacks']['before_store'][] = 'before_store';
-
- parent::configure($config);
- }
-
- /**
- * Detects whether the request is authenticated via OAuth.
- *
- * @param mixed $request_type Type of request (optional; defaults to any)
- * @return mixed Instance of self if authentication was detected, false
- * otherwise
- */
- public static function detect($request_type = null)
- {
- if (OAuthRequestVerifier::requestIsSigned() && $request_type !== 'request') {
- $user_id = false;
-
- $parameters = (in_array($_SERVER['REQUEST_METHOD'], ['GET', 'POST']))
- ? null
- : $GLOBALS['_' . $_SERVER['REQUEST_METHOD']];
-
- $req = new OAuthRequestVerifier(null, null, $parameters);
-
- // Check oauth timestamp and deny access if timestamp is outdated
- if ($req->getParam('oauth_timestamp') < strtotime('-6 hours')) {
- return false;
- }
- $result = $req->verifyExtended('access');
-
- // @todo
- # self::$consumer_key = $result['consumer_key'];
-
- $query = "SELECT user_id FROM api_oauth_user_mapping WHERE oauth_id = :oauth_id";
- $statement = DBManager::get()->prepare($query);
- $statement->bindValue(':oauth_id', $result['user_id']);
- $statement->execute();
- $user_id = $statement->fetchColumn();
-
- if (!$user_id) {
- return false;
- }
-
- $consumer = reset(self::findByAuth_Key($result['consumer_key']));
- $consumer->setUser($user_id);
- return $consumer;
- } else {
- try {
- // Check if there is a valid request token in the current request
- // Returns an array with the consumer key, consumer secret, token, token secret and token type.
- $rs = self::getServer()->authorizeVerify();
-
- $query = "SELECT consumer_id
- FROM api_consumers
- WHERE auth_key = :key";
- $statement = DBManager::get()->prepare($query);
- $statement->bindValue(':key', $rs['consumer_key']);
- $statement->execute();
- $id = $statement->fetchColumn();
-
- if ($id) {
- return new self($id);
- }
- } catch (Exception $e) {
- }
- }
- return false;
- }
-
- /**
- * Returns a singleton instance of the oauth server.
- *
- * @return OAuthServer The server object
- */
- public static function getServer()
- {
- static $server = null;
- if ($server === null) {
- $server = new OAuthServer(null, null, null, 'SESSION', [], [
- 'allowed_uri_schemes' => []
- ]);
- }
- return $server;
- }
-
- /**
- * "Before store" trigger. Creates a clone of the consumer in the
- * tables for the vendor oauth library.
- */
- protected function before_store()
- {
- static $mapping = [
- 'auth_key' => 'consumer_key',
- 'auth_secret' => 'consumer_secret',
- 'active' => 'enabled',
- 'contact' => 'requester_name',
- 'email' => 'requester_email',
- 'callback' => 'callback_uri',
- 'url' => 'application_uri',
- 'title' => 'application_title',
- 'description' => 'application_descr',
- 'notes' => 'application_notes',
- 'type' => 'application_type',
- 'commercial' => 'application_commercial',
- ];
-
- $consumer = [];
- foreach ($mapping as $from => $to) {
- $consumer[$to] = $this->$from;
- }
-
- $query = "SELECT osr_id
- FROM oauth_server_registry
- WHERE osr_consumer_key = :key AND osr_consumer_secret = :secret";
- $statement = DBManager::get()->prepare($query);
- $statement->bindValue(':key', $this->auth_key);
- $statement->bindValue(':secret', $this->auth_secret);
- $statement->execute();
- $consumer['id'] = $statement->fetchColumn();
-
- $consumer_key = OAuthStore::instance('PDO')->updateConsumer($consumer, null, true);
-
- if ($this->isNew()) {
- $consumer = OAuthStore::instance('PDO')->getConsumer($consumer_key, null, true);
- $this->auth_key = $consumer['consumer_key'];
- $this->auth_secret = $consumer['consumer_secret'];
- }
- }
-
- /**
- * Grant oauth access for a user.
- *
- * @param mixed $user_id Specific user id or null to default to the
- * injected user
- * @throws Exception If no valid user is present
- */
- public function grantAccess($user_id = null)
- {
- if ($user_id === null && $this->hasUser()) {
- $user_id = $this->user->id;
- }
- if (!$user_id) {
- throw new Exception('Can not grant access to unknown user');
- }
-
- UserPermissions::get($GLOBALS['user']->id)->set($this->id, true)->store();
- return self::getServer()->authorizeFinish(true, self::getOAuthId($user_id));
- }
-
- /**
- * Revoke oauth access from a user.
- *
- * @param mixed $user_id Specific user id or null to default to the
- * injected user
- * @throws Exception If no valid user is present
- */
- public function revokeAccess($user_id = null)
- {
- if ($user_id === null && $this->hasUser()) {
- $user_id = $this->user->id;
- }
- if (!$user_id) {
- throw new Exception('Can not revoke access from unknown user');
- }
-
- $query = "DELETE oauth_server_token
- FROM oauth_server_token
- JOIN oauth_server_registry
- WHERE ost_usa_id_ref = :id AND osr_consumer_key = :key AND osr_consumer_secret = :secret";
- $statement = DBManager::get()->prepare($query);
- $statement->bindValue(':id', self::getOAuthId($user_id));
- $statement->bindValue(':key', $this->auth_key);
- $statement->bindValue(':secret', $this->auth_secret);
- $statement->execute();
-
- UserPermissions::get($GLOBALS['user']->id)->set($this->id, false)->store();
- return self::getServer()->authorizeFinish(false, self::getOAuthId($user_id));
- }
-
- /**
- * Maps a user to an oauth id. This is neccessary due to the fact that
- * the oauth lib works with different ids than Stud.IP.
- *
- * @param String $user_id Id of the user to get an oauth id for
- * @return String The mapped oauth id
- */
- public static function getOAuthId($user_id)
- {
- $query = "SELECT oauth_id FROM api_oauth_user_mapping WHERE user_id = :id";
- $statement = DBManager::get()->prepare($query);
- $statement->bindValue(':id', $user_id);
- $statement->execute();
- $oauth_id = $statement->fetchColumn();
-
- if (!$oauth_id) {
- $query = "INSERT INTO api_oauth_user_mapping (user_id, mkdate)
- VALUES (:id, UNIX_TIMESTAMP())";
- $statement = DBManager::get()->prepare($query);
- $statement->bindValue(':id', $user_id);
- $statement->execute();
- $oauth_id = DBManager::get()->lastInsertId();
- }
-
- return $oauth_id;
- }
-}
diff --git a/lib/classes/restapi/consumer/Studip.php b/lib/classes/restapi/consumer/Studip.php
deleted file mode 100644
index 738dd75..0000000
--- a/lib/classes/restapi/consumer/Studip.php
+++ /dev/null
@@ -1,36 +0,0 @@
-<?php
-namespace RESTAPI\Consumer;
-
-/**
- * Stud.IP Session Consumer for the rest api
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class Studip extends Base
-{
- /**
- * Detects a user via the Stud.IP session. If a session is present and
- * valid, the auth and user object have already been set up by stud.ip
- * functions, so we just need to check if these are present.
- *
- * @param mixed $request_type Type of request (optional; defaults to any)
- * @return mixed Instance of self if authentication was detected, false
- * otherwise
- */
- public static function detect($request_type = null)
- {
- if (
- !isset($GLOBALS['auth'])
- || !$GLOBALS['auth']->is_authenticated()
- || $GLOBALS['user']->id === 'nobody'
- || !\CSRFProtection::verifyRequest()
- ) {
- return false;
- }
-
- return new self(null, $GLOBALS['user']->id);
- }
-}
diff --git a/lib/classes/restapi/renderer/DebugRenderer.php b/lib/classes/restapi/renderer/DebugRenderer.php
deleted file mode 100644
index afd56f6..0000000
--- a/lib/classes/restapi/renderer/DebugRenderer.php
+++ /dev/null
@@ -1,57 +0,0 @@
-<?php
-namespace RESTAPI\Renderer;
-
-/**
- * Debug content renderer.
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class DebugRenderer extends DefaultRenderer
-{
- /**
- * Returns an associated content type.
- */
- public function contentType()
- {
- return 'text/plain';
- }
-
- /**
- * Returns an associated extension.
- */
- public function extension()
- {
- return '.debug';
- }
-
- /**
- * Response transformation function.
- *
- * @param \RESTAPI\Response $response the response to transform
- */
- public function render($response)
- {
- if (!isset($response['Content-Type'])) {
- $response['Content-Type'] = $this->contentType() . ';charset=utf-8';
- }
-
- $debug = function ($label, $data) {
- echo str_pad('', 78, '=') . PHP_EOL;
- echo str_pad('- ' . $label, 77, ' ') . '-' . PHP_EOL;
- echo str_pad('', 78, '=') . PHP_EOL;
- var_export($data);
- echo PHP_EOL;
- };
-
- ob_start();
- $debug('Response Status', $response->status);
- $debug('Response Header', $response->headers);
- $debug('Response Body', $response->body);
- $debug('Request', $GLOBALS['_' . $_SERVER['REQUEST_METHOD']]);
- $response->body = ob_get_clean();
- }
-}
diff --git a/lib/classes/restapi/renderer/DefaultRenderer.php b/lib/classes/restapi/renderer/DefaultRenderer.php
deleted file mode 100644
index 836ba36..0000000
--- a/lib/classes/restapi/renderer/DefaultRenderer.php
+++ /dev/null
@@ -1,74 +0,0 @@
-<?php
-namespace RESTAPI\Renderer;
-
-/**
- * Default base content renderer class (outputs text/plain).
- *
- * Content renderers are output filters that can reshape data before it
- * is sent to the client.
- * Each content renderer is associated with a certain content type and a
- * certain file extension. This is neccessary for content negotiation.
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class DefaultRenderer
-{
- /**
- * Returns an associated content type.
- *
- * @return String Content/mime type for this renderer
- */
- public function contentType()
- {
- return 'text/plain';
- }
-
- /**
- * Returns an associated extension.
- *
- * @return String Associated extension for this renderer.
- */
- public function extension()
- {
- return '';
- }
-
- /**
- * Response transformation function.
- *
- * @param \RESTAPI\Response $response the response to transform
- */
- public function render($response)
- {
- if (!isset($response['Content-Type'])) {
- $response['Content-Type'] = $this->contentType() . ';charset=utf-8';
- }
- }
-
- /**
- * Detects whether the renderer should respond to either a certain
- * filename (tests by extension) or to a certain media range.
- *
- * @param String $filename Filename to test against
- * @param mixed $media_range Media range to test against (optional,
- * defaults to request's accept header if set)
- * @return bool Returns whether the renderer should respond
- */
- public function shouldRespondTo($filename, $media_range = null)
- {
- // If no media range is passed, evalute http header "Accept"
- if ($media_range === null && isset($_SERVER['ACCEPT'])) {
- $media_ranges = explode(';', $_SERVER['ACCEPT']);
- $media_range = reset($media_ranges);
- }
-
- // Test if either the filename has the appropriate extension or
- // if the client accepts the content type
- return ($this->extension() && fnmatch('*' . $this->extension(), $filename))
- || ($media_range && fnmatch($media_range, $this->contentType()));
- }
-}
diff --git a/lib/classes/restapi/renderer/JSONRenderer.php b/lib/classes/restapi/renderer/JSONRenderer.php
deleted file mode 100644
index 9c6e449..0000000
--- a/lib/classes/restapi/renderer/JSONRenderer.php
+++ /dev/null
@@ -1,35 +0,0 @@
-<?php
-namespace RESTAPI\Renderer;
-
-/**
- * Content renderer for json content.
- *
- * @author Jan-Hendrik Willms <tleilax+studip@gmail.com>
- * @author <mlunzena@uos.de>
- * @license GPL 2 or later
- * @since Stud.IP 3.0
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-class JSONRenderer extends DefaultRenderer
-{
- public function contentType()
- {
- return 'application/json';
- }
-
- public function extension()
- {
- return '.json';
- }
-
- public function render($response)
- {
- if (!isset($response['Content-Type'])) {
- $response['Content-Type'] = $this->contentType() . ';charset=utf-8';
- }
-
- if (isset($response->body)) {
- $response->body = json_encode($response->body);
- }
- }
-}
diff --git a/lib/models/resources/ResourceBooking.php b/lib/models/resources/ResourceBooking.php
index fadf92f..8950713 100644
--- a/lib/models/resources/ResourceBooking.php
+++ b/lib/models/resources/ResourceBooking.php
@@ -1755,18 +1755,16 @@ class ResourceBooking extends SimpleORMap implements PrivacyObject, Studip\Calen
//(lib/resources.js, method dropEventInRoomGroupBookingPlan)
$interval_api_urls = [
'resize' => \URLHelper::getURL(
- 'api.php/resources/booking/'
- . $this->id . '/move',
+ 'dispatch.php/resources/ajax/move_booking/' . $this->id,
[
- 'quiet' => '1',
+ 'quiet' => true,
'interval_id' => $interval->id
]
),
'move' => \URLHelper::getURL(
- 'api.php/resources/booking/'
- . $this->id . '/move',
+ 'dispatch.php/resources/ajax/move_booking/' . $this->id,
[
- 'quiet' => '1',
+ 'quiet' => true,
'interval_id' => $interval->id
]
)
@@ -1784,11 +1782,11 @@ class ResourceBooking extends SimpleORMap implements PrivacyObject, Studip\Calen
$text_colour,
$colour,
$booking_is_editable,
- 'ResourceBookingInterval',
+ ResourceBookingInterval::class,
$interval->id,
- 'ResourceBooking',
+ ResourceBooking::class,
$this->id,
- 'Resource',
+ Resource::class,
$this->resource_id,
$booking_view_urls,
$interval_api_urls,
diff --git a/lib/models/resources/ResourceRequest.php b/lib/models/resources/ResourceRequest.php
index 9cad900..b2f5524 100644
--- a/lib/models/resources/ResourceRequest.php
+++ b/lib/models/resources/ResourceRequest.php
@@ -2244,24 +2244,19 @@ class ResourceRequest extends SimpleORMap implements PrivacyObject, Studip\Calen
protected function convertToEventData(array $time_intervals, User $user)
{
- $booking_plan_request_bg =
- ColourValue::find('Resources.BookingPlan.Request.Bg');
- $booking_plan_request_fg =
- ColourValue::find('Resources.BookingPlan.Request.Fg');
- $booking_plan_preparation_bg =
- ColourValue::find('Resources.BookingPlan.PreparationTime.Bg');
- $booking_plan_preparation_fg =
- ColourValue::find('Resources.BookingPlan.PreparationTime.Fg');
+ $booking_plan_request_bg = ColourValue::find('Resources.BookingPlan.Request.Bg');
+ $booking_plan_request_fg = ColourValue::find('Resources.BookingPlan.Request.Fg');
+ $booking_plan_preparation_bg = ColourValue::find('Resources.BookingPlan.PreparationTime.Bg');
+ $booking_plan_preparation_fg = ColourValue::find('Resources.BookingPlan.PreparationTime.Fg');
$user_is_resource_autor = false;
- if ($this->resource_id && ($this->resource instanceof Resource)) {
+ if ($this->resource_id && $this->resource instanceof Resource) {
$user_is_resource_autor = $this->resource->userHasPermission(
$user,
'autor'
);
}
- $request_is_editable =
- $user_is_resource_autor || ($user->id == $this->user_id);
+ $request_is_editable = $user_is_resource_autor || ($user->id == $this->user_id);
$request_api_urls = [];
$request_view_urls = [];
@@ -2269,18 +2264,12 @@ class ResourceRequest extends SimpleORMap implements PrivacyObject, Studip\Calen
if ($request_is_editable) {
$request_api_urls = [
'resize' => URLHelper::getURL(
- 'api.php/resources/request/'
- . $this->id . '/move',
- [
- 'quiet' => '1'
- ]
+ 'dispatch.php/resources/ajax/move_request/'. $this->id,
+ ['quiet' => true]
),
- 'move' => URLHelper::getURL(
- 'api.php/resources/request/'
- . $this->id . '/move',
- [
- 'quiet' => '1'
- ]
+ 'move' => URLHelper::getURL(
+ 'dispatch.php/resources/ajax/move_request/'. $this->id,
+ ['quiet' => true]
)
];
@@ -2290,13 +2279,14 @@ class ResourceRequest extends SimpleORMap implements PrivacyObject, Studip\Calen
. $this->id
)
];
- if ($this->resource_id && ($this->resource instanceof Resource)) {
- if ($this->resource->userHasBookingRights($user)) {
- $request_view_urls['edit'] = URLHelper::getURL(
- 'dispatch.php/resources/room_request/resolve/'
- . $this->id
- );
- }
+ if (
+ $this->resource_id
+ && $this->resource instanceof Resource
+ && $this->resource->userHasBookingRights($user)
+ ) {
+ $request_view_urls['edit'] = URLHelper::getURL(
+ 'dispatch.php/resources/room_request/resolve/'. $this->id
+ );
}
}
@@ -2306,7 +2296,7 @@ class ResourceRequest extends SimpleORMap implements PrivacyObject, Studip\Calen
$real_begin = $interval['begin'];
if ($this->preparation_time) {
$real_begin += (int)$this->preparation_time;
- $begin = new DateTime();
+ $begin = new DateTime();
$begin->setTimestamp($interval['begin']);
$end = new DateTime();
$end->setTimestamp($real_begin);
@@ -2320,9 +2310,9 @@ class ResourceRequest extends SimpleORMap implements PrivacyObject, Studip\Calen
$request_is_editable,
'',
'',
- 'ResourceRequest',
+ ResourceRequest::class,
$this->id,
- 'Resource',
+ Resource::class,
$this->resource_id,
$request_view_urls,
$request_api_urls
@@ -2342,11 +2332,11 @@ class ResourceRequest extends SimpleORMap implements PrivacyObject, Studip\Calen
$booking_plan_request_fg->__toString(),
$booking_plan_request_bg->__toString(),
$request_is_editable,
- 'ResourceRequest',
+ ResourceRequest::class,
$this->id,
- 'Resource',
+ Resource::class,
$this->resource_id,
- 'Resource',
+ Resource::class,
$this->resource_id,
$request_view_urls,
$request_api_urls
diff --git a/lib/modules/ActivityFeed.php b/lib/modules/ActivityFeed.php
index 62762b6..667c4f9 100644
--- a/lib/modules/ActivityFeed.php
+++ b/lib/modules/ActivityFeed.php
@@ -50,28 +50,4 @@ class ActivityFeed extends CorePlugin implements PortalPlugin
return $template;
}
-
- public static function onEnable($pluginId)
- {
- $errors = [];
- if (!Config::get()->API_ENABLED) {
- $errors[] = sprintf(
- _('Die REST-API ist nicht aktiviert (%s "API_ENABLED")'),
- formatReady(sprintf('[%s]%s',
- _('Konfiguration'),
- URLHelper::getLink('dispatch.php/admin/configuration/configuration')
- ))
- );
- } elseif (!RESTAPI\ConsumerPermissions::get('global')->check('/user/:user_id/activitystream', 'get')) {
- $errors[] = sprintf(
- _('Die REST-API-Route ist nicht aktiviert (%s "/user/:user_id/activitystream"")'),
- formatReady(sprintf('[%s]%s',
- _('Konfiguration'),
- URLHelper::getLink('dispatch.php/admin/api/permissions')
- ))
- );
- }
-
- return count($errors) === 0;
- }
}
diff --git a/lib/navigation/AdminNavigation.php b/lib/navigation/AdminNavigation.php
index a725082..3e63876 100644
--- a/lib/navigation/AdminNavigation.php
+++ b/lib/navigation/AdminNavigation.php
@@ -206,10 +206,6 @@ class AdminNavigation extends Navigation
$navigation->addSubNavigation('admissionrules', new Navigation(_('Anmelderegeln'), 'dispatch.php/admission/ruleadministration'));
- if (Config::get()->API_ENABLED) {
- $navigation->addSubNavigation('api', new Navigation(_('API'), 'dispatch.php/admin/api'));
- }
-
$navigation->addSubNavigation('oauth2', new Navigation(_('OAuth2'), 'dispatch.php/admin/oauth2/index'));
$navigation->addSubNavigation('globalsearch', new Navigation(_('Globale Suche'), 'dispatch.php/globalsearch/settings'));
diff --git a/lib/navigation/ProfileNavigation.php b/lib/navigation/ProfileNavigation.php
index 4827fe4..307cd98 100644
--- a/lib/navigation/ProfileNavigation.php
+++ b/lib/navigation/ProfileNavigation.php
@@ -114,10 +114,6 @@ class ProfileNavigation extends Navigation
$navigation->addSubNavigation('deputies', new Navigation(_('Standardvertretung'), 'dispatch.php/settings/deputies'));
}
- if (Config::Get()->API_ENABLED) {
- $navigation->addSubNavigation('api', new Navigation(_('API-Berechtigungen'), 'dispatch.php/api/authorizations'));
- }
-
if (TwoFactorAuth::isEnabledForUser()) {
$navigation->addSubNavigation('tfa', new Navigation(_('Zwei-Faktor-Authentifizierung'), 'dispatch.php/tfa'));
}
diff --git a/lib/plugins/core/RESTAPIPlugin.php b/lib/plugins/core/RESTAPIPlugin.php
deleted file mode 100644
index f69344c..0000000
--- a/lib/plugins/core/RESTAPIPlugin.php
+++ /dev/null
@@ -1,26 +0,0 @@
-<?php
-/*
- * REST-API Plugins add maps to the REST-API router.
- *
- * Copyright (c) 2014 - Marcus Lunzenauer <mlunzena@uos.de>
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License as
- * published by the Free Software Foundation; either version 2 of
- * the License, or (at your option) any later version.
- */
-
-/**
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-interface RESTAPIPlugin
-{
- /**
- * Returns one or more instances of RESTAPI\RouteMap to register
- * to the Router.
- *
- * @return RouteMap|Array either a single instance of class
- * RouteMap or an array of them
- */
- public function getRouteMaps();
-}
diff --git a/public/api.php b/public/api.php
deleted file mode 100644
index 9f7863c..0000000
--- a/public/api.php
+++ /dev/null
@@ -1,103 +0,0 @@
-<?php
-
-/** @file
- *
- * Diese Datei stellt den Ausgangspunkt für alle Zugriffe auf die
- * RESTful Web Services von Stud.IP dar.
- * Grob betrachtet läuft das Routings so ab:
- *
- * Ein HTTP-Request geht ein. Falls dort eine inkompatible Version der
- * REST-API verlangt wird, bricht das Skript ab. Die Authentifizierung
- * wird durchgeführt. Bei Erfolg wird die PATH_INFO und die HTTP
- * Methode im Router verwendet, um die passende Funktion zu
- * finden. Der Router liefert in jedem Fall ein Response-Objekt
- * zurück, dass dann anschließende ausgegeben wird, d.h. die Header
- * werden gesendet und dann das Ergebnis ausgegeben oder gestreamt.
- *
- * @deprecated Since Stud.IP 5.0. Will be removed in Stud.IP 6.0.
- */
-
-
-namespace {
- require_once '../lib/bootstrap.php';
-
- page_open([
- 'sess' => 'Seminar_Session',
- 'auth' => 'Seminar_Default_Auth',
- 'perm' => 'Seminar_Perm',
- 'user' => 'Seminar_User',
- ]);
-}
-
-namespace RESTAPI {
-
- use Config;
-
- // A potential api exception will lead to an according response with the
- // exception code and name as the http status.
- try {
- if (!Config::get()->API_ENABLED) {
- throw new RouterException(503, 'REST API is not available');
- }
-
- require 'lib/bootstrap-api.php';
-
- // Initialize RESTAPI plugins
- \PluginEngine::getPlugins(RESTAPIPlugin::class);
-
- $uri = \Request::pathInfo();
-
- // Check version
- if (defined('RESTAPI\\VERSION') && preg_match('~^/v(\d+)~i', $uri, $match)) {
- $version = $match[1];
- if ($version != VERSION) {
- throw new RouterException(400, 'Version not supported');
- }
-
- $uri = mb_substr($uri, mb_strlen($match[0]));
- header('X-API-Version: ' . VERSION);
- }
-
- // Get router instance
- $router = Router::getInstance();
-
- $api_user = $router->setupAuth();
-
- // Actual dispatch
- $response = $router->dispatch($uri);
-
- // Tear down
- if ($api_user) {
- restoreLanguage();
- }
-
- // Send output
- $response->output();
-
- } catch (RouterException $e) {
- $status = sprintf('%s %u %s',
- $_SERVER['SERVER_PROTOCOL'] ?: 'HTTP/1.1',
- $e->getCode(),
- $e->getMessage());
- $status = trim($status);
- if (!headers_sent()) {
- if ($e->getCode() === 401) {
- header('WWW-Authenticate: Basic realm="' . Config::get()->STUDIP_INSTALLATION_ID . '"');
- }
- header($status, true, $e->getCode());
- echo $status;
- } else {
- echo $status;
- }
- } catch (\Exception $e) {
- error_log("Caught {$e}");
-
- $message = explode("\n", $e->getMessage())[0];
- header('Content-Type: application/json; charset=UTF-8');
- header("{$_SERVER['SERVER_PROTOCOL']} 500 {$message}");
- echo $GLOBALS['template_factory']->render('json_exception', [
- 'exception' => $e,
- 'status' => 500,
- ]);
- }
-}
diff --git a/resources/assets/javascripts/bootstrap/resources.js b/resources/assets/javascripts/bootstrap/resources.js
index 8c89b7f..7eb6a68 100644
--- a/resources/assets/javascripts/bootstrap/resources.js
+++ b/resources/assets/javascripts/bootstrap/resources.js
@@ -416,7 +416,7 @@ STUDIP.ready(function () {
$("#BookingEndDateInput").prop('defaultValue', $(this).val());
$("#BookingEndDateInput").val($(this).val()).trigger('change');
}
- updateRepeatEndSemesterByTimestamp(Math.floor(d / 1000));
+ updateRepeatEndSemesterByTimestamp(d);
} else if ($(this).attr('id') == 'BookingEndDateInput') {
$("#end_date-weekdays span").addClass('invisible');
$("#end_date-weekdays #" + day_numer).removeClass('invisible');
@@ -545,38 +545,41 @@ STUDIP.ready(function () {
}
);
- function updateRepeatEndSemesterByTimestamp(timestamp, api_url = 'api.php/semesters') {
- var semester = null;
- jQuery.ajax(
- STUDIP.URLHelper.getURL(api_url),
- {
- method: 'get',
- dataType: 'json',
- success: function (data) {
- if (data) {
- Object.values(data.collection).forEach(item => {
- if (timestamp >= item.begin && timestamp < item.end) {
- semester = item;
- }
- });
- if (semester) {
- $("#semester_course_name").text(semester.title);
- $(".semester-time-option").prop('disabled', false);
- } else {
- if (data.pagination && data.pagination.links.next != api_url) {
- semester = updateRepeatEndSemesterByTimestamp(timestamp, data.pagination.links.next);
- } else {
- $("#semester_course_name").text('außerhalb definierter Zeiten');
- $(".semester-time-option").prop('checked', false);
- $(".semester-time-option").prop('disabled', true);
- $(".manual-time-option").prop('checked', true);
- $(".manual-time-option").trigger('change');
- }
- }
- }
- }
+ function updateRepeatEndSemesterByTimestamp(timestamp) {
+ (new Promise((resolve, reject) => {
+ const cache = STUDIP.Cache.getInstance('jsonapi');
+ if (cache.has('semesters')) {
+ resolve(cache.get('semesters'));
+ } else {
+ STUDIP.jsonapi.GET('semesters', { data: { page: { limit: 100000 }}})
+ .done(({data}) => {
+ cache.set('semesters', data);
+ resolve(data)
+ })
+ .fail(() => {
+ reject(new Error('Could not load semesters'));
+ });
+ }
+ })).then(semesters => {
+ const semester = semesters.find(({attributes}) => {
+ return new Date(attributes.start) <= timestamp
+ && timestamp <= new Date(attributes.end);
+ });
+
+ if (semester) {
+ $('#semester_course_name').text(semester.attributes.title);
+ $('.semester-time-option').prop('disabled', false);
+ } else {
+ $('#semester_course_name').text('außerhalb definierter Zeiten');
+ $('.semester-time-option').prop({
+ checked: false,
+ disabled: true
+ });
+ $('.manual-time-option')
+ .prop('checked', true)
+ .trigger('change');
}
- );
+ });
}
function updateViewURL(defaultView) {
diff --git a/resources/assets/javascripts/init.js b/resources/assets/javascripts/init.js
index 36a72a5..1d7d5ac 100644
--- a/resources/assets/javascripts/init.js
+++ b/resources/assets/javascripts/init.js
@@ -64,7 +64,6 @@ import register from './lib/register.js';
import Report from './lib/report.js';
import Resources from './lib/resources.js';
import Responsive from './lib/responsive.js';
-import RESTAPI, { api } from './lib/restapi.js';
import Schedule from './lib/schedule.js';
import Screenreader from './lib/screenreader.js';
import Scroll from './lib/scroll.js';
@@ -92,7 +91,6 @@ window.STUDIP = _.assign(window.STUDIP || {}, {
admin_sem_class,
AdminCourses,
Admission,
- api,
Arbeitsgruppen,
Archive,
Avatar,
@@ -151,7 +149,6 @@ window.STUDIP = _.assign(window.STUDIP || {}, {
register,
Report,
Responsive,
- RESTAPI,
Schedule,
Scroll,
Screenreader,
diff --git a/resources/assets/javascripts/lib/activityfeed.js b/resources/assets/javascripts/lib/activityfeed.js
index 74c27f9..12f0bac 100644
--- a/resources/assets/javascripts/lib/activityfeed.js
+++ b/resources/assets/javascripts/lib/activityfeed.js
@@ -6,13 +6,13 @@ const ActivityFeed = {
maxheight: null,
filter: null,
- init: function() {
+ init() {
STUDIP.ActivityFeed.maxheight = parseInt($('#stream-container').css('max-height').replace(/[^-\d.]/g, ''));
STUDIP.ActivityFeed.loadFeed(STUDIP.ActivityFeed.filter);
- $('#stream-container').scroll(function () {
- var scrollBottom = $('#stream-container').scrollTop() + $('#stream-container').height() + 250;
+ $('#stream-container').scroll(() => {
+ const scrollBottom = $('#stream-container').scrollTop() + $('#stream-container').height() + 250;
if ($('#stream-container').prop('scrollHeight') < scrollBottom) {
STUDIP.ActivityFeed.loadFeed(STUDIP.ActivityFeed.filter);
@@ -23,7 +23,7 @@ const ActivityFeed = {
$(document).on('click', '.provider_circle', function () {
$(this).parent().parent().children('.activity-content').toggle();
}).on('click', '#toggle-all-activities,#toggle-user-activities', function () {
- var toggled = $(this).is(':not(.toggled)');
+ const toggled = $(this).is(':not(.toggled)');
$(this).toggleClass('toggled', toggled);
STUDIP.ActivityFeed.setToggleStatus();
@@ -32,11 +32,11 @@ const ActivityFeed = {
});
},
- getTemplate: _.memoize(function(name) {
- return _.template($("script." + name).html());
+ getTemplate: _.memoize(name => {
+ return _.template($(`script.${name}`).html());
}),
- loadFeed: function(filtertype) {
+ loadFeed(filtertype) {
if (STUDIP.ActivityFeed.user_id === null) {
console.log('Could not retrieve activities, no valid user id found!');
return false;
@@ -48,17 +48,18 @@ const ActivityFeed = {
STUDIP.ActivityFeed.polling = true;
- STUDIP.api.GET(['user', STUDIP.ActivityFeed.user_id, 'activitystream'], {
- data: {
- filtertype: JSON.stringify(filtertype),
- scrollfrom: STUDIP.ActivityFeed.scrolledfrom
- }
- }).done(function (activities) {
- var stream = STUDIP.ActivityFeed.getTemplate('activity_stream');
- var activity = STUDIP.ActivityFeed.getTemplate('activity');
- var activity_urls = STUDIP.ActivityFeed.getTemplate('activity-urls');
- var num_entries = Object.keys(activities).length;
- var lastelem = $(activities).last();
+ const url = STUDIP.URLHelper.getURL('dispatch.php/activityfeed/load', {
+ filtertype: JSON.stringify(filtertype),
+ scrollfrom: STUDIP.ActivityFeed.scrolledfrom,
+ });
+ fetch(url).then(
+ response => response.json(),
+ ).then(activities => {
+ const stream = STUDIP.ActivityFeed.getTemplate('activity_stream');
+ const activity = STUDIP.ActivityFeed.getTemplate('activity');
+ const activity_urls = STUDIP.ActivityFeed.getTemplate('activity-urls');
+ const num_entries = Object.keys(activities).length;
+ const lastelem = $(activities).last();
if (lastelem[0]) {
STUDIP.ActivityFeed.scrolledfrom = lastelem[0].mkdate;
@@ -79,15 +80,15 @@ const ActivityFeed = {
if ($('#stream-container').height() < STUDIP.ActivityFeed.maxheight) {
STUDIP.ActivityFeed.loadFeed('');
}
- }).fail(function () {
- var template = STUDIP.ActivityFeed.getTemplate('activity-load-error');
+ }).catch(() => {
+ const template = STUDIP.ActivityFeed.getTemplate('activity-load-error');
STUDIP.ActivityFeed.writeToStream(template());
- }).always(function () {
+ }).finally(() => {
STUDIP.ActivityFeed.polling = false;
});
},
- writeToStream: function (html) {
+ writeToStream(html) {
if (STUDIP.ActivityFeed.initial) {
// replace data in DOM
$('#stream-container').html('');
@@ -98,9 +99,9 @@ const ActivityFeed = {
$('#stream-container').append(html);
},
- setToggleStatus: function() {
- var show_details = $('#toggle-all-activities').is('.toggled'),
- show_own = $('#toggle-user-activities').is('.toggled');
+ setToggleStatus() {
+ const show_details = $('#toggle-all-activities').is('.toggled');
+ const show_own = $('#toggle-user-activities').is('.toggled');
// update toggle status fir activity contents
$('.activity-content').toggle(show_details);
@@ -109,7 +110,7 @@ const ActivityFeed = {
$('.activity:has(.provider_circle.right)').toggle(show_own);
},
- updateFilter: function(filter) {
+ updateFilter(filter) {
STUDIP.ActivityFeed.filter = filter;
STUDIP.ActivityFeed.initial = true;
STUDIP.ActivityFeed.scrolledfrom = Math.floor(Date.now() / 1000);
diff --git a/resources/assets/javascripts/lib/fullcalendar.js b/resources/assets/javascripts/lib/fullcalendar.js
index 3b8fa11..5b7d032 100644
--- a/resources/assets/javascripts/lib/fullcalendar.js
+++ b/resources/assets/javascripts/lib/fullcalendar.js
@@ -622,8 +622,13 @@ class Fullcalendar
$('.fc-slats tr:odd .fc-widget-content:not(.fc-axis)').remove();
}
- STUDIP.api.GET(`semester/${timestamp}/week`).done((data) => {
+ if (document.getElementById('booking-plan-header-semname') === null) {
+ return;
+ }
+ $.getJSON(
+ STUDIP.URLHelper.getURL(`dispatch.php/resources/ajax/semester_week/${timestamp}`)
+ ).done((data) => {
if (data) {
$('#booking-plan-header-semname').text(data.semester_name);
if (data.sem_week) {
@@ -640,7 +645,7 @@ class Fullcalendar
$('#booking-plan-header-semrow').hide();
$('#booking-plan-header-semweek-part').hide();
}
- })
+ });
},
resourceRender (renderInfo) {
if ($(renderInfo.view.context.calendar.el).hasClass('room-group-booking-plan')) {
diff --git a/resources/assets/javascripts/lib/resources.js b/resources/assets/javascripts/lib/resources.js
index 3287b42..6ff4156 100644
--- a/resources/assets/javascripts/lib/resources.js
+++ b/resources/assets/javascripts/lib/resources.js
@@ -50,7 +50,7 @@ class Resources
jQuery(row_tds[user_td_index]).children('input').removeAttr('disabled');
if (username) {
- jQuery(row_tds[user_td_index]).append(username);
+ jQuery('<span>').text(username).appendTo(row_tds[user_td_index]);
} else {
jQuery(row_tds[user_td_index]).append('ID ' + user_id);
}
@@ -60,8 +60,6 @@ class Resources
}
jQuery(user_id_input).val(user_id);
- var perm_select = jQuery(row_tds[user_td_index + 1]).children()[0];
-
if (temp_perms_row) {
//Set the time input fields to useful values:
@@ -134,22 +132,19 @@ class Resources
jQuery(table_element).trigger('update');
};
- STUDIP.api.GET(
- `user/${user_id}`
- ).done(function (data) {
- var username = data.name.family
- + ', '
- + data.name.given;
- if (data.name.prefix) {
- username += ', ' + data.name.prefix;
+ STUDIP.jsonapi.GET(`users/${user_id}`).done(data => {
+ const attributes = data.data.attributes;
+
+ let username = `${attributes['family-name']}, ${attributes['given-name']}`;
+ if (attributes['name-prefix']) {
+ username += `, ${attributes['name-prefix']}`;
}
- if (data.name.suffix) {
- username += ' ' + data.name.suffix;
+ if (attributes['name-suffix']) {
+ username += ` ${attributes['name-suffix']}`;
}
- username += ' (' + data.name.username + ')'
- + ' (' + data.perms + ')';
+ username += ` (${attributes.username}) (${attributes.permission})`;
insert_function(user_id, username);
- }).fail(function () {
+ }).fail(() => {
insert_function(user_id);
});
}
@@ -160,23 +155,13 @@ class Resources
return;
}
- STUDIP.api.GET(
- `course/${course_id}/members`,
- {
- data: {
- //The limit '0' results in a division by zero.
- //Hopefully, the limit is set to a value high enough:
- limit: 1000000
- }
- }
- ).done(function (data) {
- for (var attribute in data.collection) {
- var user_id = data.collection[attribute].member.id;
+ STUDIP.jsonapi.GET(`courses/${course_id}/memberships`, {data: {page: {limit: 1000000}}}).done(data => {
+ data.data.forEach(membership => {
STUDIP.Resources.addUserToPermissionList(
- user_id,
+ membership.relationships.user.data.id,
table_element
);
- }
+ });
});
}
diff --git a/resources/assets/javascripts/lib/restapi.js b/resources/assets/javascripts/lib/restapi.js
deleted file mode 100644
index b6e31df..0000000
--- a/resources/assets/javascripts/lib/restapi.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import AbstractAPI from './abstract-api.js';
-
-// Actual RESTAPI object
-class RESTAPI extends AbstractAPI
-{
- constructor() {
- super('api.php');
- }
-}
-
-export default RESTAPI;
-export const api = new RESTAPI();
diff --git a/vendor/oauth-php/LICENSE b/vendor/oauth-php/LICENSE
deleted file mode 100644
index fbdcc37..0000000
--- a/vendor/oauth-php/LICENSE
+++ /dev/null
@@ -1,22 +0,0 @@
-The MIT License
-
-Copyright (c) 2007-2009 Mediamatic Lab
-Copyright (c) 2010 Corollarium Technologies
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE. \ No newline at end of file
diff --git a/vendor/oauth-php/README b/vendor/oauth-php/README
deleted file mode 100644
index ecd6815..0000000
--- a/vendor/oauth-php/README
+++ /dev/null
@@ -1 +0,0 @@
-Please see http://code.google.com/p/oauth-php/ for documentation and help.
diff --git a/vendor/oauth-php/example/client/googledocs.php b/vendor/oauth-php/example/client/googledocs.php
deleted file mode 100644
index 45d66cc..0000000
--- a/vendor/oauth-php/example/client/googledocs.php
+++ /dev/null
@@ -1,109 +0,0 @@
-<?php
-
-/**
- * oauth-php: Example OAuth client for accessing Google Docs
- *
- * @author BBG
- *
- *
- * The MIT License
- *
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-include_once "../../library/OAuthStore.php";
-include_once "../../library/OAuthRequester.php";
-
-define("GOOGLE_CONSUMER_KEY", "FILL THIS"); //
-define("GOOGLE_CONSUMER_SECRET", "FILL THIS"); //
-
-define("GOOGLE_OAUTH_HOST", "https://www.google.com");
-define("GOOGLE_REQUEST_TOKEN_URL", GOOGLE_OAUTH_HOST . "/accounts/OAuthGetRequestToken");
-define("GOOGLE_AUTHORIZE_URL", GOOGLE_OAUTH_HOST . "/accounts/OAuthAuthorizeToken");
-define("GOOGLE_ACCESS_TOKEN_URL", GOOGLE_OAUTH_HOST . "/accounts/OAuthGetAccessToken");
-
-define('OAUTH_TMP_DIR', function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : realpath($_ENV["TMP"]));
-
-// Init the OAuthStore
-$options = array(
- 'consumer_key' => GOOGLE_CONSUMER_KEY,
- 'consumer_secret' => GOOGLE_CONSUMER_SECRET,
- 'server_uri' => GOOGLE_OAUTH_HOST,
- 'request_token_uri' => GOOGLE_REQUEST_TOKEN_URL,
- 'authorize_uri' => GOOGLE_AUTHORIZE_URL,
- 'access_token_uri' => GOOGLE_ACCESS_TOKEN_URL
-);
-// Note: do not use "Session" storage in production. Prefer a database
-// storage, such as MySQL.
-OAuthStore::instance("Session", $options);
-
-try
-{
- // STEP 1: If we do not have an OAuth token yet, go get one
- if (empty($_GET["oauth_token"]))
- {
- $getAuthTokenParams = array('scope' =>
- 'http://docs.google.com/feeds/',
- 'xoauth_displayname' => 'Oauth test',
- 'oauth_callback' => 'XXXXXXXXXXX');
-
- // get a request token
- $tokenResultParams = OAuthRequester::requestRequestToken(GOOGLE_CONSUMER_KEY, 0, $getAuthTokenParams);
-
- // redirect to the google authorization page, they will redirect back
- header("Location: " . GOOGLE_AUTHORIZE_URL . "?btmpl=mobile&oauth_token=" . $tokenResultParams['token']);
- }
- else {
- // STEP 2: Get an access token
- $oauthToken = $_GET["oauth_token"];
-
- // echo "oauth_verifier = '" . $oauthVerifier . "'<br/>";
- $tokenResultParams = $_GET;
-
- try {
- OAuthRequester::requestAccessToken(GOOGLE_CONSUMER_KEY, $oauthToken, 0, 'POST', $_GET);
- }
- catch (OAuthException2 $e)
- {
- var_dump($e);
- // Something wrong with the oauth_token.
- // Could be:
- // 1. Was already ok
- // 2. We were not authorized
- return;
- }
-
- // make the docs requestrequest.
- $request = new OAuthRequester("http://docs.google.com/feeds/documents/private/full", 'GET', $tokenResultParams);
- $result = $request->doRequest(0);
- if ($result['code'] == 200) {
- var_dump($result['body']);
- }
- else {
- echo 'Error';
- }
- }
-}
-catch(OAuthException2 $e) {
- echo "OAuthException: " . $e->getMessage();
- var_dump($e);
-}
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/example/client/opera.php b/vendor/oauth-php/example/client/opera.php
deleted file mode 100644
index d881c98..0000000
--- a/vendor/oauth-php/example/client/opera.php
+++ /dev/null
@@ -1,125 +0,0 @@
-<?php
-
-/**
- * oauth-php: Example OAuth client for accessing my opera
- *
- * @author Ryan
- *
- *
- * The MIT License
- *
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- * Request your consumer key/secret here:
- * http://auth.opera.com/service/oauth/applications/
- * Make sure to set the Application callback URL
- *
- * To make this example work change the following files
- *
- * OAuthRequestSigner.php // Opera oAuth doesn't accept twice encoded signature
- * $this->setParam('oauth_signature', $signature, true);
- * to:
- * $this->setParam('oauth_signature', urldecode($signature), true);
- */
-
-include_once "../../library/OAuthStore.php";
-include_once "../../library/OAuthRequester.php";
-
-define("OPERA_CONSUMER_KEY", "---");
-define("OPERA_CONSUMER_SECRET", "---");
-
-define("OPERA_REQUEST_TOKEN_URL", "https://auth.opera.com/service/oauth/request_token");
-define("OPERA_AUTHORIZE_URL", "https://auth.opera.com/service/oauth/authorize");
-define("OPERA_ACCESS_TOKEN_URL", "https://auth.opera.com/service/oauth/access_token");
-
-define('OAUTH_TMP_DIR', function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : realpath($_ENV["TMP"]));
-
-// Start the session
-session_start();
-
-// Init the OAuthStore
-$options = array(
- 'consumer_key' => OPERA_CONSUMER_KEY,
- 'consumer_secret' => OPERA_CONSUMER_SECRET,
- 'server_uri' => 'http://my.opera.com/community/api/',
- 'request_token_uri' => OPERA_REQUEST_TOKEN_URL,
- 'authorize_uri' => OPERA_AUTHORIZE_URL,
- 'access_token_uri' => OPERA_ACCESS_TOKEN_URL
-);
-// Note: do not use "Session" storage in production. Prefer a database
-// storage, such as MySQL.
-OAuthStore::instance("Session", $options);
-
-try
-{
- // STEP 1: If we do not have an OAuth token yet, go get one
- if (empty($_GET["oauth_verifier"]))
- {
- $getAuthTokenParams = array(
- 'oauth_callback'=>'oob'
- );
- $options = array (
- 'oauth_as_header' => false
- );
-
- // get a request token
- $tokenResultParams = OAuthRequester::requestRequestToken(OPERA_CONSUMER_KEY, 0, $getAuthTokenParams, 'POST', $options);
- $_SESSION['oauth_token'] = $tokenResultParams['token'];
-
- // redirect to the opera authorization page, they will redirect back
- header("Location: " . OPERA_AUTHORIZE_URL . "?oauth_token=" . $tokenResultParams['token']);
- }
- else {
- // STEP 2: Get an access token
- try {
- OAuthRequester::requestAccessToken(OPERA_CONSUMER_KEY, $_SESSION['oauth_token'], 0, 'POST', $options=array(
- 'oauth_verifier'=>$_GET['oauth_verifier']
- ));
- }
- catch (OAuthException2 $e)
- {
- var_dump($e);
- // Something wrong with the oauth_token.
- // Could be:
- // 1. Was already ok
- // 2. We were not authorized
- return;
- }
-
- // make the docs requestrequest.
- $request = new OAuthRequester("http://my.opera.com/community/api/users/status.pl", 'GET');
- $result = $request->doRequest(0,array(
- CURLOPT_HTTPHEADER=>array(
- 'Accept: application/json',
- ),
- ));
- if ($result['code'] == 200) {
- var_dump($result['body']);
- }
- else {
- echo 'Error';
- }
- }
-}
-catch(OAuthException2 $e) {
- echo "OAuthException: " . $e->getMessage();
- var_dump($e);
-}
-?>
diff --git a/vendor/oauth-php/example/client/twolegged.php b/vendor/oauth-php/example/client/twolegged.php
deleted file mode 100644
index a22c4fd..0000000
--- a/vendor/oauth-php/example/client/twolegged.php
+++ /dev/null
@@ -1,67 +0,0 @@
-<?php
-
-/**
- * oauth-php: Example OAuth client
- *
- * Performs simple 2-legged authentication
- *
- * @author Ben Hesketh
- *
- *
- * The MIT License
- *
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-include_once "../../library/OAuthStore.php";
-include_once "../../library/OAuthRequester.php";
-
-// Test of the OAuthStore2Leg
-
-$key = '???????'; // fill with your public key
-$secret = '????????'; // fill with your secret key
-$url = "?????????"; // fill with the url for the oauth service
-
-$options = array('consumer_key' => $key, 'consumer_secret' => $secret);
-OAuthStore::instance("2Leg", $options);
-
-$method = "GET";
-$params = null;
-
-try
-{
- // Obtain a request object for the request we want to make
- $request = new OAuthRequester($url, $method, $params);
-
- // Sign the request, perform a curl request and return the results,
- // throws OAuthException2 exception on an error
- // $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
- $result = $request->doRequest();
-
- $response = $result['body'];
- var_dump($response);
-}
-catch(OAuthException2 $e)
-{
- echo "Exception";
-}
-
-?>
diff --git a/vendor/oauth-php/example/client/twoleggedtest.php b/vendor/oauth-php/example/client/twoleggedtest.php
deleted file mode 100644
index 0fc866b..0000000
--- a/vendor/oauth-php/example/client/twoleggedtest.php
+++ /dev/null
@@ -1,78 +0,0 @@
-<?php
-
-/**
- * oauth-php: Example OAuth client
- *
- * Performs simple 2-legged authentication
- *
- * @author Ben Hesketh
- *
- *
- * The MIT License
- *
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-include_once "../../library/OAuthStore.php";
-include_once "../../library/OAuthRequester.php";
-
-// Test of the OAuthStore2Leg
-// uses http://term.ie/oauth/example/
-
-$key = 'key'; // fill with your public key
-$secret = 'secret'; // fill with your secret key
-$url = "http://term.ie/oauth/example/request_token.php"; // fill with the url for the oauth service
-
-$options = array('consumer_key' => $key, 'consumer_secret' => $secret);
-OAuthStore::instance("2Leg", $options);
-
-$method = "GET";
-$params = null;
-
-try
-{
- // Obtain a request object for the request we want to make
- $request = new OAuthRequester($url, $method, $params);
-
- // Sign the request, perform a curl request and return the results,
- // throws OAuthException2 exception on an error
- // $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
- $result = $request->doRequest();
-
- $response = $result['body'];
-
- if ($response != 'oauth_token=requestkey&oauth_token_secret=requestsecret')
- {
- echo 'Error! $response ' . $response;
- }
- else
- {
- }
-
-
- var_dump($response);
-}
-catch(OAuthException2 $e)
-{
- echo "Exception" . $e->getMessage();
-}
-
-?>
diff --git a/vendor/oauth-php/example/client/twoleggedtwitter.php b/vendor/oauth-php/example/client/twoleggedtwitter.php
deleted file mode 100644
index 871c2a4..0000000
--- a/vendor/oauth-php/example/client/twoleggedtwitter.php
+++ /dev/null
@@ -1,67 +0,0 @@
-<?php
-
-/**
- * oauth-php: Example OAuth client
- *
- * Performs simple 2-legged authentication
- *
- * The MIT License
- *
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-include_once "../../library/OAuthStore.php";
-include_once "../../library/OAuthRequester.php";
-
-// register at http://twitter.com/oauth_clients and fill these two
-define("TWITTER_CONSUMER_KEY", "FILL THIS");
-define("TWITTER_CONSUMER_SECRET", "FILL THIS");
-
-define("TWITTER_OAUTH_HOST","https://twitter.com");
-define("TWITTER_REQUEST_TOKEN_URL", TWITTER_OAUTH_HOST . "/oauth/request_token");
-define("TWITTER_AUTHORIZE_URL", TWITTER_OAUTH_HOST . "/oauth/authorize");
-define("TWITTER_ACCESS_TOKEN_URL", TWITTER_OAUTH_HOST . "/oauth/access_token");
-define("TWITTER_PUBLIC_TIMELINE_API", TWITTER_OAUTH_HOST . "/statuses/public_timeline.json");
-define("TWITTER_UPDATE_STATUS_API", TWITTER_OAUTH_HOST . "/statuses/update.json");
-
-define('OAUTH_TMP_DIR', function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : realpath($_ENV["TMP"]));
-
-// Twitter test
-$options = array('consumer_key' => TWITTER_CONSUMER_KEY, 'consumer_secret' => TWITTER_CONSUMER_SECRET);
-OAuthStore::instance("2Leg", $options);
-
-try
-{
- // Obtain a request object for the request we want to make
- $request = new OAuthRequester(TWITTER_REQUEST_TOKEN_URL, "POST");
- $result = $request->doRequest(0);
- parse_str($result['body'], $params);
-
- // now make the request.
- $request = new OAuthRequester(TWITTER_PUBLIC_TIMELINE_API, 'GET', $params);
- $result = $request->doRequest();
-}
-catch(OAuthException2 $e)
-{
- echo "Exception" . $e->getMessage();
-}
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/example/server/INSTALL b/vendor/oauth-php/example/server/INSTALL
deleted file mode 100644
index 249c85e..0000000
--- a/vendor/oauth-php/example/server/INSTALL
+++ /dev/null
@@ -1,53 +0,0 @@
-In this example I assume that oauth-php lives in /home/john/src/oauth-php
-
-
-1) Create a virtual host and set the DB_DSN VARIABLE to the DSN of your (mysql) database.
-
-Example
-<VirtualHost *>
- ServerAdmin admin@localhost
- ServerName hello.local
- DocumentRoot /home/john/src/oauth-php/example/server/www
-
- UseCanonicalName Off
- ServerSignature On
-
- SetEnv DB_DSN mysql://foo:bar@localhost/oauth_example_server_db
-
- <Directory "home/john/src/oauth-php/example/server/www">
- Options Indexes FollowSymLinks MultiViews
- AllowOverride None
- Order allow,deny
- Allow from all
-
- <IfModule mod_php5.c>
- php_value magic_quotes_gpc 0
- php_value register_globals 0
- php_value session.auto_start 0
- </IfModule>
-
- </Directory>
-</VirtualHost>
-
-
-2) Create the database structure for the server:
-
-# mysql -u foo -p bar -h localhost < /home/john/src/oauth-php/library/store/mysql/mysql.sql
-
-
-
-3) Download and install smarty into the smarty/core/smarty directory:
-
-# cd /home/john/src/oauth-php/example/server/core
-# wget 'http://www.smarty.net/do_download.php?download_file=Smarty-2.6.19.tar.gz'
-# tar zxf Smarty-2.6.19.tar.gz
-# mv Smarty-2.6.19 smarty
-
-
-4) That's it! Point your browser to
-
- http://hello.local/
-
-To get started.
-
-Arjan Scherpenisse <arjan@mediamatic.nl>, July 2008
diff --git a/vendor/oauth-php/example/server/core/init.php b/vendor/oauth-php/example/server/core/init.php
deleted file mode 100644
index 82c65db..0000000
--- a/vendor/oauth-php/example/server/core/init.php
+++ /dev/null
@@ -1,128 +0,0 @@
-<?php
-
-/**
- * oauth-php: Example OAuth server
- *
- * Global initialization file for the server, defines some helper
- * functions, required includes, and starts the session.
- *
- * @author Arjan Scherpenisse <arjan@scherpenisse.net>
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-/*
- * Simple 'user management'
- */
-define ('USERNAME', 'sysadmin');
-define ('PASSWORD', 'sysadmin');
-
-
-/*
- * Always announce XRDS OAuth discovery
- */
-header('X-XRDS-Location: http://' . $_SERVER['SERVER_NAME'] . '/services.xrds');
-
-
-/*
- * Initialize the database connection
- */
-$info = parse_url(getenv('DB_DSN'));
-($GLOBALS['db_conn'] = mysql_connect($info['host'], $info['user'], $info['pass'])) || die(mysql_error());
-mysql_select_db(basename($info['path']), $GLOBALS['db_conn']) || die(mysql_error());
-unset($info);
-
-
-require_once '../../../library/OAuthServer.php';
-
-/*
- * Initialize OAuth store
- */
-require_once '../../../library/OAuthStore.php';
-OAuthStore::instance('MySQL', array('conn' => $GLOBALS['db_conn']));
-
-
-/*
- * Session
- */
-session_start();
-
-
-/*
- * Template handling
- */
-require_once 'smarty/libs/Smarty.class.php';
-function session_smarty()
-{
- if (!isset($GLOBALS['smarty']))
- {
- $GLOBALS['smarty'] = new Smarty;
- $GLOBALS['smarty']->template_dir = dirname(__FILE__) . '/templates/';
- $GLOBALS['smarty']->compile_dir = dirname(__FILE__) . '/../cache/templates_c';
- }
-
- return $GLOBALS['smarty'];
-}
-
-function assert_logged_in()
-{
- if (empty($_SESSION['authorized']))
- {
- $uri = $_SERVER['REQUEST_URI'];
- header('Location: /logon?goto=' . urlencode($uri));
- exit();
- }
-}
-
-function assert_request_vars()
-{
- foreach(func_get_args() as $a)
- {
- if (!isset($_REQUEST[$a]))
- {
- header('HTTP/1.1 400 Bad Request');
- echo 'Bad request.';
- exit;
- }
- }
-}
-
-function assert_request_vars_all()
-{
- foreach($_REQUEST as $row)
- {
- foreach(func_get_args() as $a)
- {
- if (!isset($row[$a]))
- {
- header('HTTP/1.1 400 Bad Request');
- echo 'Bad request.';
- exit;
- }
- }
- }
-}
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/example/server/core/templates/inc/footer.tpl b/vendor/oauth-php/example/server/core/templates/inc/footer.tpl
deleted file mode 100644
index 308b1d0..0000000
--- a/vendor/oauth-php/example/server/core/templates/inc/footer.tpl
+++ /dev/null
@@ -1,2 +0,0 @@
-</body>
-</html>
diff --git a/vendor/oauth-php/example/server/core/templates/inc/header.tpl b/vendor/oauth-php/example/server/core/templates/inc/header.tpl
deleted file mode 100644
index 5046f54..0000000
--- a/vendor/oauth-php/example/server/core/templates/inc/header.tpl
+++ /dev/null
@@ -1,2 +0,0 @@
-<html>
- <body>
diff --git a/vendor/oauth-php/example/server/core/templates/index.tpl b/vendor/oauth-php/example/server/core/templates/index.tpl
deleted file mode 100644
index 7b06553..0000000
--- a/vendor/oauth-php/example/server/core/templates/index.tpl
+++ /dev/null
@@ -1,13 +0,0 @@
-{include file='inc/header.tpl'}
-
-<h1>OAuth server</h1>
-Go to:
-
-<ul>
- <li><a href="/logon">Logon</a></li>
- <li><a href="/register">Register your consumer</a></li>
-</ul>
-
-Afterwards, make an OAuth test request to <strong>http://{$smarty.server.name}/hello</strong> to test your connection.</p>
-
-{include file='inc/footer.tpl'}
diff --git a/vendor/oauth-php/example/server/core/templates/logon.tpl b/vendor/oauth-php/example/server/core/templates/logon.tpl
deleted file mode 100644
index 5ccd432..0000000
--- a/vendor/oauth-php/example/server/core/templates/logon.tpl
+++ /dev/null
@@ -1,21 +0,0 @@
-{include file='inc/header.tpl'}
-
-<h1>Login</h1>
-
-<form method="post">
- <input type="hidden" name="goto" value="{$smarty.request.goto}" />
-
- <label for="username">User name</label><br />
- <input type="text" name="username" id="username" />
-
- <br /><br />
-
- <label for="password">Password</label><br />
- <input type="text" name="password" id="password" />
-
- <br /><br />
-
- <input type="submit" value="Login" />
-</form>
-
-{include file='inc/footer.tpl'}
diff --git a/vendor/oauth-php/example/server/core/templates/register.tpl b/vendor/oauth-php/example/server/core/templates/register.tpl
deleted file mode 100644
index 0e28c15..0000000
--- a/vendor/oauth-php/example/server/core/templates/register.tpl
+++ /dev/null
@@ -1,41 +0,0 @@
-{include file='inc/header.tpl'}
-
-<h1>Register server</h1>
-
-<p>Register a server which is gonna act as an identity client.</p>
-
-<form method="post">
-
- <fieldset>
- <legend>About You</legend>
-
- <p>
- <label for="requester_name">Your name</label><br/>
- <input class="text" id="requester_name" name="requester_name" type="text" value="{$consumer.requester_name|default:$smarty.request.requester_name|escape}" />
- </p>
-
- <p>
- <label for="requester_email">Your email address</label><br/>
- <input class="text" id="requester_email" name="requester_email" type="text" value="{$consumer.requester_email|default:$smarty.request.requester_email|escape}" />
- </p>
- </fieldset>
-
- <fieldset>
- <legend>Location Of Your Application Or Site</legend>
-
- <p>
- <label for="application_uri">URL of your application or site</label><br/>
- <input id="application_uri" class="text" name="application_uri" type="text" value="{$consumer.application_uri|default:$smarty.request.application_uri|escape}" />
- </p>
-
- <p>
- <label for="callback_uri">Callback URL</label><br/>
- <input id="callback_uri" class="text" name="callback_uri" type="text" value="{$consumer.callback_uri|default:$smarty.request.callback_uri|escape}" />
- </p>
- </fieldset>
-
- <br />
- <input type="submit" value="Register server" />
-</form>
-
-{include file='inc/footer.tpl'}
diff --git a/vendor/oauth-php/example/server/www/hello.php b/vendor/oauth-php/example/server/www/hello.php
deleted file mode 100644
index 12526a9..0000000
--- a/vendor/oauth-php/example/server/www/hello.php
+++ /dev/null
@@ -1,65 +0,0 @@
-<?php
-
-/**
- * oauth-php: Example OAuth server
- *
- * An example service, http://hostname/hello. You will only get the
- * 'Hello, world!' string back if you have signed your request with
- * oauth.
- *
- * @author Arjan Scherpenisse <arjan@scherpenisse.net>
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once '../core/init.php';
-
-$authorized = false;
-$server = new OAuthServer();
-try
-{
- if ($server->verifyIfSigned())
- {
- $authorized = true;
- }
-}
-catch (OAuthException2 $e)
-{
-}
-
-if (!$authorized)
-{
- header('HTTP/1.1 401 Unauthorized');
- header('Content-Type: text/plain');
-
- echo "OAuth Verification Failed: " . $e->getMessage();
- die;
-}
-
-// From here on we are authenticated with OAuth.
-
-header('Content-type: text/plain');
-echo 'Hello, world!';
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/example/server/www/index.php b/vendor/oauth-php/example/server/www/index.php
deleted file mode 100644
index f5cadbe..0000000
--- a/vendor/oauth-php/example/server/www/index.php
+++ /dev/null
@@ -1,37 +0,0 @@
-<?php
-
-/**
- * oauth-php: Example OAuth server
- *
- * @author Arjan Scherpenisse <arjan@scherpenisse.net>
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require '../core/init.php';
-
-$smarty = session_smarty();
-$smarty->display('index.tpl');
-
-?>
diff --git a/vendor/oauth-php/example/server/www/logon.php b/vendor/oauth-php/example/server/www/logon.php
deleted file mode 100644
index 5c937b7..0000000
--- a/vendor/oauth-php/example/server/www/logon.php
+++ /dev/null
@@ -1,55 +0,0 @@
-<?php
-
-/**
- * oauth-php: Example OAuth server
- *
- * Simple logon for consumer registration at this server.
- *
- * @author Arjan Scherpenisse <arjan@scherpenisse.net>
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once '../core/init.php';
-
-if (isset($_POST['username']) && isset($_POST['password']))
-{
- if ($_POST['username'] == USERNAME && $_POST['password'] == PASSWORD)
- {
- $_SESSION['authorized'] = true;
- if (!empty($_REQUEST['goto']))
- {
- header('Location: ' . $_REQUEST['goto']);
- die;
- }
-
- echo "Logon succesfull.";
- die;
- }
-}
-
-$smarty = session_smarty();
-$smarty->display('logon.tpl');
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/example/server/www/oauth.php b/vendor/oauth-php/example/server/www/oauth.php
deleted file mode 100644
index 6dafd61..0000000
--- a/vendor/oauth-php/example/server/www/oauth.php
+++ /dev/null
@@ -1,77 +0,0 @@
-<?php
-
-/**
- * oauth-php: Example OAuth server
- *
- * This file implements the OAuth server endpoints. The most basic
- * implementation of an OAuth server.
- *
- * Call with: /oauth/request_token, /oauth/authorize, /oauth/access_token
- *
- * @author Arjan Scherpenisse <arjan@scherpenisse.net>
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once '../core/init.php';
-
-$server = new OAuthServer();
-
-switch($_SERVER['PATH_INFO'])
-{
-case '/request_token':
- $server->requestToken();
- exit;
-
-case '/access_token':
- $server->accessToken();
- exit;
-
-case '/authorize':
- # logon
-
- assert_logged_in();
-
- try
- {
- $server->authorizeVerify();
- $server->authorizeFinish(true, 1);
- }
- catch (OAuthException2 $e)
- {
- header('HTTP/1.1 400 Bad Request');
- header('Content-Type: text/plain');
-
- echo "Failed OAuth Request: " . $e->getMessage();
- }
- exit;
-
-
-default:
- header('HTTP/1.1 500 Internal Server Error');
- header('Content-Type: text/plain');
- echo "Unknown request";
-}
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/example/server/www/register.php b/vendor/oauth-php/example/server/www/register.php
deleted file mode 100644
index 0a74297..0000000
--- a/vendor/oauth-php/example/server/www/register.php
+++ /dev/null
@@ -1,29 +0,0 @@
-<?php
-
-require_once '../core/init.php';
-
-assert_logged_in();
-
-if ($_SERVER['REQUEST_METHOD'] == 'POST')
-{
- try
- {
- $store = OAuthStore::instance();
- $user_id = 1; // this should not be hardcoded, of course
- $key = $store->updateConsumer($_POST, $user_id, true);
-
- $c = $store->getConsumer($key, $user_id);
- echo 'Your consumer key is: <strong>' . $c['consumer_key'] . '</strong><br />';
- echo 'Your consumer secret is: <strong>' . $c['consumer_secret'] . '</strong><br />';
- }
- catch (OAuthException2 $e)
- {
- echo '<strong>Error: ' . $e->getMessage() . '</strong><br />';
- }
-}
-
-
-$smarty = session_smarty();
-$smarty->display('register.tpl');
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/example/server/www/services.xrds.php b/vendor/oauth-php/example/server/www/services.xrds.php
deleted file mode 100644
index 0f4bbac..0000000
--- a/vendor/oauth-php/example/server/www/services.xrds.php
+++ /dev/null
@@ -1,71 +0,0 @@
-<?php
-
-/**
- * oauth-php: Example OAuth server
- *
- * XRDS discovery for OAuth. This file helps the consumer program to
- * discover where the OAuth endpoints for this server are.
- *
- * @author Arjan Scherpenisse <arjan@scherpenisse.net>
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-header('Content-Type: application/xrds+xml');
-
-$server = $_SERVER['SERVER_NAME'];
-
-echo '<?xml version="1.0" encoding="utf-8"?>' . "\n";
-
-?>
-<XRDS xmlns="xri://$xrds">
- <XRD xmlns:simple="http://xrds-simple.net/core/1.0" xmlns="xri://$XRD*($v*2.0)" xmlns:openid="http://openid.net/xmlns/1.0" version="2.0" xml:id="main">
- <Type>xri://$xrds*simple</Type>
- <Service>
- <Type>http://oauth.net/discovery/1.0</Type>
- <URI>#main</URI>
- </Service>
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/request</Type>
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
- <Type>http://oauth.net/core/1.0/signature/HMAC-SHA1</Type>
- <Type>http://oauth.net/core/1.0/signature/PLAINTEXT</Type>
- <URI>http://<?php echo $server; ?>/oauth/request_token</URI>
- </Service>
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/authorize</Type>
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
- <URI>http://<?php echo $server; ?>/oauth/authorize</URI>
- </Service>
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/access</Type>
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
- <Type>http://oauth.net/core/1.0/signature/HMAC-SHA1</Type>
- <Type>http://oauth.net/core/1.0/signature/PLAINTEXT</Type>
- <URI>http://<?php echo $server; ?>/oauth/access_token</URI>
- </Service>
- </XRD>
-</XRDS>
diff --git a/vendor/oauth-php/library/OAuthDiscovery.php b/vendor/oauth-php/library/OAuthDiscovery.php
deleted file mode 100644
index 8eee118..0000000
--- a/vendor/oauth-php/library/OAuthDiscovery.php
+++ /dev/null
@@ -1,227 +0,0 @@
-<?php
-
-/**
- * Handle the discovery of OAuth service provider endpoints and static consumer identity.
- *
- * @version $Id$
- * @author Marc Worrell <marcw@pobox.com>
- * @date Sep 4, 2008 5:05:19 PM
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__).'/discovery/xrds_parse.php';
-
-require_once dirname(__FILE__).'/OAuthException2.php';
-require_once dirname(__FILE__).'/OAuthRequestLogger.php';
-
-
-class OAuthDiscovery
-{
- /**
- * Return a description how we can do a consumer allocation. Prefers static allocation if
- * possible. If static allocation is possible
- *
- * See also: http://oauth.net/discovery/#consumer_identity_types
- *
- * @param string uri
- * @return array provider description
- */
- static function discover ( $uri )
- {
- // See what kind of consumer allocations are available
- $xrds_file = self::discoverXRDS($uri);
- if (!empty($xrds_file))
- {
- $xrds = xrds_parse($xrds_file);
- if (empty($xrds))
- {
- throw new OAuthException2('Could not discover OAuth information for '.$uri);
- }
- }
- else
- {
- throw new OAuthException2('Could not discover XRDS file at '.$uri);
- }
-
- // Fill an OAuthServer record for the uri found
- $ps = parse_url($uri);
- $host = isset($ps['host']) ? $ps['host'] : 'localhost';
- $server_uri = $ps['scheme'].'://'.$host.'/';
-
- $p = array(
- 'user_id' => null,
- 'consumer_key' => '',
- 'consumer_secret' => '',
- 'signature_methods' => '',
- 'server_uri' => $server_uri,
- 'request_token_uri' => '',
- 'authorize_uri' => '',
- 'access_token_uri' => ''
- );
-
-
- // Consumer identity (out of bounds or static)
- if (isset($xrds['consumer_identity']))
- {
- // Try to find a static consumer allocation, we like those :)
- foreach ($xrds['consumer_identity'] as $ci)
- {
- if ($ci['method'] == 'static' && !empty($ci['consumer_key']))
- {
- $p['consumer_key'] = $ci['consumer_key'];
- $p['consumer_secret'] = '';
- }
- else if ($ci['method'] == 'oob' && !empty($ci['uri']))
- {
- // TODO: Keep this uri somewhere for the user?
- $p['consumer_oob_uri'] = $ci['uri'];
- }
- }
- }
-
- // The token uris
- if (isset($xrds['request'][0]['uri']))
- {
- $p['request_token_uri'] = $xrds['request'][0]['uri'];
- if (!empty($xrds['request'][0]['signature_method']))
- {
- $p['signature_methods'] = $xrds['request'][0]['signature_method'];
- }
- }
- if (isset($xrds['authorize'][0]['uri']))
- {
- $p['authorize_uri'] = $xrds['authorize'][0]['uri'];
- if (!empty($xrds['authorize'][0]['signature_method']))
- {
- $p['signature_methods'] = $xrds['authorize'][0]['signature_method'];
- }
- }
- if (isset($xrds['access'][0]['uri']))
- {
- $p['access_token_uri'] = $xrds['access'][0]['uri'];
- if (!empty($xrds['access'][0]['signature_method']))
- {
- $p['signature_methods'] = $xrds['access'][0]['signature_method'];
- }
- }
- return $p;
- }
-
-
- /**
- * Discover the XRDS file at the uri. This is a bit primitive, you should overrule
- * this function so that the XRDS file can be cached for later referral.
- *
- * @param string uri
- * @return string false when no XRDS file found
- */
- static protected function discoverXRDS ( $uri, $recur = 0 )
- {
- // Bail out when we are following redirects
- if ($recur > 10)
- {
- return false;
- }
-
- $data = self::curl($uri);
-
- // Check what we got back, could be:
- // 1. The XRDS discovery file itself (check content-type)
- // 2. The X-XRDS-Location header
-
- if (is_string($data) && !empty($data))
- {
- list($head,$body) = explode("\r\n\r\n", $data);
- $body = trim($body);
- $m = false;
-
- // See if we got the XRDS file itself or we have to follow a location header
- if ( preg_match('/^Content-Type:\s*application\/xrds+xml/im', $head)
- || preg_match('/^<\?xml[^>]*\?>\s*<xrds\s/i', $body)
- || preg_match('/^<xrds\s/i', $body)
- )
- {
- $xrds = $body;
- }
- else if ( preg_match('/^X-XRDS-Location:\s*([^\r\n]*)/im', $head, $m)
- || preg_match('/^Location:\s*([^\r\n]*)/im', $head, $m))
- {
- // Recurse to the given location
- if ($uri != $m[1])
- {
- $xrds = self::discoverXRDS($m[1], $recur+1);
- }
- else
- {
- // Referring to the same uri, bail out
- $xrds = false;
- }
- }
- else
- {
- // Not an XRDS file an nowhere else to check
- $xrds = false;
- }
- }
- else
- {
- $xrds = false;
- }
- return $xrds;
- }
-
-
- /**
- * Try to fetch an XRDS file at the given location. Sends an accept header preferring the xrds file.
- *
- * @param string uri
- * @return array (head,body), false on an error
- */
- static protected function curl ( $uri )
- {
- $ch = curl_init();
-
- curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*;q=0.1'));
- curl_setopt($ch, CURLOPT_USERAGENT, 'anyMeta/OAuth 1.0 - (OAuth Discovery $LastChangedRevision: 45 $)');
- curl_setopt($ch, CURLOPT_URL, $uri);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HEADER, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, 30);
-
- $txt = curl_exec($ch);
- curl_close($ch);
-
- // Tell the logger what we requested and what we received back
- $data = "GET $uri";
- OAuthRequestLogger::setSent($data, "");
- OAuthRequestLogger::setReceived($txt);
-
- return $txt;
- }
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/OAuthException2.php b/vendor/oauth-php/library/OAuthException2.php
deleted file mode 100644
index 30fc80e..0000000
--- a/vendor/oauth-php/library/OAuthException2.php
+++ /dev/null
@@ -1,50 +0,0 @@
-<?php
-
-/**
- * Simple exception wrapper for OAuth
- *
- * @version $Id: OAuthException2.php 67 2010-01-12 18:42:04Z brunobg@corollarium.com $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Nov 29, 2007 5:33:54 PM
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-// TODO: something with the HTTP return code matching to the problem
-
-require_once dirname(__FILE__) . '/OAuthRequestLogger.php';
-
-class OAuthException2 extends Exception
-{
- function __construct ( $message )
- {
- Exception::__construct($message);
- OAuthRequestLogger::addNote('OAuthException2: '.$message);
- }
-
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/OAuthRequest.php b/vendor/oauth-php/library/OAuthRequest.php
deleted file mode 100644
index 41448a3..0000000
--- a/vendor/oauth-php/library/OAuthRequest.php
+++ /dev/null
@@ -1,854 +0,0 @@
-<?php
-
-/**
- * Request wrapper class. Prepares a request for consumption by the OAuth routines
- *
- * @version $Id: OAuthRequest.php 186 2011-02-18 15:46:18Z scherpenisse $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Nov 16, 2007 12:20:31 PM
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-require_once dirname(__FILE__) . '/OAuthException2.php';
-
-/**
- * Object to parse an incoming OAuth request or prepare an outgoing OAuth request
- */
-class OAuthRequest
-{
- /* the realm for this request */
- protected $realm;
-
- /* all the parameters, RFC3986 encoded name/value pairs */
- protected $param = array();
-
- /* the parsed request uri */
- protected $uri_parts;
-
- /* the raw request uri */
- protected $uri;
-
- /* the request headers */
- protected $headers;
-
- /* the request method */
- protected $method;
-
- /* the body of the OAuth request */
- protected $body;
-
-
- /**
- * Construct from the current request. Useful for checking the signature of a request.
- * When not supplied with any parameters this will use the current request.
- *
- * @param string uri might include parameters
- * @param string method GET, PUT, POST etc.
- * @param string parameters additional post parameters, urlencoded (RFC1738)
- * @param array headers headers for request
- * @param string body optional body of the OAuth request (POST or PUT)
- */
- function __construct ( $uri = null, $method = null, $parameters = '', $headers = array(), $body = null )
- {
- if (is_object($_SERVER))
- {
- // Tainted arrays - the normal stuff in anyMeta
- if (!$method) {
- $method = $_SERVER->REQUEST_METHOD->getRawUnsafe();
- }
- if (empty($uri)) {
- $uri = $_SERVER->REQUEST_URI->getRawUnsafe();
- $proto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
- if (strpos($uri, "://") === false) {
- $uri = sprintf('%s://%s%s', $proto, $_SERVER->HTTP_HOST->getRawUnsafe(), $uri);
- }
- }
- }
- else
- {
- // non anyMeta systems
- if (!$method) {
- if (isset($_SERVER['REQUEST_METHOD'])) {
- $method = $_SERVER['REQUEST_METHOD'];
- }
- else {
- $method = 'GET';
- }
- }
- $proto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
- if (empty($uri)) {
- if (strpos($_SERVER['REQUEST_URI'], "://") !== false) {
- $uri = $_SERVER['REQUEST_URI'];
- }
- else {
- $uri = sprintf('%s://%s%s', $proto, $_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI']);
- }
- }
- }
- $headers = OAuthRequestLogger::getAllHeaders();
- $this->method = strtoupper($method);
-
- // If this is a post then also check the posted variables
- if (strcasecmp($method, 'POST') == 0)
- {
- // TODO: what to do with 'multipart/form-data'?
- if ($this->getRequestContentType() == 'multipart/form-data')
- {
- // Get the posted body (when available)
- if (!isset($headers['X-OAuth-Test']))
- {
- $parameters .= $this->getRequestBodyOfMultipart();
- }
- }
- if ($this->getRequestContentType() == 'application/x-www-form-urlencoded')
- {
- // Get the posted body (when available)
- if (!isset($headers['X-OAuth-Test']))
- {
- $parameters .= $this->getRequestBody();
- }
- }
- else
- {
- $body = $this->getRequestBody();
- }
- }
- else if (strcasecmp($method, 'PUT') == 0)
- {
- $body = $this->getRequestBody();
- }
-
- $this->method = strtoupper($method);
- $this->headers = $headers;
- // Store the values, prepare for oauth
- $this->uri = $uri;
- $this->body = $body;
- $this->parseUri($parameters);
- $this->parseHeaders();
- $this->transcodeParams();
- }
-
-
- /**
- * Return the signature base string.
- * Note that we can't use rawurlencode due to specified use of RFC3986.
- *
- * @return string
- */
- function signatureBaseString ()
- {
- $sig = array();
- $sig[] = $this->method;
- $sig[] = $this->getRequestUrl();
- $sig[] = $this->getNormalizedParams();
-
- return implode('&', array_map(array($this, 'urlencode'), $sig));
- }
-
-
- /**
- * Calculate the signature of the request, using the method in oauth_signature_method.
- * The signature is returned encoded in the form as used in the url. So the base64 and
- * urlencoding has been done.
- *
- * @param string consumer_secret
- * @param string token_secret
- * @param string token_type
- * @exception when not all parts available
- * @return string
- */
- function calculateSignature ( $consumer_secret, $token_secret, $token_type = 'access' )
- {
- $required = array(
- 'oauth_consumer_key',
- 'oauth_signature_method',
- 'oauth_timestamp',
- 'oauth_nonce'
- );
-
- if ($token_type != 'requestToken')
- {
- $required[] = 'oauth_token';
- }
-
- foreach ($required as $req)
- {
- if (!isset($this->param[$req]))
- {
- throw new OAuthException2('Can\'t sign request, missing parameter "'.$req.'"');
- }
- }
-
- $this->checks();
-
- $base = $this->signatureBaseString();
- $signature = $this->calculateDataSignature($base, $consumer_secret, $token_secret, $this->param['oauth_signature_method']);
- return $signature;
- }
-
-
- /**
- * Calculate the signature of a string.
- * Uses the signature method from the current parameters.
- *
- * @param string data
- * @param string consumer_secret
- * @param string token_secret
- * @param string signature_method
- * @exception OAuthException2 thrown when the signature method is unknown
- * @return string signature
- */
- function calculateDataSignature ( $data, $consumer_secret, $token_secret, $signature_method )
- {
- if (is_null($data))
- {
- $data = '';
- }
-
- $sig = $this->getSignatureMethod($signature_method);
- return $sig->signature($this, $data, $consumer_secret, $token_secret);
- }
-
-
- /**
- * Select a signature method from the list of available methods.
- * We try to check the most secure methods first.
- *
- * @todo Let the signature method tell us how secure it is
- * @param array methods
- * @exception OAuthException2 when we don't support any method in the list
- * @return string
- */
- public function selectSignatureMethod ( $methods )
- {
- if (in_array('HMAC-SHA1', $methods))
- {
- $method = 'HMAC-SHA1';
- }
- else if (in_array('MD5', $methods))
- {
- $method = 'MD5';
- }
- else
- {
- $method = false;
- foreach ($methods as $m)
- {
- $m = strtoupper($m);
- $m2 = preg_replace('/[^A-Z0-9]/', '_', $m);
- if (file_exists(dirname(__FILE__).'/signature_method/OAuthSignatureMethod_'.$m2.'.php'))
- {
- $method = $m;
- break;
- }
- }
-
- if (empty($method))
- {
- throw new OAuthException2('None of the signing methods is supported.');
- }
- }
- return $method;
- }
-
-
- /**
- * Fetch the signature object used for calculating and checking the signature base string
- *
- * @param string method
- * @return OAuthSignatureMethod object
- */
- function getSignatureMethod ( $method )
- {
- $m = strtoupper($method);
- $m = preg_replace('/[^A-Z0-9]/', '_', $m);
- $class = 'OAuthSignatureMethod_'.$m;
-
- if (file_exists(dirname(__FILE__).'/signature_method/'.$class.'.php'))
- {
- require_once dirname(__FILE__).'/signature_method/'.$class.'.php';
- $sig = new $class();
- }
- else
- {
- throw new OAuthException2('Unsupported signature method "'.$m.'".');
- }
- return $sig;
- }
-
-
- /**
- * Perform some sanity checks.
- *
- * @exception OAuthException2 thrown when sanity checks failed
- */
- function checks ()
- {
- if (isset($this->param['oauth_version']))
- {
- $version = $this->urldecode($this->param['oauth_version']);
- if ($version != '1.0')
- {
- throw new OAuthException2('Expected OAuth version 1.0, got "'.$this->param['oauth_version'].'"');
- }
- }
- }
-
-
- /**
- * Return the request method
- *
- * @return string
- */
- function getMethod ()
- {
- return $this->method;
- }
-
- /**
- * Return the complete parameter string for the signature check.
- * All parameters are correctly urlencoded and sorted on name and value
- *
- * @return string
- */
- function getNormalizedParams ()
- {
- /*
- // sort by name, then by value
- // (needed when we start allowing multiple values with the same name)
- $keys = array_keys($this->param);
- $values = array_values($this->param);
- array_multisort($keys, SORT_ASC, $values, SORT_ASC);
- */
- $params = $this->param;
- $normalized = array();
-
- ksort($params);
- foreach ($params as $key => $value)
- {
- // all names and values are already urlencoded, exclude the oauth signature
- if ($key != 'oauth_signature')
- {
- if (is_array($value))
- {
- $value_sort = $value;
- sort($value_sort);
- foreach ($value_sort as $v)
- {
- $normalized[] = $key.'='.$v;
- }
- }
- else
- {
- $normalized[] = $key.'='.$value;
- }
- }
- }
- return implode('&', $normalized);
- }
-
-
- /**
- * Return the normalised url for signature checks
- */
- function getRequestUrl ()
- {
- $url = $this->uri_parts['scheme'] . '://'
- . $this->uri_parts['user'] . (!empty($this->uri_parts['pass']) ? ':' : '')
- . $this->uri_parts['pass'] . (!empty($this->uri_parts['user']) ? '@' : '')
- . $this->uri_parts['host'];
-
- if ( $this->uri_parts['port']
- && $this->uri_parts['port'] != $this->defaultPortForScheme($this->uri_parts['scheme']))
- {
- $url .= ':'.$this->uri_parts['port'];
- }
- if (!empty($this->uri_parts['path']))
- {
- $url .= $this->uri_parts['path'];
- }
- return $url;
- }
-
-
- /**
- * Get a parameter, value is always urlencoded
- *
- * @param string name
- * @param boolean urldecode set to true to decode the value upon return
- * @return string value false when not found
- */
- function getParam ( $name, $urldecode = false )
- {
- if (isset($this->param[$name]))
- {
- $s = $this->param[$name];
- }
- else if (isset($this->param[$this->urlencode($name)]))
- {
- $s = $this->param[$this->urlencode($name)];
- }
- else
- {
- $s = false;
- }
- if (!empty($s) && $urldecode)
- {
- if (is_array($s))
- {
- $s = array_map(array($this,'urldecode'), $s);
- }
- else
- {
- $s = $this->urldecode($s);
- }
- }
- return $s;
- }
-
- /**
- * Set a parameter
- *
- * @param string name
- * @param string value
- * @param boolean encoded set to true when the values are already encoded
- */
- function setParam ( $name, $value, $encoded = false )
- {
- if (!$encoded)
- {
- $name_encoded = $this->urlencode($name);
- if (is_array($value))
- {
- foreach ($value as $v)
- {
- $this->param[$name_encoded][] = $this->urlencode($v);
- }
- }
- else
- {
- $this->param[$name_encoded] = $this->urlencode($value);
- }
- }
- else
- {
- $this->param[$name] = $value;
- }
- }
-
-
- /**
- * Re-encode all parameters so that they are encoded using RFC3986.
- * Updates the $this->param attribute.
- */
- protected function transcodeParams ()
- {
- $params = $this->param;
- $this->param = array();
-
- foreach ($params as $name=>$value)
- {
- if (is_array($value))
- {
- $this->param[$this->urltranscode($name)] = array_map(array($this,'urltranscode'), $value);
- }
- else
- {
- $this->param[$this->urltranscode($name)] = $this->urltranscode($value);
- }
- }
- }
-
-
-
- /**
- * Return the body of the OAuth request.
- *
- * @return string null when no body
- */
- function getBody ()
- {
- return $this->body;
- }
-
-
- /**
- * Return the body of the OAuth request.
- *
- * @return string null when no body
- */
- function setBody ( $body )
- {
- $this->body = $body;
- }
-
-
- /**
- * Parse the uri into its parts. Fill in the missing parts.
- *
- * @param string $parameters optional extra parameters (from eg the http post)
- */
- protected function parseUri ( $parameters )
- {
- $ps = @parse_url($this->uri);
-
- // Get the current/requested method
- $ps['scheme'] = strtolower($ps['scheme']);
-
- // Get the current/requested host
- if (function_exists('mb_strtolower'))
- $ps['host'] = mb_strtolower($ps['host']);
- else
- $ps['host'] = strtolower($ps['host']);
-
- if (!preg_match('/^[a-z0-9\.\-]+$/', $ps['host']))
- {
- throw new OAuthException2('Unsupported characters in host name');
- }
-
- // Get the port we are talking on
- if (empty($ps['port']))
- {
- $ps['port'] = $this->defaultPortForScheme($ps['scheme']);
- }
-
- if (empty($ps['user']))
- {
- $ps['user'] = '';
- }
- if (empty($ps['pass']))
- {
- $ps['pass'] = '';
- }
- if (empty($ps['path']))
- {
- $ps['path'] = '/';
- }
- if (empty($ps['query']))
- {
- $ps['query'] = '';
- }
- if (empty($ps['fragment']))
- {
- $ps['fragment'] = '';
- }
-
- // Now all is complete - parse all parameters
- foreach (array($ps['query'], $parameters) as $params)
- {
- if (strlen($params) > 0)
- {
- $params = explode('&', $params);
- foreach ($params as $p)
- {
- @list($name, $value) = explode('=', $p, 2);
- if (!strlen($name))
- {
- continue;
- }
-
- if (array_key_exists($name, $this->param))
- {
- if (is_array($this->param[$name]))
- $this->param[$name][] = $value;
- else
- $this->param[$name] = array($this->param[$name], $value);
- }
- else
- {
- $this->param[$name] = $value;
- }
- }
- }
- }
- $this->uri_parts = $ps;
- }
-
-
- /**
- * Return the default port for a scheme
- *
- * @param string scheme
- * @return int
- */
- protected function defaultPortForScheme ( $scheme )
- {
- switch ($scheme)
- {
- case 'http': return 80;
- case 'https': return 443;
- default:
- throw new OAuthException2('Unsupported scheme type, expected http or https, got "'.$scheme.'"');
- break;
- }
- }
-
-
- /**
- * Encode a string according to the RFC3986
- *
- * @param string s
- * @return string
- */
- function urlencode ( $s )
- {
- if ($s === false)
- {
- return $s;
- }
- else
- {
- return str_replace('%7E', '~', rawurlencode($s));
- }
- }
-
- /**
- * Decode a string according to RFC3986.
- * Also correctly decodes RFC1738 urls.
- *
- * @param string s
- * @return string
- */
- function urldecode ( $s )
- {
- if ($s === false)
- {
- return $s;
- }
- else
- {
- return rawurldecode($s);
- }
- }
-
- /**
- * urltranscode - make sure that a value is encoded using RFC3986.
- * We use a basic urldecode() function so that any use of '+' as the
- * encoding of the space character is correctly handled.
- *
- * @param string s
- * @return string
- */
- function urltranscode ( $s )
- {
- if ($s === false)
- {
- return $s;
- }
- else
- {
- //return $this->urlencode(rawurldecode($s));
- return $this->urlencode(urldecode($s));
- }
- }
-
-
- /**
- * Parse the oauth parameters from the request headers
- * Looks for something like:
- *
- * Authorization: OAuth realm="http://photos.example.net/authorize",
- * oauth_consumer_key="dpf43f3p2l4k3l03",
- * oauth_token="nnch734d00sl2jdk",
- * oauth_signature_method="HMAC-SHA1",
- * oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D",
- * oauth_timestamp="1191242096",
- * oauth_nonce="kllo9940pd9333jh",
- * oauth_version="1.0"
- */
- private function parseHeaders ()
- {
-/*
- $this->headers['Authorization'] = 'OAuth realm="http://photos.example.net/authorize",
- oauth_consumer_key="dpf43f3p2l4k3l03",
- oauth_token="nnch734d00sl2jdk",
- oauth_signature_method="HMAC-SHA1",
- oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D",
- oauth_timestamp="1191242096",
- oauth_nonce="kllo9940pd9333jh",
- oauth_version="1.0"';
-*/
- if (isset($this->headers['Authorization']))
- {
- $auth = trim($this->headers['Authorization']);
- if (strncasecmp($auth, 'OAuth', 4) == 0)
- {
- $vs = explode(',', substr($auth, 6));
- foreach ($vs as $v)
- {
- if (strpos($v, '='))
- {
- $v = trim($v);
- list($name,$value) = explode('=', $v, 2);
- if (!empty($value) && $value[0] == '"' && substr($value, -1) == '"')
- {
- $value = substr(substr($value, 1), 0, -1);
- }
-
- if (strcasecmp($name, 'realm') == 0)
- {
- $this->realm = $value;
- }
- else
- {
- $this->param[$name] = $value;
- }
- }
- }
- }
- }
- }
-
-
- /**
- * Fetch the content type of the current request
- *
- * @return string
- */
- private function getRequestContentType ()
- {
- $content_type = 'application/octet-stream';
- if (!empty($_SERVER) && array_key_exists('CONTENT_TYPE', $_SERVER))
- {
- list($content_type) = explode(';', $_SERVER['CONTENT_TYPE']);
- }
- return trim($content_type);
- }
-
-
- /**
- * Get the body of a POST or PUT.
- *
- * Used for fetching the post parameters and to calculate the body signature.
- *
- * @return string null when no body present (or wrong content type for body)
- */
- private function getRequestBody ()
- {
- $body = null;
- if ($this->method == 'POST' || $this->method == 'PUT')
- {
- $body = '';
- $fh = @fopen('php://input', 'r');
- if ($fh)
- {
- while (!feof($fh))
- {
- $s = fread($fh, 1024);
- if (is_string($s))
- {
- $body .= $s;
- }
- }
- fclose($fh);
- }
- }
- return $body;
- }
-
- /**
- * Get the body of a POST with multipart/form-data by Edison tsai on 16:52 2010/09/16
- *
- * Used for fetching the post parameters and to calculate the body signature.
- *
- * @return string null when no body present (or wrong content type for body)
- */
- private function getRequestBodyOfMultipart()
- {
- $body = null;
- if ($this->method == 'POST')
- {
- $body = '';
- if (is_array($_POST) && count($_POST) > 1)
- {
- foreach ($_POST AS $k => $v) {
- $body .= $k . '=' . $this->urlencode($v) . '&';
- } #end foreach
- if(substr($body,-1) == '&')
- {
- $body = substr($body, 0, strlen($body)-1);
- } #end if
- } #end if
- } #end if
-
- return $body;
- }
-
-
- /**
- * Simple function to perform a redirect (GET).
- * Redirects the User-Agent, does not return.
- *
- * @param string uri
- * @param array params parameters, urlencoded
- * @param bool skip protocol check
- * @exception OAuthException2 when redirect uri is illegal
- */
- public function redirect ( $uri, $params, $skip_protocol_check = false )
- {
- if (!empty($params))
- {
- $q = array();
- foreach ($params as $name=>$value)
- {
- $q[] = $name.'='.$value;
- }
- $q_s = implode('&', $q);
-
- if (strpos($uri, '?'))
- {
- $uri .= '&'.$q_s;
- }
- else
- {
- $uri .= '?'.$q_s;
- }
- }
-
- // simple security - multiline location headers can inject all kinds of extras
- $uri = preg_replace('/\s/', '%20', $uri);
-
- if (!$skip_protocol_check) {
- if (strncasecmp($uri, 'http://', 7) && strncasecmp($uri, 'https://', 8))
- {
- if (strpos($uri, '://'))
- {
- throw new OAuthException2('Illegal protocol in redirect uri '.$uri);
- }
- $uri = 'http://'.$uri;
- }
- }
-
- header('HTTP/1.1 302 Found');
- header('Location: '.$uri);
- echo '';
- exit();
- }
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?>
diff --git a/vendor/oauth-php/library/OAuthRequestLogger.php b/vendor/oauth-php/library/OAuthRequestLogger.php
deleted file mode 100644
index 24cd8ba..0000000
--- a/vendor/oauth-php/library/OAuthRequestLogger.php
+++ /dev/null
@@ -1,314 +0,0 @@
-<?php
-
-/**
- * Log OAuth requests
- *
- * @version $Id: OAuthRequestLogger.php 185 2011-02-08 16:11:20Z brunobg@corollarium.com $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Dec 7, 2007 12:22:43 PM
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-class OAuthRequestLogger
-{
- static private $logging = 0;
- static private $enable_logging = null;
- static private $store_log = null;
- static private $note = '';
- static private $user_id = null;
- static private $request_object = null;
- static private $sent = null;
- static private $received = null;
- static private $log = array();
-
- /**
- * Start any logging, checks the system configuration if logging is needed.
- *
- * @param OAuthRequest $request_object
- */
- static function start ( $request_object = null )
- {
- if (defined('OAUTH_LOG_REQUEST'))
- {
- if (is_null(OAuthRequestLogger::$enable_logging))
- {
- OAuthRequestLogger::$enable_logging = true;
- }
- if (is_null(OAuthRequestLogger::$store_log))
- {
- OAuthRequestLogger::$store_log = true;
- }
- }
-
- if (OAuthRequestLogger::$enable_logging && !OAuthRequestLogger::$logging)
- {
- OAuthRequestLogger::$logging = true;
- OAuthRequestLogger::$request_object = $request_object;
- ob_start();
-
- // Make sure we flush our log entry when we stop the request (eg on an exception)
- register_shutdown_function(array('OAuthRequestLogger','flush'));
- }
- }
-
-
- /**
- * Force logging, needed for performing test connects independent from the debugging setting.
- *
- * @param boolean store_log (optional) true to store the log in the db
- */
- static function enableLogging ( $store_log = null )
- {
- OAuthRequestLogger::$enable_logging = true;
- if (!is_null($store_log))
- {
- OAuthRequestLogger::$store_log = $store_log;
- }
- }
-
-
- /**
- * Logs the request to the database, sends any cached output.
- * Also called on shutdown, to make sure we always log the request being handled.
- */
- static function flush ()
- {
- if (OAuthRequestLogger::$logging)
- {
- OAuthRequestLogger::$logging = false;
-
- if (is_null(OAuthRequestLogger::$sent))
- {
- // What has been sent to the user-agent?
- $data = ob_get_contents();
- if (strlen($data) > 0)
- {
- ob_end_flush();
- }
- elseif (ob_get_level())
- {
- ob_end_clean();
- }
- $hs = headers_list();
- $sent = implode("\n", $hs) . "\n\n" . $data;
- }
- else
- {
- // The request we sent
- $sent = OAuthRequestLogger::$sent;
- }
-
- if (is_null(OAuthRequestLogger::$received))
- {
- // Build the request we received
- $hs0 = self::getAllHeaders();
- $hs = array();
- foreach ($hs0 as $h => $v)
- {
- $hs[] = "$h: $v";
- }
-
- $data = '';
- $fh = @fopen('php://input', 'r');
- if ($fh)
- {
- while (!feof($fh))
- {
- $s = fread($fh, 1024);
- if (is_string($s))
- {
- $data .= $s;
- }
- }
- fclose($fh);
- }
- $received = implode("\n", $hs) . "\n\n" . $data;
- }
- else
- {
- // The answer we received
- $received = OAuthRequestLogger::$received;
- }
-
- // The request base string
- if (OAuthRequestLogger::$request_object)
- {
- $base_string = OAuthRequestLogger::$request_object->signatureBaseString();
- }
- else
- {
- $base_string = '';
- }
-
- // Figure out to what keys we want to log this request
- $keys = array();
- if (OAuthRequestLogger::$request_object)
- {
- $consumer_key = OAuthRequestLogger::$request_object->getParam('oauth_consumer_key', true);
- $token = OAuthRequestLogger::$request_object->getParam('oauth_token', true);
-
- switch (get_class(OAuthRequestLogger::$request_object))
- {
- // tokens are access/request tokens by a consumer
- case 'OAuthServer':
- case 'OAuthRequestVerifier':
- $keys['ocr_consumer_key'] = $consumer_key;
- $keys['oct_token'] = $token;
- break;
-
- // tokens are access/request tokens to a server
- case 'OAuthRequester':
- case 'OAuthRequestSigner':
- $keys['osr_consumer_key'] = $consumer_key;
- $keys['ost_token'] = $token;
- break;
- }
- }
-
- // Log the request
- if (OAuthRequestLogger::$store_log)
- {
- $store = OAuthStore::instance();
- $store->addLog($keys, $received, $sent, $base_string, OAuthRequestLogger::$note, OAuthRequestLogger::$user_id);
- }
-
- OAuthRequestLogger::$log[] = array(
- 'keys' => $keys,
- 'received' => $received,
- 'sent' => $sent,
- 'base_string' => $base_string,
- 'note' => OAuthRequestLogger::$note
- );
- }
- }
-
-
- /**
- * Add a note, used by the OAuthException2 to log all exceptions.
- *
- * @param string note
- */
- static function addNote ( $note )
- {
- OAuthRequestLogger::$note .= $note . "\n\n";
- }
-
- /**
- * Set the OAuth request object being used
- *
- * @param OAuthRequest request_object
- */
- static function setRequestObject ( $request_object )
- {
- OAuthRequestLogger::$request_object = $request_object;
- }
-
-
- /**
- * Set the relevant user (defaults to the current user)
- *
- * @param int user_id
- */
- static function setUser ( $user_id )
- {
- OAuthRequestLogger::$user_id = $user_id;
- }
-
-
- /**
- * Set the request we sent
- *
- * @param string request
- */
- static function setSent ( $request )
- {
- OAuthRequestLogger::$sent = $request;
- }
-
- /**
- * Set the reply we received
- *
- * @param string request
- */
- static function setReceived ( $reply )
- {
- OAuthRequestLogger::$received = $reply;
- }
-
-
- /**
- * Get the the log till now
- *
- * @return array
- */
- static function getLog ()
- {
- return OAuthRequestLogger::$log;
- }
-
-
- /**
- * helper to try to sort out headers for people who aren't running apache,
- * or people who are running PHP as FastCGI.
- *
- * @return array of request headers as associative array.
- */
- public static function getAllHeaders() {
- $retarr = array();
- $headers = array();
-
- if (function_exists('apache_request_headers')) {
- $headers = apache_request_headers();
- } else {
- $headers = array_merge($_ENV, $_SERVER);
-
- foreach ($headers as $key => $val) {
- //we need this header
- if (strpos(strtolower($key), 'content-type') !== FALSE)
- continue;
- if (strtoupper(substr($key, 0, 5)) != "HTTP_")
- unset($headers[$key]);
- }
- }
-
- //Normalize this array to Cased-Like-This structure.
- foreach ($headers AS $key => $value) {
- $key = preg_replace('/^HTTP_/i', '', $key);
- $key = str_replace(
- " ",
- "-",
- ucwords(strtolower(str_replace(array("-", "_"), " ", $key)))
- );
- $retarr[$key] = $value;
- }
- ksort($retarr);
-
- return $retarr;
- }
-}
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/OAuthRequestSigner.php b/vendor/oauth-php/library/OAuthRequestSigner.php
deleted file mode 100644
index 15c0fd8..0000000
--- a/vendor/oauth-php/library/OAuthRequestSigner.php
+++ /dev/null
@@ -1,215 +0,0 @@
-<?php
-
-/**
- * Sign requests before performing the request.
- *
- * @version $Id: OAuthRequestSigner.php 174 2010-11-24 15:15:41Z brunobg@corollarium.com $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Nov 16, 2007 4:02:49 PM
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-require_once dirname(__FILE__) . '/OAuthStore.php';
-require_once dirname(__FILE__) . '/OAuthRequest.php';
-
-
-class OAuthRequestSigner extends OAuthRequest
-{
- protected $request;
- protected $store;
- protected $usr_id = 0;
- private $signed = false;
-
-
- /**
- * Construct the request to be signed. Parses or appends the parameters in the params url.
- * When you supply an params array, then the params should not be urlencoded.
- * When you supply a string, then it is assumed it is of the type application/x-www-form-urlencoded
- *
- * @param string request url
- * @param string method PUT, GET, POST etc.
- * @param mixed params string (for urlencoded data, or array with name/value pairs)
- * @param string body optional body for PUT and/or POST requests
- */
- function __construct ( $request, $method = null, $params = null, $body = null )
- {
- $this->store = OAuthStore::instance();
-
- if (is_string($params))
- {
- parent::__construct($request, $method, $params);
- }
- else
- {
- parent::__construct($request, $method);
- if (is_array($params))
- {
- foreach ($params as $name => $value)
- {
- $this->setParam($name, $value);
- }
- }
- }
-
- // With put/ post we might have a body (not for application/x-www-form-urlencoded requests)
- if (strcasecmp($method, 'PUT') == 0 || strcasecmp($method, 'POST') == 0)
- {
- $this->setBody($body);
- }
- }
-
-
- /**
- * Reset the 'signed' flag, so that any changes in the parameters force a recalculation
- * of the signature.
- */
- function setUnsigned ()
- {
- $this->signed = false;
- }
-
-
- /**
- * Sign our message in the way the server understands.
- * Set the needed oauth_xxxx parameters.
- *
- * @param int usr_id (optional) user that wants to sign this request
- * @param array secrets secrets used for signing, when empty then secrets will be fetched from the token registry
- * @param string name name of the token to be used for signing
- * @exception OAuthException2 when there is no oauth relation with the server
- * @exception OAuthException2 when we don't support the signing methods of the server
- */
- function sign ( $usr_id = 0, $secrets = null, $name = '', $token_type = null)
- {
- $url = $this->getRequestUrl();
- if (empty($secrets))
- {
- // get the access tokens for the site (on an user by user basis)
- $secrets = $this->store->getSecretsForSignature($url, $usr_id, $name);
- }
- if (empty($secrets))
- {
- throw new OAuthException2('No OAuth relation with the server for at "'.$url.'"');
- }
-
- $signature_method = $this->selectSignatureMethod($secrets['signature_methods']);
-
- $token = isset($secrets['token']) ? $secrets['token'] : '';
- $token_secret = isset($secrets['token_secret']) ? $secrets['token_secret'] : '';
-
- if (!$token) {
- $token = $this->getParam('oauth_token');
- }
-
- $this->setParam('oauth_signature_method',$signature_method);
- $this->setParam('oauth_signature', '');
- $this->setParam('oauth_nonce', !empty($secrets['nonce']) ? $secrets['nonce'] : uniqid(''));
- $this->setParam('oauth_timestamp', !empty($secrets['timestamp']) ? $secrets['timestamp'] : time());
- if ($token_type != 'requestToken')
- $this->setParam('oauth_token', $token);
- $this->setParam('oauth_consumer_key', $secrets['consumer_key']);
- $this->setParam('oauth_version', '1.0');
-
- $body = $this->getBody();
- if (!is_null($body))
- {
- // We also need to sign the body, use the default signature method
- $body_signature = $this->calculateDataSignature($body, $secrets['consumer_secret'], $token_secret, $signature_method);
- $this->setParam('xoauth_body_signature', $body_signature, true);
- }
-
- $signature = $this->calculateSignature($secrets['consumer_secret'], $token_secret, $token_type);
- $this->setParam('oauth_signature', $signature, true);
- // $this->setParam('oauth_signature', urldecode($signature), true);
-
- $this->signed = true;
- $this->usr_id = $usr_id;
- }
-
-
- /**
- * Builds the Authorization header for the request.
- * Adds all oauth_ and xoauth_ parameters to the Authorization header.
- *
- * @return string
- */
- function getAuthorizationHeader ()
- {
- if (!$this->signed)
- {
- $this->sign($this->usr_id);
- }
- $h = array();
- $h[] = 'Authorization: OAuth realm=""';
- foreach ($this->param as $name => $value)
- {
- if (strncmp($name, 'oauth_', 6) == 0 || strncmp($name, 'xoauth_', 7) == 0)
- {
- $h[] = $name.'="'.$value.'"';
- }
- }
- $hs = implode(', ', $h);
- return $hs;
- }
-
-
- /**
- * Builds the application/x-www-form-urlencoded parameter string. Can be appended as
- * the query part to a GET or inside the request body for a POST.
- *
- * @param boolean oauth_as_header (optional) set to false to include oauth parameters
- * @return string
- */
- function getQueryString ( $oauth_as_header = true )
- {
- $parms = array();
- foreach ($this->param as $name => $value)
- {
- if ( !$oauth_as_header
- || (strncmp($name, 'oauth_', 6) != 0 && strncmp($name, 'xoauth_', 7) != 0))
- {
- if (is_array($value))
- {
- foreach ($value as $v)
- {
- $parms[] = $name.'='.$v;
- }
- }
- else
- {
- $parms[] = $name.'='.$value;
- }
- }
- }
- return implode('&', $parms);
- }
-
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/OAuthRequestVerifier.php b/vendor/oauth-php/library/OAuthRequestVerifier.php
deleted file mode 100644
index a5def75..0000000
--- a/vendor/oauth-php/library/OAuthRequestVerifier.php
+++ /dev/null
@@ -1,306 +0,0 @@
-<?php
-
-/**
- * Verify the current request. Checks if signed and if the signature is correct.
- * When correct then also figures out on behalf of which user this request is being made.
- *
- * @version $Id: OAuthRequestVerifier.php 155 2010-09-10 18:38:33Z brunobg@corollarium.com $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Nov 16, 2007 4:35:03 PM
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__) . '/OAuthStore.php';
-require_once dirname(__FILE__) . '/OAuthRequest.php';
-
-
-class OAuthRequestVerifier extends OAuthRequest
-{
- private $request;
- private $store;
- private $accepted_signatures = null;
-
- /**
- * Construct the request to be verified
- *
- * @param string request
- * @param string method
- * @param array params The request parameters
- */
- function __construct ( $uri = null, $method = null, $params = null )
- {
- if ($params) {
- $encodedParams = array();
- foreach ($params as $key => $value) {
- if (preg_match("/^oauth_/", $key)) {
- continue;
- }
- $encodedParams[rawurlencode($key)] = rawurlencode($value);
- }
- $this->param = array_merge($this->param, $encodedParams);
- }
-
- $this->store = OAuthStore::instance();
- parent::__construct($uri, $method);
-
- OAuthRequestLogger::start($this);
- }
-
-
- /**
- * See if the current request is signed with OAuth
- *
- * @return boolean
- */
- static public function requestIsSigned ()
- {
- if (isset($_REQUEST['oauth_signature']))
- {
- $signed = true;
- }
- else
- {
- $hs = OAuthRequestLogger::getAllHeaders();
- if (isset($hs['Authorization']) && strpos($hs['Authorization'], 'oauth_signature') !== false)
- {
- $signed = true;
- }
- else
- {
- $signed = false;
- }
- }
- return $signed;
- }
-
-
- /**
- * Verify the request if it seemed to be signed.
- *
- * @param string token_type the kind of token needed, defaults to 'access'
- * @exception OAuthException2 thrown when the request did not verify
- * @return boolean true when signed, false when not signed
- */
- public function verifyIfSigned ( $token_type = 'access' )
- {
- if ($this->getParam('oauth_consumer_key'))
- {
- OAuthRequestLogger::start($this);
- $this->verify($token_type);
- $signed = true;
- OAuthRequestLogger::flush();
- }
- else
- {
- $signed = false;
- }
- return $signed;
- }
-
-
-
- /**
- * Verify the request
- *
- * @param string token_type the kind of token needed, defaults to 'access' (false, 'access', 'request')
- * @exception OAuthException2 thrown when the request did not verify
- * @return int user_id associated with token (false when no user associated)
- */
- public function verify ( $token_type = 'access' )
- {
- $retval = $this->verifyExtended($token_type);
- return $retval['user_id'];
- }
-
-
- /**
- * Verify the request
- *
- * @param string token_type the kind of token needed, defaults to 'access' (false, 'access', 'request')
- * @exception OAuthException2 thrown when the request did not verify
- * @return array ('user_id' => associated with token (false when no user associated),
- * 'consumer_key' => the associated consumer_key)
- *
- */
- public function verifyExtended ( $token_type = 'access' )
- {
- $consumer_key = $this->getParam('oauth_consumer_key');
- $token = $this->getParam('oauth_token');
- $user_id = false;
- $secrets = array();
-
- if ($consumer_key && ($token_type === false || $token))
- {
- $secrets = $this->store->getSecretsForVerify( $this->urldecode($consumer_key),
- $this->urldecode($token),
- $token_type);
-
- $this->store->checkServerNonce( $this->urldecode($consumer_key),
- $this->urldecode($token),
- $this->getParam('oauth_timestamp', true),
- $this->getParam('oauth_nonce', true));
-
- $oauth_sig = $this->getParam('oauth_signature');
- if (empty($oauth_sig))
- {
- throw new OAuthException2('Verification of signature failed (no oauth_signature in request).');
- }
-
- try
- {
- $this->verifySignature($secrets['consumer_secret'], $secrets['token_secret'], $token_type);
- }
- catch (OAuthException2 $e)
- {
- throw new OAuthException2('Verification of signature failed (signature base string was "'.$this->signatureBaseString().'").'
- . " with " . print_r(array($secrets['consumer_secret'], $secrets['token_secret'], $token_type), true));
- }
-
- // Check the optional body signature
- if ($this->getParam('xoauth_body_signature'))
- {
- $method = $this->getParam('xoauth_body_signature_method');
- if (empty($method))
- {
- $method = $this->getParam('oauth_signature_method');
- }
-
- try
- {
- $this->verifyDataSignature($this->getBody(), $secrets['consumer_secret'], $secrets['token_secret'], $method, $this->getParam('xoauth_body_signature'));
- }
- catch (OAuthException2 $e)
- {
- throw new OAuthException2('Verification of body signature failed.');
- }
- }
-
- // All ok - fetch the user associated with this request
- if (isset($secrets['user_id']))
- {
- $user_id = $secrets['user_id'];
- }
-
- // Check if the consumer wants us to reset the ttl of this token
- $ttl = $this->getParam('xoauth_token_ttl', true);
- if (is_numeric($ttl))
- {
- $this->store->setConsumerAccessTokenTtl($this->urldecode($token), $ttl);
- }
- }
- else
- {
- throw new OAuthException2('Can\'t verify request, missing oauth_consumer_key or oauth_token');
- }
- return array('user_id' => $user_id, 'consumer_key' => $consumer_key, 'osr_id' => $secrets['osr_id']);
- }
-
-
-
- /**
- * Verify the signature of the request, using the method in oauth_signature_method.
- * The signature is returned encoded in the form as used in the url. So the base64 and
- * urlencoding has been done.
- *
- * @param string consumer_secret
- * @param string token_secret
- * @exception OAuthException2 thrown when the signature method is unknown
- * @exception OAuthException2 when not all parts available
- * @exception OAuthException2 when signature does not match
- */
- public function verifySignature ( $consumer_secret, $token_secret, $token_type = 'access' )
- {
- $required = array(
- 'oauth_consumer_key',
- 'oauth_signature_method',
- 'oauth_timestamp',
- 'oauth_nonce',
- 'oauth_signature'
- );
-
- if ($token_type !== false)
- {
- $required[] = 'oauth_token';
- }
-
- foreach ($required as $req)
- {
- if (!isset($this->param[$req]))
- {
- throw new OAuthException2('Can\'t verify request signature, missing parameter "'.$req.'"');
- }
- }
-
- $this->checks();
-
- $base = $this->signatureBaseString();
- $this->verifyDataSignature($base, $consumer_secret, $token_secret, $this->param['oauth_signature_method'], $this->param['oauth_signature']);
- }
-
-
-
- /**
- * Verify the signature of a string.
- *
- * @param string data
- * @param string consumer_secret
- * @param string token_secret
- * @param string signature_method
- * @param string signature
- * @exception OAuthException2 thrown when the signature method is unknown
- * @exception OAuthException2 when signature does not match
- */
- public function verifyDataSignature ( $data, $consumer_secret, $token_secret, $signature_method, $signature )
- {
- if (is_null($data))
- {
- $data = '';
- }
-
- $sig = $this->getSignatureMethod($signature_method);
- if (!$sig->verify($this, $data, $consumer_secret, $token_secret, $signature))
- {
- throw new OAuthException2('Signature verification failed ('.$signature_method.')');
- }
- }
-
- /**
- *
- * @param array $accepted The array of accepted signature methods, or if null is passed
- * all supported methods are accepted and there is no filtering.
- *
- */
- public function setAcceptedSignatureMethods($accepted = null) {
- if (is_array($accepted))
- $this->accepted_signatures = $accepted;
- else if ($accepted == null)
- $this->accepted_signatures = null;
- }
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/OAuthRequester.php b/vendor/oauth-php/library/OAuthRequester.php
deleted file mode 100644
index dde9a99..0000000
--- a/vendor/oauth-php/library/OAuthRequester.php
+++ /dev/null
@@ -1,543 +0,0 @@
-<?php
-
-/**
- * Perform a signed OAuth request with a GET, POST, PUT or DELETE operation.
- *
- * @version $Id: OAuthRequester.php 191 2011-03-23 17:50:55Z scherpenisse $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Nov 20, 2007 1:41:38 PM
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__) . '/OAuthRequestSigner.php';
-require_once dirname(__FILE__) . '/body/OAuthBodyContentDisposition.php';
-
-
-class OAuthRequester extends OAuthRequestSigner
-{
- protected $files;
-
- /**
- * Construct a new request signer. Perform the request with the doRequest() method below.
- *
- * A request can have either one file or a body, not both.
- *
- * The files array consists of arrays:
- * - file the filename/path containing the data for the POST/PUT
- * - data data for the file, omit when you have a file
- * - mime content-type of the file
- * - filename filename for content disposition header
- *
- * When OAuth (and PHP) can support multipart/form-data then we can handle more than one file.
- * For now max one file, with all the params encoded in the query string.
- *
- * @param string request
- * @param string method http method. GET, PUT, POST etc. Defaults to 'GET'.
- * @param array params name=>value array with request parameters
- * @param string body optional body to send
- * @param array files optional files to send (max 1 till OAuth support multipart/form-data posts)
- */
- function __construct ( $request, $method = 'GET', $params = null, $body = null, $files = null )
- {
- parent::__construct($request, $method, $params, $body);
-
- // When there are files, then we can construct a POST with a single file
- if (!empty($files))
- {
- $empty = true;
- foreach ($files as $f)
- {
- $empty = $empty && empty($f['file']) && !isset($f['data']);
- }
-
- if (!$empty)
- {
- if (!is_null($body))
- {
- throw new OAuthException2('When sending files, you can\'t send a body as well.');
- }
- $this->files = $files;
- }
- }
- }
-
-
- /**
- * Perform the request, returns the response code, headers and body.
- *
- * @param int usr_id optional user id for which we make the request
- * @param array curl_options optional extra options for curl request
- * @param array options options like
- * - name Named tokens, unique per user/consumer key
- * - token_ttl Time to live
- * - server_uri The server uri
- * - boolean oauth_as_header set to false to include oauth parameters in query string. Default true (includes on headers)
- * @exception OAuthException2 when authentication not accepted
- * @exception OAuthException2 when signing was not possible
- * @return array (code=>int, headers=>array(), body=>string)
- */
- function doRequest ( $usr_id = 0, $curl_options = array(), $options = array() )
- {
- $name = isset($options['name']) ? $options['name'] : '';
- if (isset($options['token_ttl']))
- {
- $this->setParam('xoauth_token_ttl', intval($options['token_ttl']));
- }
-
- if (!empty($this->files))
- {
- // At the moment OAuth does not support multipart/form-data, so try to encode
- // the supplied file (or data) as the request body and add a content-disposition header.
- list($extra_headers, $body) = OAuthBodyContentDisposition::encodeBody($this->files);
- $this->setBody($body);
- $curl_options = $this->prepareCurlOptions($curl_options, $extra_headers);
- }
- $this->sign($usr_id, null, $name);
- $text = $this->curl_raw($curl_options, (isset($options['oauth_as_header']) ? $options['oauth_as_header'] : true));
- $result = $this->curl_parse($text);
- if ($result['code'] >= 400)
- {
- throw new OAuthException2('Request failed with code ' . $result['code'] . ': ' . $result['body']);
- }
-
- // Record the token time to live for this server access token, immediate delete iff ttl <= 0
- // Only done on a succesful request.
- $token_ttl = $this->getParam('xoauth_token_ttl', false);
- if (is_numeric($token_ttl))
- {
- $this->store->setServerTokenTtl($this->getParam('oauth_consumer_key',true), $this->getParam('oauth_token',true),
- $token_ttl, (isset($options['server_uri']) ? $options['server_uri'] : NULL));
- }
-
- return $result;
- }
-
-
- /**
- * Request a request token from the site belonging to consumer_key
- *
- * @param string consumer_key
- * @param int usr_id
- * @param array params (optional) extra arguments for when requesting the request token
- * @param string method (optional) change the method of the request, defaults to POST (as it should be)
- * @param array options (optional) options:
- * - name Named tokens, unique per user/consumer key
- * - token_ttl Time to live
- * - server_uri The server uri
- * - boolean oauth_as_header set to false to include oauth parameters in query string. Default true (includes on headers)
- * @param array curl_options optional extra options for curl request
- * @exception OAuthException2 when no key could be fetched
- * @exception OAuthException2 when no server with consumer_key registered
- * @return array (authorize_uri, token)
- */
- static function requestRequestToken ( $consumer_key, $usr_id, $params = null, $method = 'POST', $options = array(), $curl_options = array() )
- {
- OAuthRequestLogger::start();
-
- if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
- {
- $params['xoauth_token_ttl'] = intval($options['token_ttl']);
- }
-
- $store = OAuthStore::instance();
- $r = $store->getServer($consumer_key, $usr_id);
- $uri = $r['request_token_uri'];
-
- $oauth = new OAuthRequester($uri, $method, $params);
- $oauth->sign($usr_id, $r, '', 'requestToken');
- $text = $oauth->curl_raw($curl_options, (isset($options['oauth_as_header']) ? $options['oauth_as_header'] : true));
-
- if (empty($text))
- {
- throw new OAuthException2('No answer from the server "'.$uri.'" while requesting a request token');
- }
- $data = $oauth->curl_parse($text);
- if ($data['code'] != 200)
- {
- throw new OAuthException2('Unexpected result from the server "'.$uri.'" ('.$data['code'].') while requesting a request token:' . $data['body']);
- }
- $token = array();
- $params = explode('&', $data['body']);
- foreach ($params as $p)
- {
- @list($name, $value) = explode('=', $p, 2);
- $token[$name] = $oauth->urldecode($value);
- }
-
- if (!empty($token['oauth_token']) && !empty($token['oauth_token_secret']))
- {
- $opts = array();
- if (isset($options['name']))
- {
- $opts['name'] = $options['name'];
- }
- if (isset($token['xoauth_token_ttl']))
- {
- $opts['token_ttl'] = $token['xoauth_token_ttl'];
- }
- if (isset($options['server_uri']))
- {
- $opts['server_uri'] = $options['server_uri'];
- }
- $store->addServerToken($consumer_key, 'request', $token['oauth_token'], $token['oauth_token_secret'], $usr_id, $opts);
- }
- else
- {
- throw new OAuthException2('The server "'.$uri.'" did not return the oauth_token or the oauth_token_secret');
- }
-
- OAuthRequestLogger::flush();
-
- // Now we can direct a browser to the authorize_uri
- return array(
- 'authorize_uri' => $r['authorize_uri'],
- 'token' => $token['oauth_token']
- );
- }
-
-
- /**
- * Request an access token from the site belonging to consumer_key.
- * Before this we got an request token, now we want to exchange it for
- * an access token.
- *
- * @param string consumer_key
- * @param string token
- * @param int usr_id user requesting the access token
- * @param string method (optional) change the method of the request, defaults to POST (as it should be)
- * @param array options (optional) options:
- * - name Named tokens, unique per user/consumer key
- * - token_ttl Time to live
- * - server_uri The server uri
- * - boolean oauth_as_header set to false to include oauth parameters in query string. Default true (includes on headers)
- * @param array curl_options optional extra options for curl request
- *
- * @exception OAuthException2 when no key could be fetched
- * @exception OAuthException2 when no server with consumer_key registered
- */
- static function requestAccessToken ( $consumer_key, $token, $usr_id, $method = 'POST', $options = array(), $curl_options = array())
- {
- OAuthRequestLogger::start();
-
- $store = OAuthStore::instance();
- $r = $store->getServerTokenSecrets($consumer_key, $token, 'request', $usr_id);
- $uri = $r['access_token_uri'];
- $token_name = $r['token_name'];
-
- // Delete the server request token, this one was for one use only
- $store->deleteServerToken($consumer_key, $r['token'], 0, true);
-
- // Try to exchange our request token for an access token
- $oauth = new OAuthRequester($uri, $method);
-
- if (isset($options['oauth_verifier']))
- {
- $oauth->setParam('oauth_verifier', $options['oauth_verifier']);
- }
- if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
- {
- $oauth->setParam('xoauth_token_ttl', intval($options['token_ttl']));
- }
-
- OAuthRequestLogger::setRequestObject($oauth);
-
- $oauth->sign($usr_id, $r, '', 'accessToken');
- $text = $oauth->curl_raw($curl_options, (isset($options['oauth_as_header']) ? $options['oauth_as_header'] : true));
- if (empty($text))
- {
- throw new OAuthException2('No answer from the server "'.$uri.'" while requesting an access token');
- }
- $data = $oauth->curl_parse($text);
-
- if ($data['code'] != 200)
- {
- throw new OAuthException2('Unexpected result from the server "'.$uri.'" ('.$data['code'].') while requesting an access token');
- }
-
- $token = array();
- $params = explode('&', $data['body']);
- foreach ($params as $p)
- {
- @list($name, $value) = explode('=', $p, 2);
- $token[$oauth->urldecode($name)] = $oauth->urldecode($value);
- }
-
- if (!empty($token['oauth_token']) && !empty($token['oauth_token_secret']))
- {
- $opts = array();
- $opts['name'] = $token_name;
- if (isset($token['xoauth_token_ttl']))
- {
- $opts['token_ttl'] = $token['xoauth_token_ttl'];
- }
- if (isset($options['server_uri']))
- {
- $opts['server_uri'] = $options['server_uri'];
- }
- $store->addServerToken($consumer_key, 'access', $token['oauth_token'], $token['oauth_token_secret'], $usr_id, $opts);
- }
- else
- {
- throw new OAuthException2('The server "'.$uri.'" did not return the oauth_token or the oauth_token_secret');
- }
-
- OAuthRequestLogger::flush();
- }
-
-
-
- /**
- * Open and close a curl session passing all the options to the curl libs
- *
- * @param array opts the curl options.
- * @param boolean oauth_as_header (optional) set to false to include oauth parameters in query string
- * @exception OAuthException2 when temporary file for PUT operation could not be created
- * @return string the result of the curl action
- */
- protected function curl_raw ( $opts = array(), $oauth_as_header = true )
- {
- if (isset($opts[CURLOPT_HTTPHEADER]))
- {
- $header = $opts[CURLOPT_HTTPHEADER];
- }
- else
- {
- $header = array();
- }
-
- $ch = curl_init();
- $method = $this->getMethod();
- $url = $this->getRequestUrl();
- $header[] = $this->getAuthorizationHeader();
- $query = $this->getQueryString($oauth_as_header);
- $body = $this->getBody();
-
- $has_content_type = false;
- foreach ($header as $h)
- {
- if (strncasecmp($h, 'Content-Type:', 13) == 0)
- {
- $has_content_type = true;
- }
- }
-
- if (!is_null($body))
- {
- if ($method == 'TRACE')
- {
- throw new OAuthException2('A body can not be sent with a TRACE operation');
- }
-
- // PUT and POST allow a request body
- if (!empty($query))
- {
- $url .= '?'.$query;
- }
-
- // Make sure that the content type of the request is ok
- if (!$has_content_type)
- {
- $header[] = 'Content-Type: application/octet-stream';
- $has_content_type = true;
- }
-
- // When PUTting, we need to use an intermediate file (because of the curl implementation)
- if ($method == 'PUT')
- {
- /*
- if (version_compare(phpversion(), '5.2.0') >= 0)
- {
- // Use the data wrapper to create the file expected by the put method
- $put_file = fopen('data://application/octet-stream;base64,'.base64_encode($body));
- }
- */
-
- $put_file = @tmpfile();
- if (!$put_file)
- {
- throw new OAuthException2('Could not create tmpfile for PUT operation');
- }
- fwrite($put_file, $body);
- fseek($put_file, 0);
-
- curl_setopt($ch, CURLOPT_PUT, true);
- curl_setopt($ch, CURLOPT_INFILE, $put_file);
- curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body));
- }
- else
- {
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
- }
- }
- else
- {
- // a 'normal' request, no body to be send
- if ($method == 'POST')
- {
- if (!$has_content_type)
- {
- $header[] = 'Content-Type: application/x-www-form-urlencoded';
- $has_content_type = true;
- }
-
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
- }
- else
- {
- if (!empty($query))
- {
- $url .= '?'.$query;
- }
- if ($method != 'GET')
- {
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
- }
- }
- }
-
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- curl_setopt($ch, CURLOPT_USERAGENT, 'anyMeta/OAuth 1.0 - ($LastChangedRevision: 191 $)');
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HEADER, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, 30);
-
- foreach ($opts as $k => $v)
- {
- if ($k != CURLOPT_HTTPHEADER)
- {
- curl_setopt($ch, $k, $v);
- }
- }
-
- $txt = curl_exec($ch);
- if ($txt === false) {
- $error = curl_error($ch);
- curl_close($ch);
- throw new OAuthException2('CURL error: ' . $error);
- }
- curl_close($ch);
-
- if (!empty($put_file))
- {
- fclose($put_file);
- }
-
- // Tell the logger what we requested and what we received back
- $data = $method . " $url\n".implode("\n",$header);
- if (is_string($body))
- {
- $data .= "\n\n".$body;
- }
- else if ($method == 'POST')
- {
- $data .= "\n\n".$query;
- }
-
- OAuthRequestLogger::setSent($data, $body);
- OAuthRequestLogger::setReceived($txt);
-
- return $txt;
- }
-
-
- /**
- * Parse an http response
- *
- * @param string response the http text to parse
- * @return array (code=>http-code, headers=>http-headers, body=>body)
- */
- protected function curl_parse ( $response )
- {
- if (empty($response))
- {
- return array();
- }
-
- @list($headers,$body) = explode("\r\n\r\n",$response,2);
- $lines = explode("\r\n",$headers);
-
- if (preg_match('@^HTTP/[0-9]\.[0-9] +100@', $lines[0]))
- {
- /* HTTP/1.x 100 Continue
- * the real data is on the next line
- */
- @list($headers,$body) = explode("\r\n\r\n",$body,2);
- $lines = explode("\r\n",$headers);
- }
-
- // first line of headers is the HTTP response code
- $http_line = array_shift($lines);
- if (preg_match('@^HTTP/[0-9]\.[0-9] +([0-9]{3})@', $http_line, $matches))
- {
- $code = $matches[1];
- }
-
- // put the rest of the headers in an array
- $headers = array();
- foreach ($lines as $l)
- {
- list($k, $v) = explode(': ', $l, 2);
- $headers[strtolower($k)] = $v;
- }
-
- return array( 'code' => $code, 'headers' => $headers, 'body' => $body);
- }
-
-
- /**
- * Mix the given headers into the headers that were given to curl
- *
- * @param array curl_options
- * @param array extra_headers
- * @return array new curl options
- */
- protected function prepareCurlOptions ( $curl_options, $extra_headers )
- {
- $hs = array();
- if (!empty($curl_options[CURLOPT_HTTPHEADER]) && is_array($curl_options[CURLOPT_HTTPHEADER]))
- {
- foreach ($curl_options[CURLOPT_HTTPHEADER] as $h)
- {
- list($opt, $val) = explode(':', $h, 2);
- $opt = str_replace(' ', '-', ucwords(str_replace('-', ' ', $opt)));
- $hs[$opt] = $val;
- }
- }
-
- $curl_options[CURLOPT_HTTPHEADER] = array();
- $hs = array_merge($hs, $extra_headers);
- foreach ($hs as $h => $v)
- {
- $curl_options[CURLOPT_HTTPHEADER][] = "$h: $v";
- }
- return $curl_options;
- }
-}
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/OAuthServer.php b/vendor/oauth-php/library/OAuthServer.php
deleted file mode 100644
index 878796a..0000000
--- a/vendor/oauth-php/library/OAuthServer.php
+++ /dev/null
@@ -1,333 +0,0 @@
-<?php
-
-/**
- * Server layer over the OAuthRequest handler
- *
- * @version $Id: OAuthServer.php 154 2010-08-31 18:04:41Z brunobg@corollarium.com $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Nov 27, 2007 12:36:38 PM
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once 'OAuthRequestVerifier.php';
-require_once 'OAuthSession.php';
-
-class OAuthServer extends OAuthRequestVerifier
-{
- protected $session;
-
- protected $allowed_uri_schemes = array(
- 'http',
- 'https'
- );
-
- protected $disallowed_uri_schemes = array(
- 'file',
- 'callto',
- 'mailto'
- );
-
- /**
- * Construct the request to be verified
- *
- * @param string request
- * @param string method
- * @param array params The request parameters
- * @param string store The session storage class.
- * @param array store_options The session storage class parameters.
- * @param array options Extra options:
- * - allowed_uri_schemes: list of allowed uri schemes.
- * - disallowed_uri_schemes: list of unallowed uri schemes.
- *
- * e.g. Allow only http and https
- * $options = array(
- * 'allowed_uri_schemes' => array('http', 'https'),
- * 'disallowed_uri_schemes' => array()
- * );
- *
- * e.g. Disallow callto, mailto and file, allow everything else
- * $options = array(
- * 'allowed_uri_schemes' => array(),
- * 'disallowed_uri_schemes' => array('callto', 'mailto', 'file')
- * );
- *
- * e.g. Allow everything
- * $options = array(
- * 'allowed_uri_schemes' => array(),
- * 'disallowed_uri_schemes' => array()
- * );
- *
- */
- function __construct ( $uri = null, $method = null, $params = null, $store = 'SESSION',
- $store_options = array(), $options = array() )
- {
- parent::__construct($uri, $method, $params);
- $this->session = OAuthSession::instance($store, $store_options);
-
- if (array_key_exists('allowed_uri_schemes', $options) && is_array($options['allowed_uri_schemes'])) {
- $this->allowed_uri_schemes = $options['allowed_uri_schemes'];
- }
- if (array_key_exists('disallowed_uri_schemes', $options) && is_array($options['disallowed_uri_schemes'])) {
- $this->disallowed_uri_schemes = $options['disallowed_uri_schemes'];
- }
- }
-
- /**
- * Handle the request_token request.
- * Returns the new request token and request token secret.
- *
- * TODO: add correct result code to exception
- *
- * @return string returned request token, false on an error
- */
- public function requestToken ()
- {
- OAuthRequestLogger::start($this);
- try
- {
- $this->verify(false);
-
- $options = array();
- $ttl = $this->getParam('xoauth_token_ttl', false);
- if ($ttl)
- {
- $options['token_ttl'] = $ttl;
- }
-
- // 1.0a Compatibility : associate callback url to the request token
- $cbUrl = $this->getParam('oauth_callback', true);
- if ($cbUrl) {
- $options['oauth_callback'] = $cbUrl;
- }
-
- // Create a request token
- $store = OAuthStore::instance();
- $token = $store->addConsumerRequestToken($this->getParam('oauth_consumer_key', true), $options);
- $result = 'oauth_callback_confirmed=1&oauth_token='.$this->urlencode($token['token'])
- .'&oauth_token_secret='.$this->urlencode($token['token_secret']);
-
- if (!empty($token['token_ttl']))
- {
- $result .= '&xoauth_token_ttl='.$this->urlencode($token['token_ttl']);
- }
-
- $request_token = $token['token'];
-
- header('HTTP/1.1 200 OK');
- header('Content-Length: '.strlen($result));
- header('Content-Type: application/x-www-form-urlencoded');
-
- echo $result;
- }
- catch (OAuthException2 $e)
- {
- $request_token = false;
-
- header('HTTP/1.1 401 Unauthorized');
- header('Content-Type: text/plain');
-
- echo "OAuth Verification Failed: " . $e->getMessage();
- }
-
- OAuthRequestLogger::flush();
- return $request_token;
- }
-
-
- /**
- * Verify the start of an authorization request. Verifies if the request token is valid.
- * Next step is the method authorizeFinish()
- *
- * Nota bene: this stores the current token, consumer key and callback in the _SESSION
- *
- * @exception OAuthException2 thrown when not a valid request
- * @return array token description
- */
- public function authorizeVerify ()
- {
- OAuthRequestLogger::start($this);
-
- $store = OAuthStore::instance();
- $token = $this->getParam('oauth_token', true);
- $rs = $store->getConsumerRequestToken($token);
- if (empty($rs))
- {
- throw new OAuthException2('Unknown request token "'.$token.'"');
- }
-
- // We need to remember the callback
- $verify_oauth_token = $this->session->get('verify_oauth_token');
- if ( empty($verify_oauth_token)
- || strcmp($verify_oauth_token, $rs['token']))
- {
- $this->session->set('verify_oauth_token', $rs['token']);
- $this->session->set('verify_oauth_consumer_key', $rs['consumer_key']);
- $cb = $this->getParam('oauth_callback', true);
- if ($cb)
- $this->session->set('verify_oauth_callback', $cb);
- else
- $this->session->set('verify_oauth_callback', $rs['callback_url']);
- }
- OAuthRequestLogger::flush();
- return $rs;
- }
-
-
- /**
- * Overrule this method when you want to display a nice page when
- * the authorization is finished. This function does not know if the authorization was
- * succesfull, you need to check the token in the database.
- *
- * @param boolean authorized if the current token (oauth_token param) is authorized or not
- * @param int user_id user for which the token was authorized (or denied)
- * @return string verifier For 1.0a Compatibility
- */
- public function authorizeFinish ( $authorized, $user_id )
- {
- OAuthRequestLogger::start($this);
-
- $token = $this->getParam('oauth_token', true);
- $verifier = null;
- if ($this->session->get('verify_oauth_token') == $token)
- {
- // Flag the token as authorized, or remove the token when not authorized
- $store = OAuthStore::instance();
-
- // Fetch the referrer host from the oauth callback parameter
- $referrer_host = '';
- $oauth_callback = false;
- $verify_oauth_callback = $this->session->get('verify_oauth_callback');
- if (!empty($verify_oauth_callback) && $verify_oauth_callback != 'oob') // OUT OF BAND
- {
- $oauth_callback = $this->session->get('verify_oauth_callback');
- $ps = parse_url($oauth_callback);
- if (isset($ps['host']))
- {
- $referrer_host = $ps['host'];
- }
- }
-
- if ($authorized)
- {
- OAuthRequestLogger::addNote('Authorized token "'.$token.'" for user '.$user_id.' with referrer "'.$referrer_host.'"');
- // 1.0a Compatibility : create a verifier code
- $verifier = $store->authorizeConsumerRequestToken($token, $user_id, $referrer_host);
- }
- else
- {
- OAuthRequestLogger::addNote('Authorization rejected for token "'.$token.'" for user '.$user_id."\nToken has been deleted");
- $store->deleteConsumerRequestToken($token);
- }
-
- if (!empty($oauth_callback))
- {
- $params = array('oauth_token' => rawurlencode($token));
- // 1.0a Compatibility : if verifier code has been generated, add it to the URL
- if ($verifier) {
- $params['oauth_verifier'] = $verifier;
- }
-
- $uri = preg_replace('/\s/', '%20', $oauth_callback);
- if (!empty($this->allowed_uri_schemes))
- {
- if (!in_array(substr($uri, 0, strpos($uri, '://')), $this->allowed_uri_schemes))
- {
- throw new OAuthException2('Illegal protocol in redirect uri '.$uri);
- }
- }
- else if (!empty($this->disallowed_uri_schemes))
- {
- if (in_array(substr($uri, 0, strpos($uri, '://')), $this->disallowed_uri_schemes))
- {
- throw new OAuthException2('Illegal protocol in redirect uri '.$uri);
- }
- }
-
- $this->redirect($oauth_callback, $params, true);
- }
- }
- OAuthRequestLogger::flush();
- return $verifier;
- }
-
-
- /**
- * Exchange a request token for an access token.
- * The exchange is only succesful iff the request token has been authorized.
- *
- * Never returns, calls exit() when token is exchanged or when error is returned.
- */
- public function accessToken ()
- {
- OAuthRequestLogger::start($this);
-
- try
- {
- $this->verify('request');
-
- $options = array();
- $ttl = $this->getParam('xoauth_token_ttl', false);
- if ($ttl)
- {
- $options['token_ttl'] = $ttl;
- }
-
- $verifier = $this->getParam('oauth_verifier', false);
- if ($verifier) {
- $options['verifier'] = $verifier;
- }
-
- $store = OAuthStore::instance();
- $token = $store->exchangeConsumerRequestForAccessToken($this->getParam('oauth_token', true), $options);
- $result = 'oauth_token='.$this->urlencode($token['token'])
- .'&oauth_token_secret='.$this->urlencode($token['token_secret']);
-
- if (!empty($token['token_ttl']))
- {
- $result .= '&xoauth_token_ttl='.$this->urlencode($token['token_ttl']);
- }
-
- header('HTTP/1.1 200 OK');
- header('Content-Length: '.strlen($result));
- header('Content-Type: application/x-www-form-urlencoded');
-
- echo $result;
- }
- catch (OAuthException2 $e)
- {
- header('HTTP/1.1 401 Access Denied');
- header('Content-Type: text/plain');
-
- echo "OAuth Verification Failed: " . $e->getMessage();
- }
-
- OAuthRequestLogger::flush();
- exit();
- }
-}
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?>
diff --git a/vendor/oauth-php/library/OAuthSession.php b/vendor/oauth-php/library/OAuthSession.php
deleted file mode 100644
index 80ceeb7..0000000
--- a/vendor/oauth-php/library/OAuthSession.php
+++ /dev/null
@@ -1,86 +0,0 @@
-<?php
-
-/**
- * Storage container for the oauth credentials, both server and consumer side.
- * This is the factory to select the store you want to use
- *
- * @version $Id: OAuthSession.php 67 2010-01-12 18:42:04Z brunobg@corollarium.com $
- * @author brunobg@corollarium.com
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- * Copyright (c) 2010 Corollarium Technologies
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__) . '/OAuthException2.php';
-
-class OAuthSession
-{
- static private $instance = false;
-
- /**
- * Request an instance of the OAuthSession
- */
- public static function instance ( $store = 'SESSION', $options = array() )
- {
- if (!OAuthSession::$instance)
- {
- // Select the store you want to use
- if (strpos($store, '/') === false)
- {
- $class = 'OAuthSession'.$store;
- $file = dirname(__FILE__) . '/session/'.$class.'.php';
- }
- else
- {
- $file = $store;
- $store = basename($file, '.php');
- $class = $store;
- }
-
- if (is_file($file))
- {
- require_once $file;
-
- if (class_exists($class))
- {
- OAuthSession::$instance = new $class($options);
- }
- else
- {
- throw new OAuthException2('Could not find class '.$class.' in file '.$file);
- }
- }
- else
- {
- throw new OAuthException2('No OAuthSession for '.$store.' (file '.$file.')');
- }
- }
- return OAuthSession::$instance;
- }
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/OAuthStore.php b/vendor/oauth-php/library/OAuthStore.php
deleted file mode 100644
index ff6db0f..0000000
--- a/vendor/oauth-php/library/OAuthStore.php
+++ /dev/null
@@ -1,91 +0,0 @@
-<?php
-
-/**
- * Storage container for the oauth credentials, both server and consumer side.
- * This is the factory to select the store you want to use
- *
- * @version $Id: OAuthStore.php 182 2011-01-12 14:57:29Z brunobg@corollarium.com $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Nov 16, 2007 4:03:30 PM
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__) . '/OAuthException2.php';
-
-class OAuthStore
-{
- static private $instance = false;
-
- /**
- * Request an instance of the OAuthStore
- *
- * @param string $store The storage system
- * @param array $options To pass to the storage system
- * @param boolean $forceNewInstance If true, forces the instantiation of a new store.
- * @throws OAuthException2
- */
- public static function instance ( $store = 'MySQL', $options = array(), $forceNewInstance = false )
- {
- if (!OAuthStore::$instance or $forceNewInstance)
- {
- // Select the store you want to use
- if (strpos($store, '/') === false)
- {
- $class = 'OAuthStore'.$store;
- $file = dirname(__FILE__) . '/store/'.$class.'.php';
- }
- else
- {
- $file = $store;
- $store = basename($file, '.php');
- $class = $store;
- }
-
- if (is_file($file))
- {
- require_once $file;
-
- if (class_exists($class))
- {
- OAuthStore::$instance = new $class($options);
- }
- else
- {
- throw new OAuthException2('Could not find class '.$class.' in file '.$file);
- }
- }
- else
- {
- throw new OAuthException2('No OAuthStore for '.$store.' (file '.$file.')');
- }
- }
- return OAuthStore::$instance;
- }
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/body/OAuthBodyContentDisposition.php b/vendor/oauth-php/library/body/OAuthBodyContentDisposition.php
deleted file mode 100644
index 02b1e42..0000000
--- a/vendor/oauth-php/library/body/OAuthBodyContentDisposition.php
+++ /dev/null
@@ -1,129 +0,0 @@
-<?php
-
-/**
- * Add the extra headers for a PUT or POST request with a file.
- *
- * @version $Id$
- * @author Marc Worrell <marcw@pobox.com>
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-class OAuthBodyContentDisposition
-{
- /**
- * Builds the request string.
- *
- * The files array can be a combination of the following (either data or file):
- *
- * file => "path/to/file", filename=, mime=, data=
- *
- * @param array files (name => filedesc) (not urlencoded)
- * @return array (headers, body)
- */
- static function encodeBody ( $files )
- {
- $headers = array();
- $body = null;
-
- // 1. Add all the files to the post
- if (!empty($files))
- {
- foreach ($files as $name => $f)
- {
- $data = false;
- $filename = false;
-
- if (isset($f['filename']))
- {
- $filename = $f['filename'];
- }
-
- if (!empty($f['file']))
- {
- $data = @file_get_contents($f['file']);
- if ($data === false)
- {
- throw new OAuthException2(sprintf('Could not read the file "%s" for request body', $f['file']));
- }
- if (empty($filename))
- {
- $filename = basename($f['file']);
- }
- }
- else if (isset($f['data']))
- {
- $data = $f['data'];
- }
-
- // When there is data, add it as a request body, otherwise silently skip the upload
- if ($data !== false)
- {
- if (isset($headers['Content-Disposition']))
- {
- throw new OAuthException2('Only a single file (or data) allowed in a signed PUT/POST request body.');
- }
-
- if (empty($filename))
- {
- $filename = 'untitled';
- }
- $mime = !empty($f['mime']) ? $f['mime'] : 'application/octet-stream';
-
- $headers['Content-Disposition'] = 'attachment; filename="'.OAuthBodyContentDisposition::encodeParameterName($filename).'"';
- $headers['Content-Type'] = $mime;
-
- $body = $data;
- }
-
- }
-
- // When we have a body, add the content-length
- if (!is_null($body))
- {
- $headers['Content-Length'] = strlen($body);
- }
- }
- return array($headers, $body);
- }
-
-
- /**
- * Encode a parameter's name for use in a multipart header.
- * For now we do a simple filter that removes some unwanted characters.
- * We might want to implement RFC1522 here. See http://tools.ietf.org/html/rfc1522
- *
- * @param string name
- * @return string
- */
- static function encodeParameterName ( $name )
- {
- return preg_replace('/[^\x20-\x7f]|"/', '-', $name);
- }
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/body/OAuthBodyMultipartFormdata.php b/vendor/oauth-php/library/body/OAuthBodyMultipartFormdata.php
deleted file mode 100644
index a869e1e..0000000
--- a/vendor/oauth-php/library/body/OAuthBodyMultipartFormdata.php
+++ /dev/null
@@ -1,143 +0,0 @@
-<?php
-
-/**
- * Create the body for a multipart/form-data message.
- *
- * @version $Id: OAuthMultipartFormdata.php 6 2008-02-13 12:35:09Z marcw@pobox.com $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Jan 31, 2008 12:50:05 PM
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-class OAuthBodyMultipartFormdata
-{
- /**
- * Builds the request string.
- *
- * The files array can be a combination of the following (either data or file):
- *
- * file => "path/to/file", filename=, mime=, data=
- *
- * @param array params (name => value) (all names and values should be urlencoded)
- * @param array files (name => filedesc) (not urlencoded)
- * @return array (headers, body)
- */
- static function encodeBody ( $params, $files )
- {
- $headers = array();
- $body = '';
- $boundary = 'OAuthRequester_'.md5(uniqid('multipart') . microtime());
- $headers['Content-Type'] = 'multipart/form-data; boundary=' . $boundary;
-
-
- // 1. Add the parameters to the post
- if (!empty($params))
- {
- foreach ($params as $name => $value)
- {
- $body .= '--'.$boundary."\r\n";
- $body .= 'Content-Disposition: form-data; name="'.OAuthBodyMultipartFormdata::encodeParameterName(rawurldecode($name)).'"';
- $body .= "\r\n\r\n";
- $body .= urldecode($value);
- $body .= "\r\n";
- }
- }
-
- // 2. Add all the files to the post
- if (!empty($files))
- {
- $untitled = 1;
-
- foreach ($files as $name => $f)
- {
- $data = false;
- $filename = false;
-
- if (isset($f['filename']))
- {
- $filename = $f['filename'];
- }
-
- if (!empty($f['file']))
- {
- $data = @file_get_contents($f['file']);
- if ($data === false)
- {
- throw new OAuthException2(sprintf('Could not read the file "%s" for form-data part', $f['file']));
- }
- if (empty($filename))
- {
- $filename = basename($f['file']);
- }
- }
- else if (isset($f['data']))
- {
- $data = $f['data'];
- }
-
- // When there is data, add it as a form-data part, otherwise silently skip the upload
- if ($data !== false)
- {
- if (empty($filename))
- {
- $filename = sprintf('untitled-%d', $untitled++);
- }
- $mime = !empty($f['mime']) ? $f['mime'] : 'application/octet-stream';
- $body .= '--'.$boundary."\r\n";
- $body .= 'Content-Disposition: form-data; name="'.OAuthBodyMultipartFormdata::encodeParameterName($name).'"; filename="'.OAuthBodyMultipartFormdata::encodeParameterName($filename).'"'."\r\n";
- $body .= 'Content-Type: '.$mime;
- $body .= "\r\n\r\n";
- $body .= $data;
- $body .= "\r\n";
- }
-
- }
- }
- $body .= '--'.$boundary."--\r\n";
-
- $headers['Content-Length'] = strlen($body);
- return array($headers, $body);
- }
-
-
- /**
- * Encode a parameter's name for use in a multipart header.
- * For now we do a simple filter that removes some unwanted characters.
- * We might want to implement RFC1522 here. See http://tools.ietf.org/html/rfc1522
- *
- * @param string name
- * @return string
- */
- static function encodeParameterName ( $name )
- {
- return preg_replace('/[^\x20-\x7f]|"/', '-', $name);
- }
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/discovery/xrds_parse.php b/vendor/oauth-php/library/discovery/xrds_parse.php
deleted file mode 100644
index 7262bd9..0000000
--- a/vendor/oauth-php/library/discovery/xrds_parse.php
+++ /dev/null
@@ -1,304 +0,0 @@
-<?php
-
-/**
- * Parse a XRDS discovery description to a simple array format.
- *
- * For now a simple parse of the document. Better error checking
- * in a later version.
- *
- * @version $Id$
- * @author Marc Worrell <marcw@pobox.com>
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-/* example of use:
-
-header('content-type: text/plain');
-$file = file_get_contents('../../test/discovery/xrds-magnolia.xrds');
-$xrds = xrds_parse($file);
-print_r($xrds);
-
- */
-
-/**
- * Parse the xrds file in the argument. The xrds description must have been
- * fetched via curl or something else.
- *
- * TODO: more robust checking, support for more service documents
- * TODO: support for URIs to definition instead of local xml:id
- *
- * @param string data contents of xrds file
- * @exception Exception when the file is in an unknown format
- * @return array
- */
-function xrds_parse ( $data )
-{
- $oauth = array();
- $doc = @DOMDocument::loadXML($data);
- if ($doc === false)
- {
- throw new Exception('Error in XML, can\'t load XRDS document');
- }
-
- $xpath = new DOMXPath($doc);
- $xpath->registerNamespace('xrds', 'xri://$xrds');
- $xpath->registerNamespace('xrd', 'xri://$XRD*($v*2.0)');
- $xpath->registerNamespace('simple', 'http://xrds-simple.net/core/1.0');
-
- // Yahoo! uses this namespace, with lowercase xrd in it
- $xpath->registerNamespace('xrd2', 'xri://$xrd*($v*2.0)');
-
- $uris = xrds_oauth_service_uris($xpath);
-
- foreach ($uris as $uri)
- {
- // TODO: support uris referring to service documents outside this one
- if ($uri[0] == '#')
- {
- $id = substr($uri, 1);
- $oauth = xrds_xrd_oauth($xpath, $id);
- if (is_array($oauth) && !empty($oauth))
- {
- return $oauth;
- }
- }
- }
-
- return false;
-}
-
-
-/**
- * Parse a XRD definition for OAuth and return the uris etc.
- *
- * @param XPath xpath
- * @param string id
- * @return array
- */
-function xrds_xrd_oauth ( $xpath, $id )
-{
- $oauth = array();
- $xrd = $xpath->query('//xrds:XRDS/xrd:XRD[@xml:id="'.$id.'"]');
- if ($xrd->length == 0)
- {
- // Yahoo! uses another namespace
- $xrd = $xpath->query('//xrds:XRDS/xrd2:XRD[@xml:id="'.$id.'"]');
- }
-
- if ($xrd->length >= 1)
- {
- $x = $xrd->item(0);
- $services = array();
- foreach ($x->childNodes as $n)
- {
- switch ($n->nodeName)
- {
- case 'Type':
- if ($n->nodeValue != 'xri://$xrds*simple')
- {
- // Not a simple XRDS document
- return false;
- }
- break;
- case 'Expires':
- $oauth['expires'] = $n->nodeValue;
- break;
- case 'Service':
- list($type,$service) = xrds_xrd_oauth_service($n);
- if ($type)
- {
- $services[$type][xrds_priority($n)][] = $service;
- }
- break;
- }
- }
-
- // Flatten the services on priority
- foreach ($services as $type => $service)
- {
- $oauth[$type] = xrds_priority_flatten($service);
- }
- }
- else
- {
- $oauth = false;
- }
- return $oauth;
-}
-
-
-/**
- * Parse a service definition for OAuth in a simple xrd element
- *
- * @param DOMElement n
- * @return array (type, service desc)
- */
-function xrds_xrd_oauth_service ( $n )
-{
- $service = array(
- 'uri' => '',
- 'signature_method' => array(),
- 'parameters' => array()
- );
-
- $type = false;
- foreach ($n->childNodes as $c)
- {
- $name = $c->nodeName;
- $value = $c->nodeValue;
-
- if ($name == 'URI')
- {
- $service['uri'] = $value;
- }
- else if ($name == 'Type')
- {
- if (strncmp($value, 'http://oauth.net/core/1.0/endpoint/', 35) == 0)
- {
- $type = basename($value);
- }
- else if (strncmp($value, 'http://oauth.net/core/1.0/signature/', 36) == 0)
- {
- $service['signature_method'][] = basename($value);
- }
- else if (strncmp($value, 'http://oauth.net/core/1.0/parameters/', 37) == 0)
- {
- $service['parameters'][] = basename($value);
- }
- else if (strncmp($value, 'http://oauth.net/discovery/1.0/consumer-identity/', 49) == 0)
- {
- $type = 'consumer_identity';
- $service['method'] = basename($value);
- unset($service['signature_method']);
- unset($service['parameters']);
- }
- else
- {
- $service['unknown'][] = $value;
- }
- }
- else if ($name == 'LocalID')
- {
- $service['consumer_key'] = $value;
- }
- else if ($name[0] != '#')
- {
- $service[strtolower($name)] = $value;
- }
- }
- return array($type, $service);
-}
-
-
-/**
- * Return the OAuth service uris in order of the priority.
- *
- * @param XPath xpath
- * @return array
- */
-function xrds_oauth_service_uris ( $xpath )
-{
- $uris = array();
- $xrd_oauth = $xpath->query('//xrds:XRDS/xrd:XRD/xrd:Service/xrd:Type[.=\'http://oauth.net/discovery/1.0\']');
- if ($xrd_oauth->length > 0)
- {
- $service = array();
- foreach ($xrd_oauth as $xo)
- {
- // Find the URI of the service definition
- $cs = $xo->parentNode->childNodes;
- foreach ($cs as $c)
- {
- if ($c->nodeName == 'URI')
- {
- $prio = xrds_priority($xo);
- $service[$prio][] = $c->nodeValue;
- }
- }
- }
- $uris = xrds_priority_flatten($service);
- }
- return $uris;
-}
-
-
-
-/**
- * Flatten an array according to the priority
- *
- * @param array ps buckets per prio
- * @return array one dimensional array
- */
-function xrds_priority_flatten ( $ps )
-{
- $prio = array();
- $null = array();
- ksort($ps);
- foreach ($ps as $idx => $bucket)
- {
- if (!empty($bucket))
- {
- if ($idx == 'null')
- {
- $null = $bucket;
- }
- else
- {
- $prio = array_merge($prio, $bucket);
- }
- }
- }
- $prio = array_merge($prio, $bucket);
- return $prio;
-}
-
-
-/**
- * Fetch the priority of a element
- *
- * @param DOMElement elt
- * @return mixed 'null' or int
- */
-function xrds_priority ( $elt )
-{
- if ($elt->hasAttribute('priority'))
- {
- $prio = $elt->getAttribute('priority');
- if (is_numeric($prio))
- {
- $prio = intval($prio);
- }
- }
- else
- {
- $prio = 'null';
- }
- return $prio;
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?>
diff --git a/vendor/oauth-php/library/discovery/xrds_parse.txt b/vendor/oauth-php/library/discovery/xrds_parse.txt
deleted file mode 100644
index fd867ea..0000000
--- a/vendor/oauth-php/library/discovery/xrds_parse.txt
+++ /dev/null
@@ -1,101 +0,0 @@
-The xrds_parse.php script contains the function:
-
- function xrds_parse ( $data. )
-
-$data Contains the contents of a XRDS XML file.
-When the data is invalid XML then this will throw an exception.
-
-After parsing a XRDS definition it will return a datastructure much like the one below.
-
-Array
-(
- [expires] => 2008-04-13T07:34:58Z
- [request] => Array
- (
- [0] => Array
- (
- [uri] => https://ma.gnolia.com/oauth/get_request_token
- [signature_method] => Array
- (
- [0] => HMAC-SHA1
- [1] => RSA-SHA1
- [2] => PLAINTEXT
- )
-
- [parameters] => Array
- (
- [0] => auth-header
- [1] => post-body
- [2] => uri-query
- )
- )
- )
-
- [authorize] => Array
- (
- [0] => Array
- (
- [uri] => http://ma.gnolia.com/oauth/authorize
- [signature_method] => Array
- (
- )
-
- [parameters] => Array
- (
- [0] => auth-header
- [1] => uri-query
- )
- )
- )
-
- [access] => Array
- (
- [0] => Array
- (
- [uri] => https://ma.gnolia.com/oauth/get_access_token
- [signature_method] => Array
- (
- [0] => HMAC-SHA1
- [1] => RSA-SHA1
- [2] => PLAINTEXT
- )
-
- [parameters] => Array
- (
- [0] => auth-header
- [1] => post-body
- [2] => uri-query
- )
- )
- )
-
- [resource] => Array
- (
- [0] => Array
- (
- [uri] =>
- [signature_method] => Array
- (
- [0] => HMAC-SHA1
- [1] => RSA-SHA1
- )
-
- [parameters] => Array
- (
- [0] => auth-header
- [1] => post-body
- [2] => uri-query
- )
- )
- )
-
- [consumer_identity] => Array
- (
- [0] => Array
- (
- [uri] => http://ma.gnolia.com/applications/new
- [method] => oob
- )
- )
-)
-
diff --git a/vendor/oauth-php/library/session/OAuthSessionAbstract.php b/vendor/oauth-php/library/session/OAuthSessionAbstract.php
deleted file mode 100644
index dcc80c1..0000000
--- a/vendor/oauth-php/library/session/OAuthSessionAbstract.php
+++ /dev/null
@@ -1,44 +0,0 @@
-<?php
-
-/**
- * Abstract base class for OAuthStore implementations
- *
- * @version $Id$
- * @author Bruno Barberi Gnecco <brunobg@corollarium.com>
- *
- * The MIT License
- *
- * Copyright (c) 2010 Corollarium Technologies
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-/**
- * This class is used to store Session information on the server. Most
- * people will use the $_SESSION based implementation, but you may prefer
- * a SQL, Memcache or other implementation.
- *
- */
-abstract class OAuthSessionAbstract
-{
- abstract public function get ( $key );
- abstract public function set ( $key, $data );
-}
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/session/OAuthSessionSESSION.php b/vendor/oauth-php/library/session/OAuthSessionSESSION.php
deleted file mode 100644
index 3201ecb..0000000
--- a/vendor/oauth-php/library/session/OAuthSessionSESSION.php
+++ /dev/null
@@ -1,63 +0,0 @@
-<?php
-
-/**
- * Abstract base class for OAuthStore implementations
- *
- * @version $Id$
- * @author Bruno Barberi Gnecco <brunobg@corollarium.com>
- *
- * The MIT License
- *
- * Copyright (c) 2010 Corollarium Technologies
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__) . '/OAuthSessionAbstract.class.php';
-
-class OAuthSessionSESSION extends OAuthSessionAbstract
-{
- public function __construct( $options = array() )
- {
- }
-
- /**
- * Gets a variable value
- *
- * @param string $key
- * @return The value or null if not set.
- */
- public function get ( $key )
- {
- return @$_SESSION[$key];
- }
-
- /**
- * Sets a variable value
- *
- * @param string $key The key
- * @param any $data The data
- */
- public function set ( $key, $data )
- {
- $_SESSION[$key] = $data;
- }
-}
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod.php b/vendor/oauth-php/library/signature_method/OAuthSignatureMethod.php
deleted file mode 100644
index 34ccb42..0000000
--- a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod.php
+++ /dev/null
@@ -1,69 +0,0 @@
-<?php
-
-/**
- * Interface for OAuth signature methods
- *
- * @version $Id$
- * @author Marc Worrell <marcw@pobox.com>
- * @date Sep 8, 2008 12:04:35 PM
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-abstract class OAuthSignatureMethod
-{
- /**
- * Return the name of this signature
- *
- * @return string
- */
- abstract public function name();
-
- /**
- * Return the signature for the given request
- *
- * @param OAuthRequest request
- * @param string base_string
- * @param string consumer_secret
- * @param string token_secret
- * @return string
- */
- abstract public function signature ( $request, $base_string, $consumer_secret, $token_secret );
-
- /**
- * Check if the request signature corresponds to the one calculated for the request.
- *
- * @param OAuthRequest request
- * @param string base_string data to be signed, usually the base string, can be a request body
- * @param string consumer_secret
- * @param string token_secret
- * @param string signature from the request, still urlencoded
- * @return string
- */
- abstract public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature );
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php b/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php
deleted file mode 100644
index e189c93..0000000
--- a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php
+++ /dev/null
@@ -1,115 +0,0 @@
-<?php
-
-/**
- * OAuth signature implementation using HMAC-SHA1
- *
- * @version $Id$
- * @author Marc Worrell <marcw@pobox.com>
- * @date Sep 8, 2008 12:21:19 PM
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php';
-
-
-class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod
-{
- public function name ()
- {
- return 'HMAC-SHA1';
- }
-
-
- /**
- * Calculate the signature using HMAC-SHA1
- * This function is copyright Andy Smith, 2007.
- *
- * @param OAuthRequest request
- * @param string base_string
- * @param string consumer_secret
- * @param string token_secret
- * @return string
- */
- function signature ( $request, $base_string, $consumer_secret, $token_secret )
- {
- $key = $request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret);
- if (function_exists('hash_hmac'))
- {
- $signature = base64_encode(hash_hmac("sha1", $base_string, $key, true));
- }
- else
- {
- $blocksize = 64;
- $hashfunc = 'sha1';
- if (strlen($key) > $blocksize)
- {
- $key = pack('H*', $hashfunc($key));
- }
- $key = str_pad($key,$blocksize,chr(0x00));
- $ipad = str_repeat(chr(0x36),$blocksize);
- $opad = str_repeat(chr(0x5c),$blocksize);
- $hmac = pack(
- 'H*',$hashfunc(
- ($key^$opad).pack(
- 'H*',$hashfunc(
- ($key^$ipad).$base_string
- )
- )
- )
- );
- $signature = base64_encode($hmac);
- }
- return $request->urlencode($signature);
- }
-
-
- /**
- * Check if the request signature corresponds to the one calculated for the request.
- *
- * @param OAuthRequest request
- * @param string base_string data to be signed, usually the base string, can be a request body
- * @param string consumer_secret
- * @param string token_secret
- * @param string signature from the request, still urlencoded
- * @return string
- */
- public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature )
- {
- $a = $request->urldecode($signature);
- $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret));
-
- // We have to compare the decoded values
- $valA = base64_decode($a);
- $valB = base64_decode($b);
-
- // Crude binary comparison
- return rawurlencode($valA) == rawurlencode($valB);
- }
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA256.php b/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA256.php
deleted file mode 100644
index 2d037dd..0000000
--- a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA256.php
+++ /dev/null
@@ -1,81 +0,0 @@
-<?php
-
-/**
- * OAuth signature implementation using HMAC-SHA256
- *
- * @author André Noack <noack@data-quest.de>
- *
- * The MIT License
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php';
-
-
-class OAuthSignatureMethod_HMAC_SHA256 extends OAuthSignatureMethod
-{
- public function name ()
- {
- return 'HMAC-SHA256';
- }
-
-
- /**
- * Calculate the signature using HMAC-SHA1
- * This function is copyright Andy Smith, 2007.
- *
- * @param OAuthRequest request
- * @param string base_string
- * @param string consumer_secret
- * @param string token_secret
- * @return string
- */
- function signature ( $request, $base_string, $consumer_secret, $token_secret )
- {
- $key = $request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret);
- $signature = base64_encode(hash_hmac("sha256", $base_string, $key, true));
- return $request->urlencode($signature);
- }
-
-
- /**
- * Check if the request signature corresponds to the one calculated for the request.
- *
- * @param OAuthRequest request
- * @param string base_string data to be signed, usually the base string, can be a request body
- * @param string consumer_secret
- * @param string token_secret
- * @param string signature from the request, still urlencoded
- * @return string
- */
- public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature )
- {
- $a = $request->urldecode($signature);
- $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret));
-
- // We have to compare the decoded values
- $valA = base64_decode($a);
- $valB = base64_decode($b);
-
- // Crude binary comparison
- return rawurlencode($valA) == rawurlencode($valB);
- }
-}
diff --git a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php b/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php
deleted file mode 100644
index a016709..0000000
--- a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php
+++ /dev/null
@@ -1,95 +0,0 @@
-<?php
-
-/**
- * OAuth signature implementation using MD5
- *
- * @version $Id$
- * @author Marc Worrell <marcw@pobox.com>
- * @date Sep 8, 2008 12:09:43 PM
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php';
-
-
-class OAuthSignatureMethod_MD5 extends OAuthSignatureMethod
-{
- public function name ()
- {
- return 'MD5';
- }
-
-
- /**
- * Calculate the signature using MD5
- * Binary md5 digest, as distinct from PHP's built-in hexdigest.
- * This function is copyright Andy Smith, 2007.
- *
- * @param OAuthRequest request
- * @param string base_string
- * @param string consumer_secret
- * @param string token_secret
- * @return string
- */
- function signature ( $request, $base_string, $consumer_secret, $token_secret )
- {
- $s .= '&'.$request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret);
- $md5 = md5($base_string);
- $bin = '';
-
- for ($i = 0; $i < strlen($md5); $i += 2)
- {
- $bin .= chr(hexdec($md5{$i+1}) + hexdec($md5{$i}) * 16);
- }
- return $request->urlencode(base64_encode($bin));
- }
-
-
- /**
- * Check if the request signature corresponds to the one calculated for the request.
- *
- * @param OAuthRequest request
- * @param string base_string data to be signed, usually the base string, can be a request body
- * @param string consumer_secret
- * @param string token_secret
- * @param string signature from the request, still urlencoded
- * @return string
- */
- public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature )
- {
- $a = $request->urldecode($signature);
- $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret));
-
- // We have to compare the decoded values
- $valA = base64_decode($a);
- $valB = base64_decode($b);
-
- // Crude binary comparison
- return rawurlencode($valA) == rawurlencode($valB);
- }
-}
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php b/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php
deleted file mode 100644
index 92ef308..0000000
--- a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php
+++ /dev/null
@@ -1,80 +0,0 @@
-<?php
-
-/**
- * OAuth signature implementation using PLAINTEXT
- *
- * @version $Id$
- * @author Marc Worrell <marcw@pobox.com>
- * @date Sep 8, 2008 12:09:43 PM
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php';
-
-
-class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod
-{
- public function name ()
- {
- return 'PLAINTEXT';
- }
-
-
- /**
- * Calculate the signature using PLAINTEXT
- *
- * @param OAuthRequest request
- * @param string base_string
- * @param string consumer_secret
- * @param string token_secret
- * @return string
- */
- function signature ( $request, $base_string, $consumer_secret, $token_secret )
- {
- return $request->urlencode($request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret));
- }
-
-
- /**
- * Check if the request signature corresponds to the one calculated for the request.
- *
- * @param OAuthRequest request
- * @param string base_string data to be signed, usually the base string, can be a request body
- * @param string consumer_secret
- * @param string token_secret
- * @param string signature from the request, still urlencoded
- * @return string
- */
- public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature )
- {
- $a = $request->urldecode($signature);
- $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret));
-
- return $request->urldecode($a) == $request->urldecode($b);
- }
-}
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php b/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php
deleted file mode 100644
index 864dbfb..0000000
--- a/vendor/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php
+++ /dev/null
@@ -1,139 +0,0 @@
-<?php
-
-/**
- * OAuth signature implementation using PLAINTEXT
- *
- * @version $Id$
- * @author Marc Worrell <marcw@pobox.com>
- * @date Sep 8, 2008 12:00:14 PM
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php';
-
-class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod
-{
- public function name()
- {
- return 'RSA-SHA1';
- }
-
-
- /**
- * Fetch the public CERT key for the signature
- *
- * @param OAuthRequest request
- * @return string public key
- */
- protected function fetch_public_cert ( $request )
- {
- // not implemented yet, ideas are:
- // (1) do a lookup in a table of trusted certs keyed off of consumer
- // (2) fetch via http using a url provided by the requester
- // (3) some sort of specific discovery code based on request
- //
- // either way should return a string representation of the certificate
- throw OAuthException2("OAuthSignatureMethod_RSA_SHA1::fetch_public_cert not implemented");
- }
-
-
- /**
- * Fetch the private CERT key for the signature
- *
- * @param OAuthRequest request
- * @return string private key
- */
- protected function fetch_private_cert ( $request )
- {
- // not implemented yet, ideas are:
- // (1) do a lookup in a table of trusted certs keyed off of consumer
- //
- // either way should return a string representation of the certificate
- throw OAuthException2("OAuthSignatureMethod_RSA_SHA1::fetch_private_cert not implemented");
- }
-
-
- /**
- * Calculate the signature using RSA-SHA1
- * This function is copyright Andy Smith, 2008.
- *
- * @param OAuthRequest request
- * @param string base_string
- * @param string consumer_secret
- * @param string token_secret
- * @return string
- */
- public function signature ( $request, $base_string, $consumer_secret, $token_secret )
- {
- // Fetch the private key cert based on the request
- $cert = $this->fetch_private_cert($request);
-
- // Pull the private key ID from the certificate
- $privatekeyid = openssl_get_privatekey($cert);
-
- // Sign using the key
- $sig = false;
- $ok = openssl_sign($base_string, $sig, $privatekeyid);
-
- // Release the key resource
- openssl_free_key($privatekeyid);
-
- return $request->urlencode(base64_encode($sig));
- }
-
-
- /**
- * Check if the request signature is the same as the one calculated for the request.
- *
- * @param OAuthRequest request
- * @param string base_string
- * @param string consumer_secret
- * @param string token_secret
- * @param string signature
- * @return string
- */
- public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature )
- {
- $decoded_sig = base64_decode($request->urldecode($signature));
-
- // Fetch the public key cert based on the request
- $cert = $this->fetch_public_cert($request);
-
- // Pull the public key ID from the certificate
- $publickeyid = openssl_get_publickey($cert);
-
- // Check the computed signature against the one passed in the query
- $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
-
- // Release the key resource
- openssl_free_key($publickeyid);
- return $ok == 1;
- }
-
-}
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/OAuthStore2Leg.php b/vendor/oauth-php/library/store/OAuthStore2Leg.php
deleted file mode 100644
index d86505b..0000000
--- a/vendor/oauth-php/library/store/OAuthStore2Leg.php
+++ /dev/null
@@ -1,118 +0,0 @@
-<?php
-
-/**
- * OAuthStore implementation for 2 legged OAuth. This 'store' just saves the
- * consumer_token and consumer_secret.
- *
- * @version $Id$
- * @author Ben Hesketh <ben.hesketh@compassengine.com>
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php';
-
-class OAuthStore2Leg extends OAuthStoreAbstract
-{
- protected $consumer_key;
- protected $consumer_secret;
- protected $signature_method = array('HMAC-SHA1');
- protected $token_type = false;
-
- /*
- * Takes two options: consumer_key and consumer_secret
- */
- public function __construct( $options = array() )
- {
- if(isset($options['consumer_key']) && isset($options['consumer_secret']))
- {
- $this->consumer_key = $options['consumer_key'];
- $this->consumer_secret = $options['consumer_secret'];
- if (isset($options['token_secret']))
- {
- $this->token_secret = $options['token_secret'];
- }
- }
- else
- {
- throw new OAuthException2("OAuthStore2Leg needs consumer_token and consumer_secret");
- }
- }
-
- public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function getSecretsForSignature ( $uri, $user_id )
- {
- return array(
- 'consumer_key' => $this->consumer_key,
- 'consumer_secret' => $this->consumer_secret,
- 'signature_methods' => $this->signature_method,
- 'token' => $this->token_type,
- 'token_secret' => $this->token_secret
- );
- }
- public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
-
- public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function getServer( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function getServerForUri ( $uri, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function listServerTokens ( $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function countServerTokens ( $consumer_key ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function getServerToken ( $consumer_key, $token, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function setServerTokenTtl ( $consumer_key, $token, $token_ttl, $server_uri = NULL )
- {
- //This method just needs to exist. It doesn't have to do anything!
- }
-
- public function listServers ( $q = '', $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function updateServer ( $server, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
-
- public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function getConsumerStatic () { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
-
- public function addConsumerRequestToken ( $consumer_key, $options = array() ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function getConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function deleteConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function countConsumerAccessTokens ( $consumer_key ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function getConsumerAccessToken ( $token, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function setConsumerAccessTokenTtl ( $token, $ttl ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
-
- public function listConsumers ( $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function listConsumerApplications( $begin = 0, $total = 25 ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function listConsumerTokens ( $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
-
- public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
-
- public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
- public function listLog ( $options, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
-
- public function install () { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); }
-}
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/OAuthStoreAbstract.php b/vendor/oauth-php/library/store/OAuthStoreAbstract.php
deleted file mode 100644
index 0b240ee..0000000
--- a/vendor/oauth-php/library/store/OAuthStoreAbstract.php
+++ /dev/null
@@ -1,151 +0,0 @@
-<?php
-
-/**
- * Abstract base class for OAuthStore implementations
- *
- * @version $Id$
- * @author Marc Worrell <marcw@pobox.com>
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-abstract class OAuthStoreAbstract
-{
- abstract public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' );
- abstract public function getSecretsForSignature ( $uri, $user_id );
- abstract public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' );
- abstract public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() );
-
- abstract public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false );
- abstract public function getServer( $consumer_key, $user_id, $user_is_admin = false );
- abstract public function getServerForUri ( $uri, $user_id );
- abstract public function listServerTokens ( $user_id );
- abstract public function countServerTokens ( $consumer_key );
- abstract public function getServerToken ( $consumer_key, $token, $user_id );
- abstract public function setServerTokenTtl ( $consumer_key, $token, $token_ttl, $server_uri = NULL );
- abstract public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false );
- abstract public function listServers ( $q = '', $user_id );
- abstract public function updateServer ( $server, $user_id, $user_is_admin = false );
-
- abstract public function updateConsumer ( $consumer, $user_id, $user_is_admin = false );
- abstract public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false );
- abstract public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false );
- abstract public function getConsumerStatic ();
-
- abstract public function addConsumerRequestToken ( $consumer_key, $options = array() );
- abstract public function getConsumerRequestToken ( $token );
- abstract public function deleteConsumerRequestToken ( $token );
- abstract public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' );
- abstract public function countConsumerAccessTokens ( $consumer_key );
- abstract public function exchangeConsumerRequestForAccessToken ( $token, $options = array() );
- abstract public function getConsumerAccessToken ( $token, $user_id );
- abstract public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false );
- abstract public function setConsumerAccessTokenTtl ( $token, $ttl );
-
- abstract public function listConsumers ( $user_id );
- abstract public function listConsumerApplications( $begin = 0, $total = 25 );
- abstract public function listConsumerTokens ( $user_id );
-
- abstract public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce );
-
- abstract public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null );
- abstract public function listLog ( $options, $user_id );
-
- abstract public function install ();
-
- /**
- * Fetch the current static consumer key for this site, create it when it was not found.
- * The consumer secret for the consumer key is always empty.
- *
- * @return string consumer key
- */
-
-
- /* ** Some handy utility functions ** */
-
- /**
- * Generate a unique key
- *
- * @param boolean unique force the key to be unique
- * @return string
- */
- public function generateKey ( $unique = false )
- {
- $key = md5(uniqid(rand(), true));
- if ($unique)
- {
- list($usec,$sec) = explode(' ',microtime());
- $key .= dechex($usec).dechex($sec);
- }
- return $key;
- }
-
- /**
- * Check to see if a string is valid utf8
- *
- * @param string $s
- * @return boolean
- */
- protected function isUTF8 ( $s )
- {
- return preg_match('%(?:
- [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
- |\xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
- |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
- |\xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
- |\xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
- |[\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
- |\xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
- )+%xs', $s);
- }
-
-
- /**
- * Make a string utf8, replacing all non-utf8 chars with a '.'
- *
- * @param string
- * @return string
- */
- protected function makeUTF8 ( $s )
- {
- if (function_exists('iconv'))
- {
- do
- {
- $ok = true;
- $text = @iconv('UTF-8', 'UTF-8//TRANSLIT', $s);
- if (strlen($text) != strlen($s))
- {
- // Remove the offending character...
- $s = $text . '.' . substr($s, strlen($text) + 1);
- $ok = false;
- }
- }
- while (!$ok);
- }
- return $s;
- }
-
-}
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/OAuthStoreAnyMeta.php b/vendor/oauth-php/library/store/OAuthStoreAnyMeta.php
deleted file mode 100644
index b619ec0..0000000
--- a/vendor/oauth-php/library/store/OAuthStoreAnyMeta.php
+++ /dev/null
@@ -1,264 +0,0 @@
-<?php
-
-/**
- * Storage container for the oauth credentials, both server and consumer side.
- * This file can only be used in conjunction with anyMeta.
- *
- * @version $Id: OAuthStoreAnyMeta.php 68 2010-01-12 18:59:23Z brunobg@corollarium.com $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Nov 16, 2007 4:03:30 PM
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__) . '/OAuthStoreMySQL.php';
-
-
-class OAuthStoreAnymeta extends OAuthStoreMySQL
-{
- /**
- * Construct the OAuthStoreAnymeta
- *
- * @param array options
- */
- function __construct ( $options = array() )
- {
- parent::__construct(array('conn' => any_db_conn()));
- }
-
-
- /**
- * Add an entry to the log table
- *
- * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token)
- * @param string received
- * @param string sent
- * @param string base_string
- * @param string notes
- * @param int (optional) user_id
- */
- public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null )
- {
- if (is_null($user_id) && isset($GLOBALS['any_auth']))
- {
- $user_id = $GLOBALS['any_auth']->getUserId();
- }
- parent::addLog($keys, $received, $sent, $base_string, $notes, $user_id);
- }
-
-
- /**
- * Get a page of entries from the log. Returns the last 100 records
- * matching the options given.
- *
- * @param array options
- * @param int user_id current user
- * @return array log records
- */
- public function listLog ( $options, $user_id )
- {
- $where = array();
- $args = array();
- if (empty($options))
- {
- $where[] = 'olg_usa_id_ref = %d';
- $args[] = $user_id;
- }
- else
- {
- foreach ($options as $option => $value)
- {
- if (strlen($value) > 0)
- {
- switch ($option)
- {
- case 'osr_consumer_key':
- case 'ocr_consumer_key':
- case 'ost_token':
- case 'oct_token':
- $where[] = 'olg_'.$option.' = \'%s\'';
- $args[] = $value;
- break;
- }
- }
- }
-
- $where[] = '(olg_usa_id_ref IS NULL OR olg_usa_id_ref = %d)';
- $args[] = $user_id;
- }
-
- $rs = any_db_query_all_assoc('
- SELECT olg_id,
- olg_osr_consumer_key AS osr_consumer_key,
- olg_ost_token AS ost_token,
- olg_ocr_consumer_key AS ocr_consumer_key,
- olg_oct_token AS oct_token,
- olg_usa_id_ref AS user_id,
- olg_received AS received,
- olg_sent AS sent,
- olg_base_string AS base_string,
- olg_notes AS notes,
- olg_timestamp AS timestamp,
- INET_NTOA(olg_remote_ip) AS remote_ip
- FROM oauth_log
- WHERE '.implode(' AND ', $where).'
- ORDER BY olg_id DESC
- LIMIT 0,100', $args);
-
- return $rs;
- }
-
-
-
- /**
- * Initialise the database
- */
- public function install ()
- {
- parent::install();
-
- any_db_query("ALTER TABLE oauth_consumer_registry MODIFY ocr_usa_id_ref int(11) unsigned");
- any_db_query("ALTER TABLE oauth_consumer_token MODIFY oct_usa_id_ref int(11) unsigned not null");
- any_db_query("ALTER TABLE oauth_server_registry MODIFY osr_usa_id_ref int(11) unsigned");
- any_db_query("ALTER TABLE oauth_server_token MODIFY ost_usa_id_ref int(11) unsigned not null");
- any_db_query("ALTER TABLE oauth_log MODIFY olg_usa_id_ref int(11) unsigned");
-
- any_db_alter_add_fk('oauth_consumer_registry', 'ocr_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete set null');
- any_db_alter_add_fk('oauth_consumer_token', 'oct_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete cascade');
- any_db_alter_add_fk('oauth_server_registry', 'osr_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete set null');
- any_db_alter_add_fk('oauth_server_token', 'ost_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete cascade');
- any_db_alter_add_fk('oauth_log', 'olg_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete cascade');
- }
-
-
-
- /** Some simple helper functions for querying the mysql db **/
-
- /**
- * Perform a query, ignore the results
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- */
- protected function query ( $sql )
- {
- list($sql, $args) = $this->sql_args(func_get_args());
- any_db_query($sql, $args);
- }
-
-
- /**
- * Perform a query, ignore the results
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_all_assoc ( $sql )
- {
- list($sql, $args) = $this->sql_args(func_get_args());
- return any_db_query_all_assoc($sql, $args);
- }
-
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_row_assoc ( $sql )
- {
- list($sql, $args) = $this->sql_args(func_get_args());
- return any_db_query_row_assoc($sql, $args);
- }
-
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_row ( $sql )
- {
- list($sql, $args) = $this->sql_args(func_get_args());
- return any_db_query_row($sql, $args);
- }
-
-
- /**
- * Perform a query, return the first column of the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return mixed
- */
- protected function query_one ( $sql )
- {
- list($sql, $args) = $this->sql_args(func_get_args());
- return any_db_query_one($sql, $args);
- }
-
-
- /**
- * Return the number of rows affected in the last query
- *
- * @return int
- */
- protected function query_affected_rows ()
- {
- return any_db_affected_rows();
- }
-
-
- /**
- * Return the id of the last inserted row
- *
- * @return int
- */
- protected function query_insert_id ()
- {
- return any_db_insert_id();
- }
-
-
- private function sql_args ( $args )
- {
- $sql = array_shift($args);
- if (count($args) == 1 && is_array($args[0]))
- {
- $args = $args[0];
- }
- return array($sql, $args);
- }
-
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/OAuthStoreMySQL.php b/vendor/oauth-php/library/store/OAuthStoreMySQL.php
deleted file mode 100644
index c568359..0000000
--- a/vendor/oauth-php/library/store/OAuthStoreMySQL.php
+++ /dev/null
@@ -1,245 +0,0 @@
-<?php
-
-/**
- * Storage container for the oauth credentials, both server and consumer side.
- * Based on MySQL
- *
- * @version $Id: OAuthStoreMySQL.php 85 2010-02-19 14:56:40Z brunobg@corollarium.com $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Nov 16, 2007 4:03:30 PM
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-require_once dirname(__FILE__) . '/OAuthStoreSQL.php';
-
-
-class OAuthStoreMySQL extends OAuthStoreSQL
-{
- /**
- * The MySQL connection
- */
- protected $conn;
-
- /**
- * Initialise the database
- */
- public function install ()
- {
- require_once dirname(__FILE__) . '/mysql/install.php';
- }
-
-
- /* ** Some simple helper functions for querying the mysql db ** */
-
- /**
- * Perform a query, ignore the results
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- */
- protected function query ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = mysql_query($sql, $this->conn)))
- {
- $this->sql_errcheck($sql);
- }
- if (is_resource($res))
- {
- mysql_free_result($res);
- }
- }
-
-
- /**
- * Perform a query, ignore the results
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_all_assoc ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = mysql_query($sql, $this->conn)))
- {
- $this->sql_errcheck($sql);
- }
- $rs = array();
- while ($row = mysql_fetch_assoc($res))
- {
- $rs[] = $row;
- }
- mysql_free_result($res);
- return $rs;
- }
-
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_row_assoc ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = mysql_query($sql, $this->conn)))
- {
- $this->sql_errcheck($sql);
- }
- if ($row = mysql_fetch_assoc($res))
- {
- $rs = $row;
- }
- else
- {
- $rs = false;
- }
- mysql_free_result($res);
- return $rs;
- }
-
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_row ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = mysql_query($sql, $this->conn)))
- {
- $this->sql_errcheck($sql);
- }
- if ($row = mysql_fetch_array($res))
- {
- $rs = $row;
- }
- else
- {
- $rs = false;
- }
- mysql_free_result($res);
- return $rs;
- }
-
-
- /**
- * Perform a query, return the first column of the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return mixed
- */
- protected function query_one ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = mysql_query($sql, $this->conn)))
- {
- $this->sql_errcheck($sql);
- }
- $val = @mysql_result($res, 0, 0);
- mysql_free_result($res);
- return $val;
- }
-
-
- /**
- * Return the number of rows affected in the last query
- */
- protected function query_affected_rows ()
- {
- return mysql_affected_rows($this->conn);
- }
-
-
- /**
- * Return the id of the last inserted row
- *
- * @return int
- */
- protected function query_insert_id ()
- {
- return mysql_insert_id($this->conn);
- }
-
-
- protected function sql_printf ( $args )
- {
- $sql = array_shift($args);
- if (count($args) == 1 && is_array($args[0]))
- {
- $args = $args[0];
- }
- $args = array_map(array($this, 'sql_escape_string'), $args);
- return vsprintf($sql, $args);
- }
-
-
- protected function sql_escape_string ( $s )
- {
- if (is_string($s))
- {
- return mysql_real_escape_string($s, $this->conn);
- }
- else if (is_null($s))
- {
- return NULL;
- }
- else if (is_bool($s))
- {
- return intval($s);
- }
- else if (is_int($s) || is_float($s))
- {
- return $s;
- }
- else
- {
- return mysql_real_escape_string(strval($s), $this->conn);
- }
- }
-
-
- protected function sql_errcheck ( $sql )
- {
- if (mysql_errno($this->conn))
- {
- $msg = "SQL Error in OAuthStoreMySQL: ".mysql_error($this->conn)."\n\n" . $sql;
- throw new OAuthException2($msg);
- }
- }
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/OAuthStoreMySQLi.php b/vendor/oauth-php/library/store/OAuthStoreMySQLi.php
deleted file mode 100644
index 09d71bf..0000000
--- a/vendor/oauth-php/library/store/OAuthStoreMySQLi.php
+++ /dev/null
@@ -1,306 +0,0 @@
-<?php
-
-/**
- * Storage container for the oauth credentials, both server and consumer side.
- * Based on MySQL
- *
- * @version $Id: OAuthStoreMySQLi.php 64 2009-08-16 19:37:00Z marcw@pobox.com $
- * @author Bruno Barberi Gnecco <brunobg@users.sf.net> Based on code by Marc Worrell <marcw@pobox.com>
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-/*
- * Modified from OAuthStoreMySQL to support MySQLi
- */
-
-require_once dirname(__FILE__) . '/OAuthStoreMySQL.php';
-
-
-class OAuthStoreMySQLi extends OAuthStoreMySQL
-{
-
- public function install() {
- $sql = file_get_contents(dirname(__FILE__) . '/mysql/mysql.sql');
- $ps = explode('#--SPLIT--', $sql);
-
- foreach ($ps as $p)
- {
- $p = preg_replace('/^\s*#.*$/m', '', $p);
-
- $this->query($p);
- $this->sql_errcheck($p);
- }
- }
-
- /**
- * Construct the OAuthStoreMySQLi.
- * In the options you have to supply either:
- * - server, username, password and database (for a mysqli_connect)
- * - conn (for the connection to be used)
- *
- * @param array options
- */
- function __construct ( $options = array() )
- {
- if (isset($options['conn']))
- {
- $this->conn = $options['conn'];
- }
- else
- {
- if (isset($options['server']))
- {
- $server = $options['server'];
- $username = $options['username'];
-
- if (isset($options['password']))
- {
- $this->conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect($server, $username, $options['password']));
- }
- else
- {
- $this->conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect($server, $username));
- }
- }
- else
- {
- // Try the default mysql connect
- $this->conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect());
- }
-
- if ($this->conn === false)
- {
- throw new OAuthException2('Could not connect to MySQL database: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
- }
-
- if (isset($options['database']))
- {
- /* TODO: security. mysqli_ doesn't seem to have an escape identifier function.
- $escapeddb = mysqli_real_escape_string($options['database']);
- if (!((bool)mysqli_query( $this->conn, "USE `$escapeddb`" )))
- {
- $this->sql_errcheck();
- }*/
- }
- $this->query('set character set utf8');
- }
- }
-
- /**
- * Perform a query, ignore the results
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- */
- protected function query ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = mysqli_query( $this->conn, $sql)))
- {
- $this->sql_errcheck($sql);
- }
- if (!is_bool($res))
- {
- ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false);
- }
- }
-
-
- /**
- * Perform a query, ignore the results
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_all_assoc ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = mysqli_query( $this->conn, $sql)))
- {
- $this->sql_errcheck($sql);
- }
- $rs = array();
- while ($row = mysqli_fetch_assoc($res))
- {
- $rs[] = $row;
- }
- ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false);
- return $rs;
- }
-
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_row_assoc ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = mysqli_query( $this->conn, $sql)))
- {
- $this->sql_errcheck($sql);
- }
- if ($row = mysqli_fetch_assoc($res))
- {
- $rs = $row;
- }
- else
- {
- $rs = false;
- }
- ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false);
- return $rs;
- }
-
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_row ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = mysqli_query( $this->conn, $sql)))
- {
- $this->sql_errcheck($sql);
- }
- if ($row = mysqli_fetch_array($res))
- {
- $rs = $row;
- }
- else
- {
- $rs = false;
- }
- ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false);
- return $rs;
- }
-
-
- /**
- * Perform a query, return the first column of the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return mixed
- */
- protected function query_one ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = mysqli_query( $this->conn, $sql)))
- {
- $this->sql_errcheck($sql);
- }
- if ($row = mysqli_fetch_assoc($res))
- {
- $val = array_pop($row);
- }
- else
- {
- $val = false;
- }
- ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false);
- return $val;
- }
-
-
- /**
- * Return the number of rows affected in the last query
- */
- protected function query_affected_rows ()
- {
- return mysqli_affected_rows($this->conn);
- }
-
-
- /**
- * Return the id of the last inserted row
- *
- * @return int
- */
- protected function query_insert_id ()
- {
- return ((is_null($___mysqli_res = mysqli_insert_id($this->conn))) ? false : $___mysqli_res);
- }
-
-
- protected function sql_printf ( $args )
- {
- $sql = array_shift($args);
- if (count($args) == 1 && is_array($args[0]))
- {
- $args = $args[0];
- }
- $args = array_map(array($this, 'sql_escape_string'), $args);
- return vsprintf($sql, $args);
- }
-
-
- protected function sql_escape_string ( $s )
- {
- if (is_string($s))
- {
- return mysqli_real_escape_string( $this->conn, $s);
- }
- else if (is_null($s))
- {
- return NULL;
- }
- else if (is_bool($s))
- {
- return intval($s);
- }
- else if (is_int($s) || is_float($s))
- {
- return $s;
- }
- else
- {
- return mysqli_real_escape_string( $this->conn, strval($s));
- }
- }
-
-
- protected function sql_errcheck ( $sql )
- {
- if (((is_object($this->conn)) ? mysqli_errno($this->conn) : (($___mysqli_res = mysqli_connect_errno()) ? $___mysqli_res : false)))
- {
- $msg = "SQL Error in OAuthStoreMySQL: ".((is_object($this->conn)) ? mysqli_error($this->conn) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false))."\n\n" . $sql;
- throw new OAuthException2($msg);
- }
- }
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/OAuthStoreOracle.php b/vendor/oauth-php/library/store/OAuthStoreOracle.php
deleted file mode 100644
index ea905a2..0000000
--- a/vendor/oauth-php/library/store/OAuthStoreOracle.php
+++ /dev/null
@@ -1,1541 +0,0 @@
-<?php
-
-/**
- * Added by Vinay Kant Sahu.
- * Replaced all the MySQL queries with Oracle SPs. (ref: OAuthStoreSQL.php)
- * vinaykant.sahu@gmail.com
- *
- * Storage container for the oauth credentials, both server and consumer side.
- * Based on Oracle
- *
- * @author Vinay Kant Sahu <vinaykant.sahu@gmail.com>
- * @date Aug 6, 2010
- *
- * The MIT License
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php';
-
-abstract class OAuthStoreOracle extends OAuthStoreAbstract {
- /**
- * Maximum delta a timestamp may be off from a previous timestamp.
- * Allows multiple consumers with some clock skew to work with the same token.
- * Unit is seconds, default max skew is 10 minutes.
- */
- protected $max_timestamp_skew = MAX_TIMESTAMP_SKEW;
-
- /**
- * Default ttl for request tokens
- */
- protected $max_request_token_ttl = MAX_REQUEST_TOKEN_TIME;
-
-
- /**
- * Construct the OAuthStoreMySQL.
- * In the options you have to supply either:
- * - server, username, password and database (for a mysql_connect)
- * - conn (for the connection to be used)
- *
- * @param array options
- */
- function __construct ( $options = array() ) {
- if (isset($options['conn'])) {
- $this->conn = $options['conn'];
- }
- else {
- $this->conn=oci_connect(DBUSER,DBPASSWORD,DBHOST);
-
- if ($this->conn === false) {
- throw new OAuthException2('Could not connect to database');
- }
-
- // $this->query('set character set utf8');
- }
- }
-
- /**
- * Find stored credentials for the consumer key and token. Used by an OAuth server
- * when verifying an OAuth request.
- *
- * @param string consumer_key
- * @param string token
- * @param string token_type false, 'request' or 'access'
- * @exception OAuthException2 when no secrets where found
- * @return array assoc (consumer_secret, token_secret, osr_id, ost_id, user_id)
- */
- public function getSecretsForVerify ($consumer_key, $token, $token_type = 'access' ) {
- $sql = "BEGIN SP_GET_SECRETS_FOR_VERIFY(:P_CONSUMER_KEY, :P_TOKEN, :P_TOKEN_TYPE, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_TOKEN_TYPE', $token_type, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $getSecretsForVerifyList, null, null, OCI_FETCHSTATEMENT_BY_ROW);
-
- $rs =$getSecretsForVerifyList;
- if (empty($rs)) {
- throw new OAuthException2('The consumer_key "'.$consumer_key.'" token "'.$token.'" combination does not exist or is not enabled.');
- }
-
- return $rs[0];
- }
-
-
- /**
- * Find the server details for signing a request, always looks for an access token.
- * The returned credentials depend on which local user is making the request.
- *
- * The consumer_key must belong to the user or be public (user id is null)
- *
- * For signing we need all of the following:
- *
- * consumer_key consumer key associated with the server
- * consumer_secret consumer secret associated with this server
- * token access token associated with this server
- * token_secret secret for the access token
- * signature_methods signing methods supported by the server (array)
- *
- * @todo filter on token type (we should know how and with what to sign this request, and there might be old access tokens)
- * @param string uri uri of the server
- * @param int user_id id of the logged on user
- * @param string name (optional) name of the token (case sensitive)
- * @exception OAuthException2 when no credentials found
- * @return array
- */
- public function getSecretsForSignature ( $uri, $user_id, $name = '' ) {
- // Find a consumer key and token for the given uri
- $ps = parse_url($uri);
- $host = isset($ps['host']) ? $ps['host'] : 'localhost';
- $path = isset($ps['path']) ? $ps['path'] : '';
-
- if (empty($path) || substr($path, -1) != '/') {
- $path .= '/';
- }
- //
- $sql = "BEGIN SP_GET_SECRETS_FOR_SIGNATURE(:P_HOST, :P_PATH, :P_USER_ID, :P_NAME, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_HOST', $host, 255);
- oci_bind_by_name($stmt, ':P_PATH', $path, 255);
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 20);
- oci_bind_by_name($stmt, ':P_NAME', $name, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $getSecretsForSignatureList, null, null, OCI_FETCHSTATEMENT_BY_ROW);
- $secrets = $getSecretsForSignatureList[0];
- //
- // The owner of the consumer_key is either the user or nobody (public consumer key)
- /*$secrets = $this->query_row_assoc('
- SELECT ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- oct_token as token,
- oct_token_secret as token_secret,
- ocr_signature_methods as signature_methods
- FROM oauth_consumer_registry
- JOIN oauth_consumer_token ON oct_ocr_id_ref = ocr_id
- WHERE ocr_server_uri_host = \'%s\'
- AND ocr_server_uri_path = LEFT(\'%s\', LENGTH(ocr_server_uri_path))
- AND (ocr_usa_id_ref = %s OR ocr_usa_id_ref IS NULL)
- AND oct_usa_id_ref = %d
- AND oct_token_type = \'access\'
- AND oct_name = \'%s\'
- AND oct_token_ttl >= NOW()
- ORDER BY ocr_usa_id_ref DESC, ocr_consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC
- LIMIT 0,1
- ', $host, $path, $user_id, $user_id, $name
- );
- */
- if (empty($secrets)) {
- throw new OAuthException2('No server tokens available for '.$uri);
- }
- $secrets['signature_methods'] = explode(',', $secrets['signature_methods']);
- return $secrets;
- }
-
-
- /**
- * Get the token and token secret we obtained from a server.
- *
- * @param string consumer_key
- * @param string token
- * @param string token_type
- * @param int user_id the user owning the token
- * @param string name optional name for a named token
- * @exception OAuthException2 when no credentials found
- * @return array
- */
- public function getServerTokenSecrets ($consumer_key,$token,$token_type,$user_id,$name = '')
- {
- if ($token_type != 'request' && $token_type != 'access')
- {
- throw new OAuthException2('Unkown token type "'.$token_type.'", must be either "request" or "access"');
- }
- //
- $sql = "BEGIN SP_GET_SERVER_TOKEN_SECRETS(:P_CONSUMER_KEY, :P_TOKEN, :P_TOKEN_TYPE, :P_USER_ID, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_TOKEN_TYPE', $token_type, 20);
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $getServerTokenSecretsList, null, null, OCI_FETCHSTATEMENT_BY_ROW);
- $r=$getServerTokenSecretsList[0];
- //
- // Take the most recent token of the given type
- /*$r = $this->query_row_assoc('
- SELECT ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- oct_token as token,
- oct_token_secret as token_secret,
- oct_name as token_name,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri,
- IF(oct_token_ttl >= \'9999-12-31\', NULL, UNIX_TIMESTAMP(oct_token_ttl) - UNIX_TIMESTAMP(NOW())) as token_ttl
- FROM oauth_consumer_registry
- JOIN oauth_consumer_token
- ON oct_ocr_id_ref = ocr_id
- WHERE ocr_consumer_key = \'%s\'
- AND oct_token_type = \'%s\'
- AND oct_token = \'%s\'
- AND oct_usa_id_ref = %d
- AND oct_token_ttl >= NOW()
- ', $consumer_key, $token_type, $token, $user_id
- );*/
-
- if (empty($r))
- {
- throw new OAuthException2('Could not find a "'.$token_type.'" token for consumer "'.$consumer_key.'" and user '.$user_id);
- }
- if (isset($r['signature_methods']) && !empty($r['signature_methods']))
- {
- $r['signature_methods'] = explode(',',$r['signature_methods']);
- }
- else
- {
- $r['signature_methods'] = array();
- }
- return $r;
- }
-
-
- /**
- * Add a request token we obtained from a server.
- *
- * @todo remove old tokens for this user and this ocr_id
- * @param string consumer_key key of the server in the consumer registry
- * @param string token_type one of 'request' or 'access'
- * @param string token
- * @param string token_secret
- * @param int user_id the user owning the token
- * @param array options extra options, name and token_ttl
- * @exception OAuthException2 when server is not known
- * @exception OAuthException2 when we received a duplicate token
- */
- public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() )
- {
- if ($token_type != 'request' && $token_type != 'access')
- {
- throw new OAuthException2('Unknown token type "'.$token_type.'", must be either "request" or "access"');
- }
-
- // Maximum time to live for this token
- if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
- {
- $ttl = intval($options['token_ttl']);
- }
- else if ($token_type == 'request')
- {
- $ttl =intval($this->max_request_token_ttl);
- }
- else
- {
- $ttl = NULL;
- }
-
-
-
- // Named tokens, unique per user/consumer key
- if (isset($options['name']) && $options['name'] != '')
- {
- $name = $options['name'];
- }
- else
- {
- $name = '';
- }
- //
- $sql = "BEGIN SP_ADD_SERVER_TOKEN(:P_CONSUMER_KEY, :P_USER_ID, :P_NAME, :P_TOKEN_TYPE, :P_TOKEN, :P_TOKEN_SECRET, :P_TOKEN_INTERVAL_IN_SEC, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40);
- oci_bind_by_name($stmt, ':P_NAME', $name, 255);
- oci_bind_by_name($stmt, ':P_TOKEN_TYPE', $token_type, 20);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_TOKEN_SECRET', $token_secret, 255);
- oci_bind_by_name($stmt, ':P_TOKEN_INTERVAL_IN_SEC', $ttl, 40);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
- //
-
-
-
- if (!$result)
- {
- throw new OAuthException2('Received duplicate token "'.$token.'" for the same consumer_key "'.$consumer_key.'"');
- }
- }
-
-
- /**
- * Delete a server key. This removes access to that site.
- *
- * @param string consumer_key
- * @param int user_id user registering this server
- * @param boolean user_is_admin
- */
- public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false )
- {
-
- $sql = "BEGIN SP_DELETE_SERVER(:P_CONSUMER_KEY, :P_USER_ID, :P_USER_IS_ADMIN, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40);
- oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
- }
-
-
- /**
- * Get a server from the consumer registry using the consumer key
- *
- * @param string consumer_key
- * @param int user_id
- * @param boolean user_is_admin (optional)
- * @exception OAuthException2 when server is not found
- * @return array
- */
- public function getServer ( $consumer_key, $user_id, $user_is_admin = false )
- {
-
- //
- $sql = "BEGIN SP_GET_SERVER(:P_CONSUMER_KEY, :P_USER_ID, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $getServerList, null, null, OCI_FETCHSTATEMENT_BY_ROW);
- $r = $getServerList;
- //
- if (empty($r))
- {
- throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" has been registered (for this user)');
- }
-
- if (isset($r['signature_methods']) && !empty($r['signature_methods']))
- {
- $r['signature_methods'] = explode(',',$r['signature_methods']);
- }
- else
- {
- $r['signature_methods'] = array();
- }
- return $r;
- }
-
-
-
- /**
- * Find the server details that might be used for a request
- *
- * The consumer_key must belong to the user or be public (user id is null)
- *
- * @param string uri uri of the server
- * @param int user_id id of the logged on user
- * @exception OAuthException2 when no credentials found
- * @return array
- */
- public function getServerForUri ( $uri, $user_id )
- {
- // Find a consumer key and token for the given uri
- $ps = parse_url($uri);
- $host = isset($ps['host']) ? $ps['host'] : 'localhost';
- $path = isset($ps['path']) ? $ps['path'] : '';
-
- if (empty($path) || substr($path, -1) != '/')
- {
- $path .= '/';
- }
-
-
- //
- $sql = "BEGIN SP_GET_SERVER_FOR_URI(:P_HOST, :P_PATH,:P_USER_ID, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_HOST', $host, 255);
- oci_bind_by_name($stmt, ':P_PATH', $path, 255);
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $getServerForUriList, null, null, OCI_FETCHSTATEMENT_BY_ROW);
- $server = $getServerForUriList;
- //
- if (empty($server))
- {
- throw new OAuthException2('No server available for '.$uri);
- }
- $server['signature_methods'] = explode(',', $server['signature_methods']);
- return $server;
- }
-
-
- /**
- * Get a list of all server token this user has access to.
- *
- * @param int usr_id
- * @return array
- */
- public function listServerTokens ( $user_id )
- {
-
- $sql = "BEGIN SP_LIST_SERVER_TOKENS(:P_USER_ID, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $listServerTokensList, null, null, OCI_FETCHSTATEMENT_BY_ROW);
- $ts = $listServerTokensList;
- return $ts;
- }
-
-
- /**
- * Count how many tokens we have for the given server
- *
- * @param string consumer_key
- * @return int
- */
- public function countServerTokens ( $consumer_key )
- {
-
- //
- $count =0;
- $sql = "BEGIN SP_COUNT_SERVICE_TOKENS(:P_CONSUMER_KEY, :P_COUNT, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_COUNT', $count, 40);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
- //
- return $count;
- }
-
-
- /**
- * Get a specific server token for the given user
- *
- * @param string consumer_key
- * @param string token
- * @param int user_id
- * @exception OAuthException2 when no such token found
- * @return array
- */
- public function getServerToken ( $consumer_key, $token, $user_id )
- {
-
- $sql = "BEGIN SP_GET_SERVER_TOKEN(:P_CONSUMER_KEY, :P_USER_ID,:P_TOKEN, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $getServerTokenList, null, null, OCI_FETCHSTATEMENT_BY_ROW);
- $ts = $getServerTokenList;
- //
-
- if (empty($ts))
- {
- throw new OAuthException2('No such consumer key ('.$consumer_key.') and token ('.$token.') combination for user "'.$user_id.'"');
- }
- return $ts;
- }
-
-
- /**
- * Delete a token we obtained from a server.
- *
- * @param string consumer_key
- * @param string token
- * @param int user_id
- * @param boolean user_is_admin
- */
- public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false )
- {
-
- //
- $sql = "BEGIN SP_DELETE_SERVER_TOKEN(:P_CONSUMER_KEY, :P_USER_ID,:P_TOKEN, :P_USER_IS_ADMIN, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 40);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
- //
-
- }
-
-
- /**
- * Set the ttl of a server access token. This is done when the
- * server receives a valid request with a xoauth_token_ttl parameter in it.
- *
- * @param string consumer_key
- * @param string token
- * @param int token_ttl
- */
- public function setServerTokenTtl ( $consumer_key, $token, $token_ttl, $server_uri = NULL )
- {
- if ($token_ttl <= 0)
- {
- // Immediate delete when the token is past its ttl
- $this->deleteServerToken($consumer_key, $token, 0, true);
- }
- else if ( $server_uri )
- {
- // TODO
- throw new OAuthException2('server_uri not implemented in Oracle yet, sorry');
- }
- else
- {
- // Set maximum time to live for this token
-
- //
- $sql = "BEGIN SP_SET_SERVER_TOKEN_TTL(:P_TOKEN_TTL, :P_CONSUMER_KEY, :P_TOKEN, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_TOKEN_TTL', $token_ttl, 40);
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
-//
- }
- }
-
-
- /**
- * Get a list of all consumers from the consumer registry.
- * The consumer keys belong to the user or are public (user id is null)
- *
- * @param string q query term
- * @param int user_id
- * @return array
- */
- public function listServers ( $q = '', $user_id )
- {
- $q = trim(str_replace('%', '', $q));
- $args = array();
-
-
- //
- $sql = "BEGIN SP_LIST_SERVERS(:P_Q, :P_USER_ID, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_Q', $q, 255);
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $listServersList, null, null, OCI_FETCHSTATEMENT_BY_ROW);
- $servers = $listServersList;
- //
-
- return $servers;
- }
-
-
- /**
- * Register or update a server for our site (we will be the consumer)
- *
- * (This is the registry at the consumers, registering servers ;-) )
- *
- * @param array server
- * @param int user_id user registering this server
- * @param boolean user_is_admin
- * @exception OAuthException2 when fields are missing or on duplicate consumer_key
- * @return consumer_key
- */
- public function updateServer ( $server, $user_id, $user_is_admin = false ) {
- foreach (array('consumer_key', 'server_uri') as $f) {
- if (empty($server[$f])) {
- throw new OAuthException2('The field "'.$f.'" must be set and non empty');
- }
- }
- $parts = parse_url($server['server_uri']);
- $host = (isset($parts['host']) ? $parts['host'] : 'localhost');
- $path = (isset($parts['path']) ? $parts['path'] : '/');
-
- if (isset($server['signature_methods'])) {
- if (is_array($server['signature_methods'])) {
- $server['signature_methods'] = strtoupper(implode(',', $server['signature_methods']));
- }
- }
- else {
- $server['signature_methods'] = '';
- }
- // When the user is an admin, then the user can update the user_id of this record
- if ($user_is_admin && array_key_exists('user_id', $server)) {
- $flag=1;
- }
- if($flag) {
- if (is_null($server['user_id'])) {
- $ocr_usa_id_ref= NULL;
- }
- else {
- $ocr_usa_id_ref = $server['user_id'];
- }
- }
- else {
- $flag=0;
- $ocr_usa_id_ref=$user_id;
- }
- //sp
- $sql = "BEGIN SP_UPDATE_SERVER(:P_CONSUMER_KEY, :P_USER_ID, :P_OCR_ID, :P_USER_IS_ADMIN,
- :P_OCR_CONSUMER_SECRET, :P_OCR_SERVER_URI, :P_OCR_SERVER_URI_HOST, :P_OCR_SERVER_URI_PATH,
- :P_OCR_REQUEST_TOKEN_URI, :P_OCR_AUTHORIZE_URI, :P_OCR_ACCESS_TOKEN_URI, :P_OCR_SIGNATURE_METHODS,
- :P_OCR_USA_ID_REF, :P_UPDATE_P_OCR_USA_ID_REF_FLAG, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
- $server['request_token_uri'] = isset($server['request_token_uri']) ? $server['request_token_uri'] : '';
- $server['authorize_uri'] = isset($server['authorize_uri']) ? $server['authorize_uri'] : '';
- $server['access_token_uri'] = isset($server['access_token_uri']) ? $server['access_token_uri'] : '';
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $server['consumer_key'], 255);
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40);
- oci_bind_by_name($stmt, ':P_OCR_ID', $server['id'], 40);
- oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 40);
- oci_bind_by_name($stmt, ':P_OCR_CONSUMER_SECRET', $server['consumer_secret'], 255);
- oci_bind_by_name($stmt, ':P_OCR_SERVER_URI', $server['server_uri'], 255);
- oci_bind_by_name($stmt, ':P_OCR_SERVER_URI_HOST', strtolower($host), 255);
- oci_bind_by_name($stmt, ':P_OCR_SERVER_URI_PATH', $path, 255);
- oci_bind_by_name($stmt, ':P_OCR_REQUEST_TOKEN_URI', $server['request_token_uri'], 255);
- oci_bind_by_name($stmt, ':P_OCR_AUTHORIZE_URI', $server['authorize_uri'], 255);
- oci_bind_by_name($stmt, ':P_OCR_ACCESS_TOKEN_URI', $server['access_token_uri'], 255);
- oci_bind_by_name($stmt, ':P_OCR_SIGNATURE_METHODS', $server['signature_methods'], 255);
- oci_bind_by_name($stmt, ':P_OCR_USA_ID_REF', $ocr_usa_id_ref, 40);
- oci_bind_by_name($stmt, ':P_UPDATE_P_OCR_USA_ID_REF_FLAG', $flag, 40);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
-
- return $server['consumer_key'];
- }
-
- /**
- * Insert/update a new consumer with this server (we will be the server)
- * When this is a new consumer, then also generate the consumer key and secret.
- * Never updates the consumer key and secret.
- * When the id is set, then the key and secret must correspond to the entry
- * being updated.
- *
- * (This is the registry at the server, registering consumers ;-) )
- *
- * @param array consumer
- * @param int user_id user registering this consumer
- * @param boolean user_is_admin
- * @return string consumer key
- */
- public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) {
- $consumer_key = $this->generateKey(true);
- $consumer_secret = $this->generateKey();
-
- $consumer['callback_uri'] = isset($consumer['callback_uri'])? $consumer['callback_uri']: '';
- $consumer['application_uri'] = isset($consumer['application_uri'])? $consumer['application_uri']: '';
- $consumer['application_title'] = isset($consumer['application_title'])? $consumer['application_title']: '';
- $consumer['application_descr'] = isset($consumer['application_descr'])? $consumer['application_descr']: '';
- $consumer['application_notes'] = isset($consumer['application_notes'])? $consumer['application_notes']: '';
- $consumer['application_type'] = isset($consumer['application_type'])? $consumer['application_type']: '';
- $consumer['application_commercial'] = isset($consumer['application_commercial'])?$consumer['application_commercial']:0;
-
- //sp
- $sql = "BEGIN SP_UPDATE_CONSUMER(:P_OSR_USA_ID_REF, :P_OSR_CONSUMER_KEY, :P_OSR_CONSUMER_SECRET, :P_OSR_REQUESTER_NAME, :P_OSR_REQUESTER_EMAIL, :P_OSR_CALLBACK_URI, :P_OSR_APPLICATION_URI, :P_OSR_APPLICATION_TITLE , :P_OSR_APPLICATION_DESCR, :P_OSR_APPLICATION_NOTES, :P_OSR_APPLICATION_TYPE, :P_OSR_APPLICATION_COMMERCIAL, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_OSR_USA_ID_REF', $user_id, 40);
- oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_OSR_CONSUMER_SECRET', $consumer_secret, 255);
- oci_bind_by_name($stmt, ':P_OSR_REQUESTER_NAME', $consumer['requester_name'], 255);
- oci_bind_by_name($stmt, ':P_OSR_REQUESTER_EMAIL', $consumer['requester_email'], 255);
- oci_bind_by_name($stmt, ':P_OSR_CALLBACK_URI', $consumer['callback_uri'], 255);
- oci_bind_by_name($stmt, ':P_OSR_APPLICATION_URI', $consumer['application_uri'], 255);
- oci_bind_by_name($stmt, ':P_OSR_APPLICATION_TITLE', $consumer['application_title'], 255);
- oci_bind_by_name($stmt, ':P_OSR_APPLICATION_DESCR', $consumer['application_descr'], 255);
- oci_bind_by_name($stmt, ':P_OSR_APPLICATION_NOTES', $consumer['application_notes'], 255);
- oci_bind_by_name($stmt, ':P_OSR_APPLICATION_TYPE', $consumer['application_type'], 255);
- oci_bind_by_name($stmt, ':P_OSR_APPLICATION_COMMERCIAL', $consumer['application_commercial'], 40);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
- echo $result;
- return $consumer_key;
- }
-
-
-
- /**
- * Delete a consumer key. This removes access to our site for all applications using this key.
- *
- * @param string consumer_key
- * @param int user_id user registering this server
- * @param boolean user_is_admin
- */
- public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false )
- {
-
- //
- $sql = "BEGIN SP_DELETE_CONSUMER(:P_CONSUMER_KEY, :P_USER_ID, :P_USER_IS_ADMIN, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40);
- oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 40);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
- //
- }
-
-
-
- /**
- * Fetch a consumer of this server, by consumer_key.
- *
- * @param string consumer_key
- * @param int user_id
- * @param boolean user_is_admin (optional)
- * @exception OAuthException2 when consumer not found
- * @return array
- */
- public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) {
-
- $sql = "BEGIN SP_GET_CONSUMER(:P_CONSUMER_KEY, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $getConsumerList, null, null, OCI_FETCHSTATEMENT_BY_ROW);
-
- $consumer = $getConsumerList;
-
- if (!is_array($consumer)) {
- throw new OAuthException2('No consumer with consumer_key "'.$consumer_key.'"');
- }
-
- $c = array();
- foreach ($consumer as $key => $value) {
- $c[substr($key, 4)] = $value;
- }
- $c['user_id'] = $c['usa_id_ref'];
-
- if (!$user_is_admin && !empty($c['user_id']) && $c['user_id'] != $user_id) {
- throw new OAuthException2('No access to the consumer information for consumer_key "'.$consumer_key.'"');
- }
- return $c;
- }
-
-
- /**
- * Fetch the static consumer key for this provider. The user for the static consumer
- * key is NULL (no user, shared key). If the key did not exist then the key is created.
- *
- * @return string
- */
- public function getConsumerStatic ()
- {
-
- //
- $sql = "BEGIN SP_GET_CONSUMER_STATIC_SELECT(:P_OSR_CONSUMER_KEY, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $consumer, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
-
- if (empty($consumer))
- {
- $consumer_key = 'sc-'.$this->generateKey(true);
-
- $sql = "BEGIN SP_CONSUMER_STATIC_SAVE(:P_OSR_CONSUMER_KEY, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
-
-
- // Just make sure that if the consumer key is truncated that we get the truncated string
- $consumer = $consumer_key;
- }
- return $consumer;
- }
-
-
- /**
- * Add an unautorized request token to our server.
- *
- * @param string consumer_key
- * @param array options (eg. token_ttl)
- * @return array (token, token_secret)
- */
- public function addConsumerRequestToken ( $consumer_key, $options = array() )
- {
- $token = $this->generateKey(true);
- $secret = !isset($options['secret']) ? $this->generateKey() : $options['secret'];
-
-
- if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
- {
- $ttl = intval($options['token_ttl']);
- }
- else
- {
- $ttl = $this->max_request_token_ttl;
- }
-
- if (!isset($options['oauth_callback'])) {
- // 1.0a Compatibility : store callback url associated with request token
- $options['oauth_callback']='oob';
- }
- $options_oauth_callback =$options['oauth_callback'];
- $sql = "BEGIN SP_ADD_CONSUMER_REQUEST_TOKEN(:P_TOKEN_TTL, :P_CONSUMER_KEY, :P_TOKEN, :P_TOKEN_SECRET, :P_CALLBACK_URL, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_TOKEN_TTL', $ttl, 20);
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_TOKEN_SECRET', $secret, 255);
- oci_bind_by_name($stmt, ':P_CALLBACK_URL', $options_oauth_callback, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
-
-
- $returnArray= array('token'=>$token, 'token_secret'=>$secret, 'token_ttl'=>$ttl);
- return $returnArray;
- }
-
-
- /**
- * Fetch the consumer request token, by request token.
- *
- * @param string token
- * @return array token and consumer details
- */
- public function getConsumerRequestToken ( $token )
- {
-
- $sql = "BEGIN SP_GET_CONSUMER_REQUEST_TOKEN(:P_TOKEN, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
-
- oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW);
-
- return $rs[0];
- }
-
-
- /**
- * Delete a consumer token. The token must be a request or authorized token.
- *
- * @param string token
- */
- public function deleteConsumerRequestToken ( $token )
- {
-
- $sql = "BEGIN SP_DEL_CONSUMER_REQUEST_TOKEN(:P_TOKEN, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Execute the statement
- oci_execute($stmt);
- }
-
-
- /**
- * Upgrade a request token to be an authorized request token.
- *
- * @param string token
- * @param int user_id user authorizing the token
- * @param string referrer_host used to set the referrer host for this token, for user feedback
- */
- public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' )
- {
- // 1.0a Compatibility : create a token verifier
- $verifier = substr(md5(rand()),0,10);
-
- $sql = "BEGIN SP_AUTH_CONSUMER_REQ_TOKEN(:P_USER_ID, :P_REFERRER_HOST, :P_VERIFIER, :P_TOKEN, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255);
- oci_bind_by_name($stmt, ':P_REFERRER_HOST', $referrer_host, 255);
- oci_bind_by_name($stmt, ':P_VERIFIER', $verifier, 255);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
-
- //Execute the statement
- oci_execute($stmt);
-
- return $verifier;
- }
-
-
- /**
- * Count the consumer access tokens for the given consumer.
- *
- * @param string consumer_key
- * @return int
- */
- public function countConsumerAccessTokens ( $consumer_key )
- {
- /*$count = $this->query_one('
- SELECT COUNT(ost_id)
- FROM oauth_server_token
- JOIN oauth_server_registry
- ON ost_osr_id_ref = osr_id
- WHERE ost_token_type = \'access\'
- AND osr_consumer_key = \'%s\'
- AND ost_token_ttl >= NOW()
- ', $consumer_key);
- */
- $sql = "BEGIN SP_COUNT_CONSUMER_ACCESS_TOKEN(:P_CONSUMER_KEY, :P_COUNT, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_COUNT', $count, 20);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
-
- //Execute the statement
- oci_execute($stmt);
-
- return $count;
- }
-
-
- /**
- * Exchange an authorized request token for new access token.
- *
- * @param string token
- * @param array options options for the token, token_ttl
- * @exception OAuthException2 when token could not be exchanged
- * @return array (token, token_secret)
- */
- public function exchangeConsumerRequestForAccessToken ( $token, $options = array() )
- {
- $new_token = $this->generateKey(true);
- $new_secret = $this->generateKey();
-
- $sql = "BEGIN SP_EXCH_CONS_REQ_FOR_ACC_TOKEN(:P_TOKEN_TTL, :P_NEW_TOKEN, :P_TOKEN, :P_TOKEN_SECRET, :P_VERIFIER, :P_OUT_TOKEN_TTL, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_TOKEN_TTL', $options['token_ttl'], 255);
- oci_bind_by_name($stmt, ':P_NEW_TOKEN', $new_token, 255);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_TOKEN_SECRET', $new_secret, 255);
- oci_bind_by_name($stmt, ':P_VERIFIER', $options['verifier'], 255);
- oci_bind_by_name($stmt, ':P_OUT_TOKEN_TTL', $ttl, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
-
- //Execute the statement
- oci_execute($stmt);
-
- $ret = array('token' => $new_token, 'token_secret' => $new_secret);
- if (is_numeric($ttl))
- {
- $ret['token_ttl'] = intval($ttl);
- }
- return $ret;
- }
-
-
- /**
- * Fetch the consumer access token, by access token.
- *
- * @param string token
- * @param int user_id
- * @exception OAuthException2 when token is not found
- * @return array token and consumer details
- */
- public function getConsumerAccessToken ( $token, $user_id )
- {
-
- $sql = "BEGIN SP_GET_CONSUMER_ACCESS_TOKEN(:P_USER_ID, :P_TOKEN, :P_ROWS :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_USER_ID',$user_id, 255);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW);
- if (empty($rs))
- {
- throw new OAuthException2('No server_token "'.$token.'" for user "'.$user_id.'"');
- }
- return $rs;
- }
-
-
- /**
- * Delete a consumer access token.
- *
- * @param string token
- * @param int user_id
- * @param boolean user_is_admin
- */
- public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false )
- {
- /*if ($user_is_admin)
- {
- $this->query('
- DELETE FROM oauth_server_token
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'access\'
- ', $token);
- }
- else
- {
- $this->query('
- DELETE FROM oauth_server_token
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'access\'
- AND ost_usa_id_ref = %d
- ', $token, $user_id);
- }*/
- $sql = "BEGIN SP_DEL_CONSUMER_ACCESS_TOKEN(:P_USER_ID, :P_TOKEN, :P_USER_IS_ADMIN, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 20);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
-
- //Execute the statement
- oci_execute($stmt);
- }
-
-
- /**
- * Set the ttl of a consumer access token. This is done when the
- * server receives a valid request with a xoauth_token_ttl parameter in it.
- *
- * @param string token
- * @param int ttl
- */
- public function setConsumerAccessTokenTtl ( $token, $token_ttl )
- {
- if ($token_ttl <= 0)
- {
- // Immediate delete when the token is past its ttl
- $this->deleteConsumerAccessToken($token, 0, true);
- }
- else
- {
- // Set maximum time to live for this token
-
-
- $sql = "BEGIN SP_SET_CONSUMER_ACC_TOKEN_TTL(:P_TOKEN, :P_TOKEN_TTL, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_TOKEN_TTL', $token_ttl, 20);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
-
- //Execute the statement
- oci_execute($stmt);
- }
- }
-
-
- /**
- * Fetch a list of all consumer keys, secrets etc.
- * Returns the public (user_id is null) and the keys owned by the user
- *
- * @param int user_id
- * @return array
- */
- public function listConsumers ( $user_id )
- {
-
- $sql = "BEGIN SP_LIST_CONSUMERS(:P_USER_ID, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW);
-
- return $rs;
- }
-
- /**
- * List of all registered applications. Data returned has not sensitive
- * information and therefore is suitable for public displaying.
- *
- * @param int $begin
- * @param int $total
- * @return array
- */
- public function listConsumerApplications($begin = 0, $total = 25)
- {
- // TODO
- return array();
- }
-
- /**
- * Fetch a list of all consumer tokens accessing the account of the given user.
- *
- * @param int user_id
- * @return array
- */
- public function listConsumerTokens ( $user_id )
- {
-
- $sql = "BEGIN SP_LIST_CONSUMER_TOKENS(:P_USER_ID, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW);
-
- return $rs;
- }
-
-
- /**
- * Check an nonce/timestamp combination. Clears any nonce combinations
- * that are older than the one received.
- *
- * @param string consumer_key
- * @param string token
- * @param int timestamp
- * @param string nonce
- * @exception OAuthException2 thrown when the timestamp is not in sequence or nonce is not unique
- */
- public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce )
- {
-
- $sql = "BEGIN SP_CHECK_SERVER_NONCE(:P_CONSUMER_KEY, :P_TOKEN, :P_TIMESTAMP, :P_MAX_TIMESTAMP_SKEW, :P_NONCE, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255);
- oci_bind_by_name($stmt, ':P_TOKEN', $token, 255);
- oci_bind_by_name($stmt, ':P_TIMESTAMP', $timestamp, 255);
- oci_bind_by_name($stmt, ':P_MAX_TIMESTAMP_SKEW', $this->max_timestamp_skew, 20);
- oci_bind_by_name($stmt, ':P_NONCE', $nonce, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
-
- //Execute the statement
- oci_execute($stmt);
-
- }
-
-
- /**
- * Add an entry to the log table
- *
- * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token)
- * @param string received
- * @param string sent
- * @param string base_string
- * @param string notes
- * @param int (optional) user_id
- */
- public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null )
- {
- $args = array();
- $ps = array();
- foreach ($keys as $key => $value)
- {
- $args[] = $value;
- $ps[] = "olg_$key = '%s'";
- }
-
- if (!empty($_SERVER['REMOTE_ADDR']))
- {
- $remote_ip = $_SERVER['REMOTE_ADDR'];
- }
- else if (!empty($_SERVER['REMOTE_IP']))
- {
- $remote_ip = $_SERVER['REMOTE_IP'];
- }
- else
- {
- $remote_ip = '0.0.0.0';
- }
-
- // Build the SQL
- $olg_received = $this->makeUTF8($received);
- $olg_sent = $this->makeUTF8($sent);
- $olg_base_string = $base_string;
- $olg_notes = $this->makeUTF8($notes);
- $olg_usa_id_ref = $user_id;
- $olg_remote_ip = $remote_ip;
-
-
-
- $sql = "BEGIN SP_ADD_LOG(:P_RECEIVED, :P_SENT, :P_BASE_STRING, :P_NOTES, :P_USA_ID_REF, :P_REMOTE_IP, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_RECEIVED', $olg_received, 255);
- oci_bind_by_name($stmt, ':P_SENT', $olg_sent, 255);
- oci_bind_by_name($stmt, ':P_BASE_STRING', $olg_base_string, 255);
- oci_bind_by_name($stmt, ':P_NOTES', $olg_notes, 255);
- oci_bind_by_name($stmt, ':P_USA_ID_REF', $olg_usa_id_ref, 255);
- oci_bind_by_name($stmt, ':P_REMOTE_IP', $olg_remote_ip, 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
-
- //Execute the statement
- oci_execute($stmt);
- }
-
-
- /**
- * Get a page of entries from the log. Returns the last 100 records
- * matching the options given.
- *
- * @param array options
- * @param int user_id current user
- * @return array log records
- */
- public function listLog ( $options, $user_id )
- {
-
- if (empty($options))
- {
- $optionsFlag=NULL;
-
- }
- else
- {
- $optionsFlag=1;
-
- }
-
- $sql = "BEGIN SP_LIST_LOG(:P_OPTION_FLAG, :P_USA_ID, :P_OSR_CONSUMER_KEY, :P_OCR_CONSUMER_KEY, :P_OST_TOKEN, :P_OCT_TOKEN, :P_ROWS, :P_RESULT); END;";
-
- // parse sql
- $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query');
-
- // Bind In and Out Variables
- oci_bind_by_name($stmt, ':P_OPTION_FLAG', $optionsFlag, 255);
- oci_bind_by_name($stmt, ':P_USA_ID', $user_id, 40);
- oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $options['osr_consumer_key'], 255);
- oci_bind_by_name($stmt, ':P_OCR_CONSUMER_KEY', $options['ocr_consumer_key'], 255);
- oci_bind_by_name($stmt, ':P_OST_TOKEN', $options['ost_token'], 255);
- oci_bind_by_name($stmt, ':P_OCT_TOKEN', $options['oct_token'], 255);
- oci_bind_by_name($stmt, ':P_RESULT', $result, 20);
-
- //Bind the ref cursor
- $p_row = oci_new_cursor($this->conn);
- oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR);
-
- //Execute the statement
- oci_execute($stmt);
-
- // treat the ref cursor as a statement resource
- oci_execute($p_row, OCI_DEFAULT);
- oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW);
-
- return $rs;
- }
-
- /**
- * Initialise the database
- */
- public function install ()
- {
- require_once dirname(__FILE__) . '/oracle/install.php';
- }
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/OAuthStorePDO.php b/vendor/oauth-php/library/store/OAuthStorePDO.php
deleted file mode 100644
index aa3a1b9..0000000
--- a/vendor/oauth-php/library/store/OAuthStorePDO.php
+++ /dev/null
@@ -1,274 +0,0 @@
-<?php
-
-/**
- * Storage container for the oauth credentials, both server and consumer side.
- * Based on MySQL
- *
- * @version $Id: OAuthStorePDO.php 64 2009-08-16 19:37:00Z marcw@pobox.com $
- * @author Bruno Barberi Gnecco <brunobg@users.sf.net> Based on code by Marc Worrell <marcw@pobox.com>
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__) . '/OAuthStoreSQL.php';
-
-
-class OAuthStorePDO extends OAuthStoreSQL
-{
- private $conn; // PDO connection
- private $lastaffectedrows;
-
- /**
- * Construct the OAuthStorePDO.
- * In the options you have to supply either:
- * - dsn, username, password and database (for a new PDO connection)
- * - conn (for the connection to be used)
- *
- * @param array options
- */
- function __construct ( $options = array() )
- {
- if (isset($options['conn']))
- {
- $this->conn = $options['conn'];
- }
- else if (isset($options['dsn']))
- {
- try
- {
- $this->conn = new PDO($options['dsn'], $options['username'], @$options['password']);
- }
- catch (PDOException $e)
- {
- throw new OAuthException2('Could not connect to PDO database: ' . $e->getMessage());
- }
-
- $this->query('set character set utf8');
- }
- }
-
- /**
- * Perform a query, ignore the results
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- */
- protected function query ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- try
- {
- $this->lastaffectedrows = $this->conn->exec($sql);
- if ($this->lastaffectedrows === FALSE) {
- $this->sql_errcheck($sql);
- }
- }
- catch (PDOException $e)
- {
- $this->sql_errcheck($sql);
- }
- }
-
-
- /**
- * Perform a query, ignore the results
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_all_assoc ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- $result = array();
-
- try
- {
- $stmt = $this->conn->query($sql);
-
- $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
- }
- catch (PDOException $e)
- {
- $this->sql_errcheck($sql);
- }
- return $result;
- }
-
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_row_assoc ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- $result = $this->query_all_assoc($sql);
- $val = array_pop($result);
- return $val;
- }
-
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_row ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- try
- {
- $all = $this->conn->query($sql, PDO::FETCH_NUM);
- $row = array();
- foreach ($all as $r) {
- $row = $r;
- break;
- }
- }
- catch (PDOException $e)
- {
- $this->sql_errcheck($sql);
- }
- return $row;
- }
-
-
- /**
- * Perform a query, return the first column of the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return mixed
- */
- protected function query_one ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- $row = $this->query_row($sql);
- $val = array_pop($row);
- return $val;
- }
-
-
- /**
- * Return the number of rows affected in the last query
- */
- protected function query_affected_rows ()
- {
- return $this->lastaffectedrows;
- }
-
-
- /**
- * Return the id of the last inserted row
- *
- * @return int
- */
- protected function query_insert_id ()
- {
- return $this->conn->lastInsertId();
- }
-
-
- protected function sql_printf ( $args )
- {
- $sql = array_shift($args);
- if (count($args) == 1 && is_array($args[0]))
- {
- $args = $args[0];
- }
- $args = array_map(array($this, 'sql_escape_string'), $args);
- return vsprintf($sql, $args);
- }
-
-
- protected function sql_escape_string ( $s )
- {
- if (is_string($s))
- {
- $s = $this->conn->quote($s);
- // kludge. Quote already adds quotes, and this conflicts with OAuthStoreSQL.
- // so remove the quotes
- $len = strlen($s);
- if ($len == 0)
- return $s;
-
- $startcut = 0;
- while (isset($s[$startcut]) && $s[$startcut] == '\'')
- $startcut++;
-
- $endcut = $len-1;
- while (isset($s[$endcut]) && $s[$endcut] == '\'')
- $endcut--;
-
- $s = substr($s, $startcut, $endcut-$startcut+1);
- return $s;
- }
- else if (is_null($s))
- {
- return NULL;
- }
- else if (is_bool($s))
- {
- return intval($s);
- }
- else if (is_int($s) || is_float($s))
- {
- return $s;
- }
- else
- {
- return $this->conn->quote(strval($s));
- }
- }
-
-
- protected function sql_errcheck ( $sql )
- {
- $msg = "SQL Error in OAuthStoreMySQL: ". print_r($this->conn->errorInfo(), true) ."\n\n" . $sql;
- $backtrace = debug_backtrace();
- $msg .= "\n\nAt file " . $backtrace[1]['file'] . ", line " . $backtrace[1]['line'];
- throw new OAuthException2($msg);
- }
-
- /**
- * Initialise the database
- */
- public function install ()
- {
- // TODO: this depends on mysql extension
- require_once dirname(__FILE__) . '/mysql/install.php';
- }
-
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?>
diff --git a/vendor/oauth-php/library/store/OAuthStorePostgreSQL.php b/vendor/oauth-php/library/store/OAuthStorePostgreSQL.php
deleted file mode 100644
index db55804..0000000
--- a/vendor/oauth-php/library/store/OAuthStorePostgreSQL.php
+++ /dev/null
@@ -1,1981 +0,0 @@
-<?php
-/**
- * OAuthStorePostgreSQL.php
- *
- * PHP Version 5.2
- *
- * @author Elma R&D Team <rdteam@elma.fr>
- * @link http://elma.fr
- *
- * @Id 2010-10-22 10:07:18 ndelanoe $
- * @version $Id: OAuthStorePostgreSQL.php 190 2011-03-22 09:16:01Z scherpenisse $
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- **/
-
-require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php';
-
-
-class OAuthStorePostgreSQL extends OAuthStoreAbstract
-{
- /**
- * Maximum delta a timestamp may be off from a previous timestamp.
- * Allows multiple consumers with some clock skew to work with the same token.
- * Unit is seconds, default max skew is 10 minutes.
- */
- protected $max_timestamp_skew = 600;
-
- /**
- * Default ttl for request tokens
- */
- protected $max_request_token_ttl = 3600;
-
- /**
- * Number of affected rowsby the last queries
- */
- private $_lastAffectedRows = 0;
-
- public function install()
- {
- throw new OAuthException2('Not yet implemented, see postgresql/pgsql.sql');
- }
-
- /**
- * Construct the OAuthStorePostgrSQL.
- * In the options you have to supply either:
- * - server, username, password and database (for a pg_connect)
- * - connectionString (for a pg_connect)
- * - conn (for the connection to be used)
- *
- * @param array options
- */
- function __construct ( $options = array() )
- {
- if (isset($options['conn']))
- {
- $this->conn = $options['conn'];
- }
- else
- {
- if (isset($options['server']))
- {
- $host = $options['server'];
- $user = $options['username'];
- $dbname = $options['database'];
-
- $connectionString = sprintf('host=%s dbname=%s user=%s', $host, $dbname, $user);
-
- if (isset($options['password']))
- {
- $connectionString .= ' password=' . $options['password'];
- }
-
- $this->conn = pg_connect($connectionString);
- }
- elseif (isset($options['connectionString']))
- {
- $this->conn = pg_connect($options['connectionString']);
- }
- else {
-
- // Try the default pg connect
- $this->conn = pg_connect();
- }
-
- if ($this->conn === false)
- {
- throw new OAuthException2('Could not connect to PostgresSQL database');
- }
- }
- }
-
- /**
- * Find stored credentials for the consumer key and token. Used by an OAuth server
- * when verifying an OAuth request.
- *
- * @param string consumer_key
- * @param string token
- * @param string token_type false, 'request' or 'access'
- * @exception OAuthException2 when no secrets where found
- * @return array assoc (consumer_secret, token_secret, osr_id, ost_id, user_id)
- */
- public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' )
- {
- if ($token_type === false)
- {
- $rs = $this->query_row_assoc('
- SELECT osr_id,
- osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret
- FROM oauth_server_registry
- WHERE osr_consumer_key = \'%s\'
- AND osr_enabled = \'1\'
- ',
- $consumer_key);
-
- if ($rs)
- {
- $rs['token'] = false;
- $rs['token_secret'] = false;
- $rs['user_id'] = false;
- $rs['ost_id'] = false;
- }
- }
- else
- {
- $rs = $this->query_row_assoc('
- SELECT osr_id,
- ost_id,
- ost_usa_id_ref as user_id,
- osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret,
- ost_token as token,
- ost_token_secret as token_secret
- FROM oauth_server_registry
- JOIN oauth_server_token
- ON ost_osr_id_ref = osr_id
- WHERE ost_token_type = \'%s\'
- AND osr_consumer_key = \'%s\'
- AND ost_token = \'%s\'
- AND osr_enabled = \'1\'
- AND ost_token_ttl >= NOW()
- ',
- $token_type, $consumer_key, $token);
- }
-
- if (empty($rs))
- {
- throw new OAuthException2('The consumer_key "'.$consumer_key.'" token "'.$token.'" combination does not exist or is not enabled.');
- }
- return $rs;
- }
-
- /**
- * Find the server details for signing a request, always looks for an access token.
- * The returned credentials depend on which local user is making the request.
- *
- * The consumer_key must belong to the user or be public (user id is null)
- *
- * For signing we need all of the following:
- *
- * consumer_key consumer key associated with the server
- * consumer_secret consumer secret associated with this server
- * token access token associated with this server
- * token_secret secret for the access token
- * signature_methods signing methods supported by the server (array)
- *
- * @todo filter on token type (we should know how and with what to sign this request, and there might be old access tokens)
- * @param string uri uri of the server
- * @param int user_id id of the logged on user
- * @param string name (optional) name of the token (case sensitive)
- * @exception OAuthException2 when no credentials found
- * @return array
- */
- public function getSecretsForSignature ( $uri, $user_id, $name = '' )
- {
- // Find a consumer key and token for the given uri
- $ps = parse_url($uri);
- $host = isset($ps['host']) ? $ps['host'] : 'localhost';
- $path = isset($ps['path']) ? $ps['path'] : '';
-
- if (empty($path) || substr($path, -1) != '/')
- {
- $path .= '/';
- }
-
- // The owner of the consumer_key is either the user or nobody (public consumer key)
- $secrets = $this->query_row_assoc('
- SELECT ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- oct_token as token,
- oct_token_secret as token_secret,
- ocr_signature_methods as signature_methods
- FROM oauth_consumer_registry
- JOIN oauth_consumer_token ON oct_ocr_id_ref = ocr_id
- WHERE ocr_server_uri_host = \'%s\'
- AND ocr_server_uri_path = SUBSTR(\'%s\', 1, LENGTH(ocr_server_uri_path))
- AND (ocr_usa_id_ref = \'%s\' OR ocr_usa_id_ref IS NULL)
- AND oct_usa_id_ref = \'%d\'
- AND oct_token_type = \'access\'
- AND oct_name = \'%s\'
- AND oct_token_ttl >= NOW()
- ORDER BY ocr_usa_id_ref DESC, ocr_consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC
- LIMIT 1
- ', $host, $path, $user_id, $user_id, $name
- );
-
- if (empty($secrets))
- {
- throw new OAuthException2('No server tokens available for '.$uri);
- }
- $secrets['signature_methods'] = explode(',', $secrets['signature_methods']);
- return $secrets;
- }
-
- /**
- * Get the token and token secret we obtained from a server.
- *
- * @param string consumer_key
- * @param string token
- * @param string token_type
- * @param int user_id the user owning the token
- * @param string name optional name for a named token
- * @exception OAuthException2 when no credentials found
- * @return array
- */
- public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' )
- {
- if ($token_type != 'request' && $token_type != 'access')
- {
- throw new OAuthException2('Unkown token type "'.$token_type.'", must be either "request" or "access"');
- }
-
- // Take the most recent token of the given type
- $r = $this->query_row_assoc('
- SELECT ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- oct_token as token,
- oct_token_secret as token_secret,
- oct_name as token_name,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri,
- CASE WHEN oct_token_ttl >= \'9999-12-31\' THEN NULL ELSE oct_token_ttl - NOW() END as token_ttl
- FROM oauth_consumer_registry
- JOIN oauth_consumer_token
- ON oct_ocr_id_ref = ocr_id
- WHERE ocr_consumer_key = \'%s\'
- AND oct_token_type = \'%s\'
- AND oct_token = \'%s\'
- AND oct_usa_id_ref = \'%d\'
- AND oct_token_ttl >= NOW()
- ', $consumer_key, $token_type, $token, $user_id
- );
-
- if (empty($r))
- {
- throw new OAuthException2('Could not find a "'.$token_type.'" token for consumer "'.$consumer_key.'" and user '.$user_id);
- }
- if (isset($r['signature_methods']) && !empty($r['signature_methods']))
- {
- $r['signature_methods'] = explode(',',$r['signature_methods']);
- }
- else
- {
- $r['signature_methods'] = array();
- }
- return $r;
- }
-
-
- /**
- * Add a request token we obtained from a server.
- *
- * @todo remove old tokens for this user and this ocr_id
- * @param string consumer_key key of the server in the consumer registry
- * @param string token_type one of 'request' or 'access'
- * @param string token
- * @param string token_secret
- * @param int user_id the user owning the token
- * @param array options extra options, name and token_ttl
- * @exception OAuthException2 when server is not known
- * @exception OAuthException2 when we received a duplicate token
- */
- public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() )
- {
- if ($token_type != 'request' && $token_type != 'access')
- {
- throw new OAuthException2('Unknown token type "'.$token_type.'", must be either "request" or "access"');
- }
-
- // Maximum time to live for this token
- if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
- {
- $ttl = 'NOW() + INTERVAL \''.intval($options['token_ttl']).' SECOND\'';
- }
- else if ($token_type == 'request')
- {
- $ttl = 'NOW() + INTERVAL \''.$this->max_request_token_ttl.' SECOND\'';
- }
- else
- {
- $ttl = "'9999-12-31'";
- }
-
- if (isset($options['server_uri']))
- {
- $ocr_id = $this->query_one('
- SELECT ocr_id
- FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND ocr_usa_id_ref = \'%d\'
- AND ocr_server_uri = \'%s\'
- ', $consumer_key, $user_id, $options['server_uri']);
- }
- else
- {
- $ocr_id = $this->query_one('
- SELECT ocr_id
- FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND ocr_usa_id_ref = \'%d\'
- ', $consumer_key, $user_id);
- }
-
- if (empty($ocr_id))
- {
- throw new OAuthException2('No server associated with consumer_key "'.$consumer_key.'"');
- }
-
- // Named tokens, unique per user/consumer key
- if (isset($options['name']) && $options['name'] != '')
- {
- $name = $options['name'];
- }
- else
- {
- $name = '';
- }
-
- // Delete any old tokens with the same type and name for this user/server combination
- $this->query('
- DELETE FROM oauth_consumer_token
- WHERE oct_ocr_id_ref = %d
- AND oct_usa_id_ref = \'%d\'
- AND oct_token_type::text = LOWER(\'%s\')::text
- AND oct_name = \'%s\'
- ',
- $ocr_id,
- $user_id,
- $token_type,
- $name);
-
- // Insert the new token
- $this->query('
- INSERT INTO
- oauth_consumer_token(
- oct_ocr_id_ref,
- oct_usa_id_ref,
- oct_name,
- oct_token,
- oct_token_secret,
- oct_token_type,
- oct_timestamp,
- oct_token_ttl
- )
- VALUES (%d,%d,\'%s\',\'%s\',\'%s\',\'%s\',NOW(),'.$ttl.')',
- $ocr_id,
- $user_id,
- $name,
- $token,
- $token_secret,
- $token_type);
-
- if (!$this->query_affected_rows())
- {
- throw new OAuthException2('Received duplicate token "'.$token.'" for the same consumer_key "'.$consumer_key.'"');
- }
- }
-
- /**
- * Delete a server key. This removes access to that site.
- *
- * @param string consumer_key
- * @param int user_id user registering this server
- * @param boolean user_is_admin
- */
- public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false )
- {
- if ($user_is_admin)
- {
- $this->query('
- DELETE FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL)
- ', $consumer_key, $user_id);
- }
- else
- {
- $this->query('
- DELETE FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND ocr_usa_id_ref = \'%d\'
- ', $consumer_key, $user_id);
- }
- }
-
-
- /**
- * Get a server from the consumer registry using the consumer key
- *
- * @param string consumer_key
- * @param int user_id
- * @param boolean user_is_admin (optional)
- * @exception OAuthException2 when server is not found
- * @return array
- */
- public function getServer ( $consumer_key, $user_id, $user_is_admin = false )
- {
- $r = $this->query_row_assoc('
- SELECT ocr_id as id,
- ocr_usa_id_ref as user_id,
- ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri
- FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL)
- ', $consumer_key, $user_id);
-
- if (empty($r))
- {
- throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" has been registered (for this user)');
- }
-
- if (isset($r['signature_methods']) && !empty($r['signature_methods']))
- {
- $r['signature_methods'] = explode(',',$r['signature_methods']);
- }
- else
- {
- $r['signature_methods'] = array();
- }
- return $r;
- }
-
-
- /**
- * Find the server details that might be used for a request
- *
- * The consumer_key must belong to the user or be public (user id is null)
- *
- * @param string uri uri of the server
- * @param int user_id id of the logged on user
- * @exception OAuthException2 when no credentials found
- * @return array
- */
- public function getServerForUri ( $uri, $user_id )
- {
- // Find a consumer key and token for the given uri
- $ps = parse_url($uri);
- $host = isset($ps['host']) ? $ps['host'] : 'localhost';
- $path = isset($ps['path']) ? $ps['path'] : '';
-
- if (empty($path) || substr($path, -1) != '/')
- {
- $path .= '/';
- }
-
- // The owner of the consumer_key is either the user or nobody (public consumer key)
- $server = $this->query_row_assoc('
- SELECT ocr_id as id,
- ocr_usa_id_ref as user_id,
- ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri
- FROM oauth_consumer_registry
- WHERE ocr_server_uri_host = \'%s\'
- AND ocr_server_uri_path = SUBSTR(\'%s\', 1, LENGTH(ocr_server_uri_path))
- AND (ocr_usa_id_ref = \'%s\' OR ocr_usa_id_ref IS NULL)
- ORDER BY ocr_usa_id_ref DESC, consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC
- LIMIT 1
- ', $host, $path, $user_id
- );
-
- if (empty($server))
- {
- throw new OAuthException2('No server available for '.$uri);
- }
- $server['signature_methods'] = explode(',', $server['signature_methods']);
- return $server;
- }
-
- /**
- * Get a list of all server token this user has access to.
- *
- * @param int usr_id
- * @return array
- */
- public function listServerTokens ( $user_id )
- {
- $ts = $this->query_all_assoc('
- SELECT ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- oct_id as token_id,
- oct_token as token,
- oct_token_secret as token_secret,
- oct_usa_id_ref as user_id,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_server_uri_host as server_uri_host,
- ocr_server_uri_path as server_uri_path,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri,
- oct_timestamp as timestamp
- FROM oauth_consumer_registry
- JOIN oauth_consumer_token
- ON oct_ocr_id_ref = ocr_id
- WHERE oct_usa_id_ref = \'%d\'
- AND oct_token_type = \'access\'
- AND oct_token_ttl >= NOW()
- ORDER BY ocr_server_uri_host, ocr_server_uri_path
- ', $user_id);
- return $ts;
- }
-
- /**
- * Count how many tokens we have for the given server
- *
- * @param string consumer_key
- * @return int
- */
- public function countServerTokens ( $consumer_key )
- {
- $count = $this->query_one('
- SELECT COUNT(oct_id)
- FROM oauth_consumer_token
- JOIN oauth_consumer_registry
- ON oct_ocr_id_ref = ocr_id
- WHERE oct_token_type = \'access\'
- AND ocr_consumer_key = \'%s\'
- AND oct_token_ttl >= NOW()
- ', $consumer_key);
-
- return $count;
- }
-
- /**
- * Get a specific server token for the given user
- *
- * @param string consumer_key
- * @param string token
- * @param int user_id
- * @exception OAuthException2 when no such token found
- * @return array
- */
- public function getServerToken ( $consumer_key, $token, $user_id )
- {
- $ts = $this->query_row_assoc('
- SELECT ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- oct_token as token,
- oct_token_secret as token_secret,
- oct_usa_id_ref as usr_id,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_server_uri_host as server_uri_host,
- ocr_server_uri_path as server_uri_path,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri,
- oct_timestamp as timestamp
- FROM oauth_consumer_registry
- JOIN oauth_consumer_token
- ON oct_ocr_id_ref = ocr_id
- WHERE ocr_consumer_key = \'%s\'
- AND oct_usa_id_ref = \'%d\'
- AND oct_token_type = \'access\'
- AND oct_token = \'%s\'
- AND oct_token_ttl >= NOW()
- ', $consumer_key, $user_id, $token);
-
- if (empty($ts))
- {
- throw new OAuthException2('No such consumer key ('.$consumer_key.') and token ('.$token.') combination for user "'.$user_id.'"');
- }
- return $ts;
- }
-
-
- /**
- * Delete a token we obtained from a server.
- *
- * @param string consumer_key
- * @param string token
- * @param int user_id
- * @param boolean user_is_admin
- */
- public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false )
- {
- if ($user_is_admin)
- {
- $this->query('
- DELETE FROM oauth_consumer_token
- USING oauth_consumer_registry
- WHERE
- oct_ocr_id_ref = ocr_id
- AND ocr_consumer_key = \'%s\'
- AND oct_token = \'%s\'
- ', $consumer_key, $token);
- }
- else
- {
- $this->query('
- DELETE FROM oauth_consumer_token
- USING oauth_consumer_registry
- WHERE
- oct_ocr_id_ref = ocr_id
- AND ocr_consumer_key = \'%s\'
- AND oct_token = \'%s\'
- AND oct_usa_id_ref = \'%d\'
- ', $consumer_key, $token, $user_id);
- }
- }
-
- /**
- * Set the ttl of a server access token. This is done when the
- * server receives a valid request with a xoauth_token_ttl parameter in it.
- *
- * @param string consumer_key
- * @param string token
- * @param int token_ttl
- */
- public function setServerTokenTtl ( $consumer_key, $token, $token_ttl, $server_uri = NULL )
- {
- if ($token_ttl <= 0)
- {
- // Immediate delete when the token is past its ttl
- $this->deleteServerToken($consumer_key, $token, 0, true);
- }
- else if ( $server_uri )
- {
- // Set maximum time to live for this token
- $this->query('
- UPDATE oauth_consumer_token
- SET ost_token_ttl = (NOW() + INTERVAL \'%d SECOND\')
- WHERE ocr_consumer_key = \'%s\'
- AND ocr_server_uri = \'%s\'
- AND oct_ocr_id_ref = ocr_id
- AND oct_token = \'%s\'
- ', $token_ttl, $server_uri, $consumer_key, $token);
-
- // Set maximum time to live for this token
- $this->query('
- UPDATE oauth_consumer_registry
- SET ost_token_ttl = (NOW() + INTERVAL \'%d SECOND\')
- WHERE ocr_consumer_key = \'%s\'
- AND ocr_server_uri = \'%s\'
- AND oct_ocr_id_ref = ocr_id
- AND oct_token = \'%s\'
- ', $token_ttl, $server_uri, $consumer_key, $token);
- }
- else
- {
- // Set maximum time to live for this token
- $this->query('
- UPDATE oauth_consumer_token
- SET ost_token_ttl = (NOW() + INTERVAL \'%d SECOND\')
- WHERE ocr_consumer_key = \'%s\'
- AND oct_ocr_id_ref = ocr_id
- AND oct_token = \'%s\'
- ', $token_ttl, $consumer_key, $token);
-
- // Set maximum time to live for this token
- $this->query('
- UPDATE oauth_consumer_registry
- SET ost_token_ttl = (NOW() + INTERVAL \'%d SECOND\')
- WHERE ocr_consumer_key = \'%s\'
- AND oct_ocr_id_ref = ocr_id
- AND oct_token = \'%s\'
- ', $token_ttl, $consumer_key, $token);
- }
- }
-
- /**
- * Get a list of all consumers from the consumer registry.
- * The consumer keys belong to the user or are public (user id is null)
- *
- * @param string q query term
- * @param int user_id
- * @return array
- */
- public function listServers ( $q = '', $user_id )
- {
- $q = trim(str_replace('%', '', $q));
- $args = array();
-
- if (!empty($q))
- {
- $where = ' WHERE ( ocr_consumer_key like \'%%%s%%\'
- OR ocr_server_uri like \'%%%s%%\'
- OR ocr_server_uri_host like \'%%%s%%\'
- OR ocr_server_uri_path like \'%%%s%%\')
- AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL)
- ';
-
- $args[] = $q;
- $args[] = $q;
- $args[] = $q;
- $args[] = $q;
- $args[] = $user_id;
- }
- else
- {
- $where = ' WHERE ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL';
- $args[] = $user_id;
- }
-
- $servers = $this->query_all_assoc('
- SELECT ocr_id as id,
- ocr_usa_id_ref as user_id,
- ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_server_uri_host as server_uri_host,
- ocr_server_uri_path as server_uri_path,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri
- FROM oauth_consumer_registry
- '.$where.'
- ORDER BY ocr_server_uri_host, ocr_server_uri_path
- ', $args);
- return $servers;
- }
-
- /**
- * Register or update a server for our site (we will be the consumer)
- *
- * (This is the registry at the consumers, registering servers ;-) )
- *
- * @param array server
- * @param int user_id user registering this server
- * @param boolean user_is_admin
- * @exception OAuthException2 when fields are missing or on duplicate consumer_key
- * @return consumer_key
- */
- public function updateServer ( $server, $user_id, $user_is_admin = false )
- {
- foreach (array('consumer_key', 'server_uri') as $f)
- {
- if (empty($server[$f]))
- {
- throw new OAuthException2('The field "'.$f.'" must be set and non empty');
- }
- }
-
- if (!empty($server['id']))
- {
- $exists = $this->query_one('
- SELECT ocr_id
- FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND ocr_id <> %d
- AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL)
- ', $server['consumer_key'], $server['id'], $user_id);
- }
- else
- {
- $exists = $this->query_one('
- SELECT ocr_id
- FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL)
- ', $server['consumer_key'], $user_id);
- }
-
- if ($exists)
- {
- throw new OAuthException2('The server with key "'.$server['consumer_key'].'" has already been registered');
- }
-
- $parts = parse_url($server['server_uri']);
- $host = (isset($parts['host']) ? $parts['host'] : 'localhost');
- $path = (isset($parts['path']) ? $parts['path'] : '/');
-
- if (isset($server['signature_methods']))
- {
- if (is_array($server['signature_methods']))
- {
- $server['signature_methods'] = strtoupper(implode(',', $server['signature_methods']));
- }
- }
- else
- {
- $server['signature_methods'] = '';
- }
-
- // When the user is an admin, then the user can update the user_id of this record
- if ($user_is_admin && array_key_exists('user_id', $server))
- {
- if (is_null($server['user_id']))
- {
- $update_user = ', ocr_usa_id_ref = NULL';
- }
- else
- {
- $update_user = ', ocr_usa_id_ref = \''. intval($server['user_id']) . '\'';
- }
- }
- else
- {
- $update_user = '';
- }
-
- if (!empty($server['id']))
- {
- // Check if the current user can update this server definition
- if (!$user_is_admin)
- {
- $ocr_usa_id_ref = $this->query_one('
- SELECT ocr_usa_id_ref
- FROM oauth_consumer_registry
- WHERE ocr_id = %d
- ', $server['id']);
-
- if ($ocr_usa_id_ref != $user_id)
- {
- throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this server');
- }
- }
-
- // Update the consumer registration
- $this->query('
- UPDATE oauth_consumer_registry
- SET ocr_consumer_key = \'%s\',
- ocr_consumer_secret = \'%s\',
- ocr_server_uri = \'%s\',
- ocr_server_uri_host = \'%s\',
- ocr_server_uri_path = \'%s\',
- ocr_timestamp = NOW(),
- ocr_request_token_uri = \'%s\',
- ocr_authorize_uri = \'%s\',
- ocr_access_token_uri = \'%s\',
- ocr_signature_methods = \'%s\'
- '.$update_user.'
- WHERE ocr_id = %d
- ',
- $server['consumer_key'],
- $server['consumer_secret'],
- $server['server_uri'],
- strtolower($host),
- $path,
- isset($server['request_token_uri']) ? $server['request_token_uri'] : '',
- isset($server['authorize_uri']) ? $server['authorize_uri'] : '',
- isset($server['access_token_uri']) ? $server['access_token_uri'] : '',
- $server['signature_methods'],
- $server['id']
- );
- }
- else
- {
- $update_user_field = '';
- $update_user_value = '';
- if (empty($update_user))
- {
- // Per default the user owning the key is the user registering the key
- $update_user_field = ', ocr_usa_id_ref';
- $update_user_value = ', ' . intval($user_id);
- }
-
- $this->query('
- INSERT INTO oauth_consumer_registry (
- ocr_consumer_key ,
- ocr_consumer_secret ,
- ocr_server_uri ,
- ocr_server_uri_host ,
- ocr_server_uri_path ,
- ocr_timestamp ,
- ocr_request_token_uri,
- ocr_authorize_uri ,
- ocr_access_token_uri ,
- ocr_signature_methods' . $update_user_field . '
- )
- VALUES (\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', NOW(), \'%s\', \'%s\', \'%s\', \'%s\''. $update_user_value . ')',
- $server['consumer_key'],
- $server['consumer_secret'],
- $server['server_uri'],
- strtolower($host),
- $path,
- isset($server['request_token_uri']) ? $server['request_token_uri'] : '',
- isset($server['authorize_uri']) ? $server['authorize_uri'] : '',
- isset($server['access_token_uri']) ? $server['access_token_uri'] : '',
- $server['signature_methods']
- );
-
- $ocr_id = $this->query_insert_id('oauth_consumer_registry', 'ocr_id');
- }
- return $server['consumer_key'];
- }
-
-
- /**
- * Insert/update a new consumer with this server (we will be the server)
- * When this is a new consumer, then also generate the consumer key and secret.
- * Never updates the consumer key and secret.
- * When the id is set, then the key and secret must correspond to the entry
- * being updated.
- *
- * (This is the registry at the server, registering consumers ;-) )
- *
- * @param array consumer
- * @param int user_id user registering this consumer
- * @param boolean user_is_admin
- * @return string consumer key
- */
- public function updateConsumer ( $consumer, $user_id, $user_is_admin = false )
- {
- if (!$user_is_admin)
- {
- foreach (array('requester_name', 'requester_email') as $f)
- {
- if (empty($consumer[$f]))
- {
- throw new OAuthException2('The field "'.$f.'" must be set and non empty');
- }
- }
- }
-
- if (!empty($consumer['id']))
- {
- if (empty($consumer['consumer_key']))
- {
- throw new OAuthException2('The field "consumer_key" must be set and non empty');
- }
- if (!$user_is_admin && empty($consumer['consumer_secret']))
- {
- throw new OAuthException2('The field "consumer_secret" must be set and non empty');
- }
-
- // Check if the current user can update this server definition
- if (!$user_is_admin)
- {
- $osr_usa_id_ref = $this->query_one('
- SELECT osr_usa_id_ref
- FROM oauth_server_registry
- WHERE osr_id = %d
- ', $consumer['id']);
-
- if ($osr_usa_id_ref != $user_id)
- {
- throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this consumer');
- }
- }
- else
- {
- // User is an admin, allow a key owner to be changed or key to be shared
- if (array_key_exists('user_id',$consumer))
- {
- if (is_null($consumer['user_id']))
- {
- $this->query('
- UPDATE oauth_server_registry
- SET osr_usa_id_ref = NULL
- WHERE osr_id = %d
- ', $consumer['id']);
- }
- else
- {
- $this->query('
- UPDATE oauth_server_registry
- SET osr_usa_id_ref = \'%d\'
- WHERE osr_id = %d
- ', $consumer['user_id'], $consumer['id']);
- }
- }
- }
-
- $this->query('
- UPDATE oauth_server_registry
- SET osr_requester_name = \'%s\',
- osr_requester_email = \'%s\',
- osr_callback_uri = \'%s\',
- osr_application_uri = \'%s\',
- osr_application_title = \'%s\',
- osr_application_descr = \'%s\',
- osr_application_notes = \'%s\',
- osr_application_type = \'%s\',
- osr_application_commercial = IF(%d,\'1\',\'0\'),
- osr_timestamp = NOW()
- WHERE osr_id = %d
- AND osr_consumer_key = \'%s\'
- AND osr_consumer_secret = \'%s\'
- ',
- $consumer['requester_name'],
- $consumer['requester_email'],
- isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '',
- isset($consumer['application_uri']) ? $consumer['application_uri'] : '',
- isset($consumer['application_title']) ? $consumer['application_title'] : '',
- isset($consumer['application_descr']) ? $consumer['application_descr'] : '',
- isset($consumer['application_notes']) ? $consumer['application_notes'] : '',
- isset($consumer['application_type']) ? $consumer['application_type'] : '',
- isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0,
- $consumer['id'],
- $consumer['consumer_key'],
- $consumer['consumer_secret']
- );
-
-
- $consumer_key = $consumer['consumer_key'];
- }
- else
- {
- $consumer_key = $this->generateKey(true);
- $consumer_secret= $this->generateKey();
-
- // When the user is an admin, then the user can be forced to something else that the user
- if ($user_is_admin && array_key_exists('user_id',$consumer))
- {
- if (is_null($consumer['user_id']))
- {
- $owner_id = 'NULL';
- }
- else
- {
- $owner_id = intval($consumer['user_id']);
- }
- }
- else
- {
- // No admin, take the user id as the owner id.
- $owner_id = intval($user_id);
- }
-
- $this->query('
- INSERT INTO oauth_server_registry (
- osr_enabled,
- osr_status,
- osr_usa_id_ref,
- osr_consumer_key,
- osr_consumer_secret,
- osr_requester_name,
- osr_requester_email,
- osr_callback_uri,
- osr_application_uri,
- osr_application_title,
- osr_application_descr,
- osr_application_notes,
- osr_application_type,
- osr_application_commercial,
- osr_timestamp,
- osr_issue_date
- )
- VALUES (\'1\', \'active\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%d\', NOW(), NOW())
- ',
- $owner_id,
- $consumer_key,
- $consumer_secret,
- $consumer['requester_name'],
- $consumer['requester_email'],
- isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '',
- isset($consumer['application_uri']) ? $consumer['application_uri'] : '',
- isset($consumer['application_title']) ? $consumer['application_title'] : '',
- isset($consumer['application_descr']) ? $consumer['application_descr'] : '',
- isset($consumer['application_notes']) ? $consumer['application_notes'] : '',
- isset($consumer['application_type']) ? $consumer['application_type'] : '',
- isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0
- );
- }
- return $consumer_key;
-
- }
-
- /**
- * Delete a consumer key. This removes access to our site for all applications using this key.
- *
- * @param string consumer_key
- * @param int user_id user registering this server
- * @param boolean user_is_admin
- */
- public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false )
- {
- if ($user_is_admin)
- {
- $this->query('
- DELETE FROM oauth_server_registry
- WHERE osr_consumer_key = \'%s\'
- AND (osr_usa_id_ref = \'%d\' OR osr_usa_id_ref IS NULL)
- ', $consumer_key, $user_id);
- }
- else
- {
- $this->query('
- DELETE FROM oauth_server_registry
- WHERE osr_consumer_key = \'%s\'
- AND osr_usa_id_ref = \'%d\'
- ', $consumer_key, $user_id);
- }
- }
-
- /**
- * Fetch a consumer of this server, by consumer_key.
- *
- * @param string consumer_key
- * @param int user_id
- * @param boolean user_is_admin (optional)
- * @exception OAuthException2 when consumer not found
- * @return array
- */
- public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false )
- {
- $consumer = $this->query_row_assoc('
- SELECT *
- FROM oauth_server_registry
- WHERE osr_consumer_key = \'%s\'
- ', $consumer_key);
-
- if (!is_array($consumer))
- {
- throw new OAuthException2('No consumer with consumer_key "'.$consumer_key.'"');
- }
-
- $c = array();
- foreach ($consumer as $key => $value)
- {
- $c[substr($key, 4)] = $value;
- }
- $c['user_id'] = $c['usa_id_ref'];
-
- if (!$user_is_admin && !empty($c['user_id']) && $c['user_id'] != $user_id)
- {
- throw new OAuthException2('No access to the consumer information for consumer_key "'.$consumer_key.'"');
- }
- return $c;
- }
-
-
- /**
- * Fetch the static consumer key for this provider. The user for the static consumer
- * key is NULL (no user, shared key). If the key did not exist then the key is created.
- *
- * @return string
- */
- public function getConsumerStatic ()
- {
- $consumer = $this->query_one('
- SELECT osr_consumer_key
- FROM oauth_server_registry
- WHERE osr_consumer_key LIKE \'sc-%%\'
- AND osr_usa_id_ref IS NULL
- ');
-
- if (empty($consumer))
- {
- $consumer_key = 'sc-'.$this->generateKey(true);
- $this->query('
- INSERT INTO oauth_server_registry (
- osr_enabled,
- osr_status,
- osr_usa_id_ref,
- osr_consumer_key,
- osr_consumer_secret,
- osr_requester_name,
- osr_requester_email,
- osr_callback_uri,
- osr_application_uri,
- osr_application_title,
- osr_application_descr,
- osr_application_notes,
- osr_application_type,
- osr_application_commercial,
- osr_timestamp,
- osr_issue_date
- )
- VALUES (\'1\',\'active\', NULL, \'%s\', \'\', \'\', \'\', \'\', \'\', \'Static shared consumer key\', \'\', \'Static shared consumer key\', \'\', 0, NOW(), NOW())
- ',
- $consumer_key
- );
-
- // Just make sure that if the consumer key is truncated that we get the truncated string
- $consumer = $this->getConsumerStatic();
- }
- return $consumer;
- }
-
- /**
- * Add an unautorized request token to our server.
- *
- * @param string consumer_key
- * @param array options (eg. token_ttl)
- * @return array (token, token_secret)
- */
- public function addConsumerRequestToken ( $consumer_key, $options = array() )
- {
- $token = $this->generateKey(true);
- $secret = !isset($options['secret']) ? $this->generateKey() : $options['secret'];
- $osr_id = $this->query_one('
- SELECT osr_id
- FROM oauth_server_registry
- WHERE osr_consumer_key = \'%s\'
- AND osr_enabled = \'1\'
- ', $consumer_key);
-
- if (!$osr_id)
- {
- throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" or consumer_key is disabled');
- }
-
- if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
- {
- $ttl = intval($options['token_ttl']);
- }
- else
- {
- $ttl = $this->max_request_token_ttl;
- }
-
- if (!isset($options['oauth_callback'])) {
- // 1.0a Compatibility : store callback url associated with request token
- $options['oauth_callback']='oob';
- }
-
- $this->query('
- INSERT INTO oauth_server_token (
- ost_osr_id_ref,
- ost_usa_id_ref,
- ost_token,
- ost_token_secret,
- ost_token_type,
- ost_token_ttl,
- ost_callback_url
- )
- VALUES (%d, \'1\', \'%s\', \'%s\', \'request\', NOW() + INTERVAL \'%d SECOND\', \'%s\')',
- $osr_id, $token, $secret, $ttl, $options['oauth_callback']);
-
- return array('token'=>$token, 'token_secret'=>$secret, 'token_ttl'=>$ttl);
- }
-
- /**
- * Fetch the consumer request token, by request token.
- *
- * @param string token
- * @return array token and consumer details
- */
- public function getConsumerRequestToken ( $token )
- {
- $rs = $this->query_row_assoc('
- SELECT ost_token as token,
- ost_token_secret as token_secret,
- osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret,
- ost_token_type as token_type,
- ost_callback_url as callback_url,
- osr_application_title as application_title,
- osr_application_descr as application_descr,
- osr_application_uri as application_uri
- FROM oauth_server_token
- JOIN oauth_server_registry
- ON ost_osr_id_ref = osr_id
- WHERE ost_token_type = \'request\'
- AND ost_token = \'%s\'
- AND ost_token_ttl >= NOW()
- ', $token);
-
- return $rs;
- }
-
- /**
- * Delete a consumer token. The token must be a request or authorized token.
- *
- * @param string token
- */
- public function deleteConsumerRequestToken ( $token )
- {
- $this->query('
- DELETE FROM oauth_server_token
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'request\'
- ', $token);
- }
-
- /**
- * Upgrade a request token to be an authorized request token.
- *
- * @param string token
- * @param int user_id user authorizing the token
- * @param string referrer_host used to set the referrer host for this token, for user feedback
- */
- public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' )
- {
- // 1.0a Compatibility : create a token verifier
- $verifier = substr(md5(rand()),0,10);
-
- $this->query('
- UPDATE oauth_server_token
- SET ost_authorized = \'1\',
- ost_usa_id_ref = \'%d\',
- ost_timestamp = NOW(),
- ost_referrer_host = \'%s\',
- ost_verifier = \'%s\'
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'request\'
- ', $user_id, $referrer_host, $verifier, $token);
- return $verifier;
- }
-
- /**
- * Count the consumer access tokens for the given consumer.
- *
- * @param string consumer_key
- * @return int
- */
- public function countConsumerAccessTokens ( $consumer_key )
- {
- $count = $this->query_one('
- SELECT COUNT(ost_id)
- FROM oauth_server_token
- JOIN oauth_server_registry
- ON ost_osr_id_ref = osr_id
- WHERE ost_token_type = \'access\'
- AND osr_consumer_key = \'%s\'
- AND ost_token_ttl >= NOW()
- ', $consumer_key);
-
- return $count;
- }
-
- /**
- * Exchange an authorized request token for new access token.
- *
- * @param string token
- * @param array options options for the token, token_ttl
- * @exception OAuthException2 when token could not be exchanged
- * @return array (token, token_secret)
- */
- public function exchangeConsumerRequestForAccessToken ( $token, $options = array() )
- {
- $new_token = $this->generateKey(true);
- $new_secret = $this->generateKey();
-
- // Maximum time to live for this token
- if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
- {
- $ttl_sql = '(NOW() + INTERVAL \''.intval($options['token_ttl']).' SECOND\')';
- }
- else
- {
- $ttl_sql = "'9999-12-31'";
- }
-
- if (isset($options['verifier'])) {
- $verifier = $options['verifier'];
-
- // 1.0a Compatibility : check token against oauth_verifier
- $this->query('
- UPDATE oauth_server_token
- SET ost_token = \'%s\',
- ost_token_secret = \'%s\',
- ost_token_type = \'access\',
- ost_timestamp = NOW(),
- ost_token_ttl = '.$ttl_sql.'
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'request\'
- AND ost_authorized = \'1\'
- AND ost_token_ttl >= NOW()
- AND ost_verifier = \'%s\'
- ', $new_token, $new_secret, $token, $verifier);
- } else {
-
- // 1.0
- $this->query('
- UPDATE oauth_server_token
- SET ost_token = \'%s\',
- ost_token_secret = \'%s\',
- ost_token_type = \'access\',
- ost_timestamp = NOW(),
- ost_token_ttl = '.$ttl_sql.'
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'request\'
- AND ost_authorized = \'1\'
- AND ost_token_ttl >= NOW()
- ', $new_token, $new_secret, $token);
- }
-
- if ($this->query_affected_rows() != 1)
- {
- throw new OAuthException2('Can\'t exchange request token "'.$token.'" for access token. No such token or not authorized');
- }
-
- $ret = array('token' => $new_token, 'token_secret' => $new_secret);
- $ttl = $this->query_one('
- SELECT (CASE WHEN ost_token_ttl >= \'9999-12-31\' THEN NULL ELSE ost_token_ttl - NOW() END) as token_ttl
- FROM oauth_server_token
- WHERE ost_token = \'%s\'', $new_token);
-
- if (is_numeric($ttl))
- {
- $ret['token_ttl'] = intval($ttl);
- }
- return $ret;
- }
-
- /**
- * Fetch the consumer access token, by access token.
- *
- * @param string token
- * @param int user_id
- * @exception OAuthException2 when token is not found
- * @return array token and consumer details
- */
- public function getConsumerAccessToken ( $token, $user_id )
- {
- $rs = $this->query_row_assoc('
- SELECT ost_token as token,
- ost_token_secret as token_secret,
- ost_referrer_host as token_referrer_host,
- osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret,
- osr_application_uri as application_uri,
- osr_application_title as application_title,
- osr_application_descr as application_descr,
- osr_callback_uri as callback_uri
- FROM oauth_server_token
- JOIN oauth_server_registry
- ON ost_osr_id_ref = osr_id
- WHERE ost_token_type = \'access\'
- AND ost_token = \'%s\'
- AND ost_usa_id_ref = \'%d\'
- AND ost_token_ttl >= NOW()
- ', $token, $user_id);
-
- if (empty($rs))
- {
- throw new OAuthException2('No server_token "'.$token.'" for user "'.$user_id.'"');
- }
- return $rs;
- }
-
- /**
- * Delete a consumer access token.
- *
- * @param string token
- * @param int user_id
- * @param boolean user_is_admin
- */
- public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false )
- {
- if ($user_is_admin)
- {
- $this->query('
- DELETE FROM oauth_server_token
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'access\'
- ', $token);
- }
- else
- {
- $this->query('
- DELETE FROM oauth_server_token
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'access\'
- AND ost_usa_id_ref = \'%d\'
- ', $token, $user_id);
- }
- }
-
- /**
- * Set the ttl of a consumer access token. This is done when the
- * server receives a valid request with a xoauth_token_ttl parameter in it.
- *
- * @param string token
- * @param int ttl
- */
- public function setConsumerAccessTokenTtl ( $token, $token_ttl )
- {
- if ($token_ttl <= 0)
- {
- // Immediate delete when the token is past its ttl
- $this->deleteConsumerAccessToken($token, 0, true);
- }
- else
- {
- // Set maximum time to live for this token
- $this->query('
- UPDATE oauth_server_token
- SET ost_token_ttl = (NOW() + INTERVAL \'%d SECOND\')
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'access\'
- ', $token_ttl, $token);
- }
- }
-
- /**
- * Fetch a list of all consumer keys, secrets etc.
- * Returns the public (user_id is null) and the keys owned by the user
- *
- * @param int user_id
- * @return array
- */
- public function listConsumers ( $user_id )
- {
- $rs = $this->query_all_assoc('
- SELECT osr_id as id,
- osr_usa_id_ref as user_id,
- osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret,
- osr_enabled as enabled,
- osr_status as status,
- osr_issue_date as issue_date,
- osr_application_uri as application_uri,
- osr_application_title as application_title,
- osr_application_descr as application_descr,
- osr_requester_name as requester_name,
- osr_requester_email as requester_email,
- osr_callback_uri as callback_uri
- FROM oauth_server_registry
- WHERE (osr_usa_id_ref = \'%d\' OR osr_usa_id_ref IS NULL)
- ORDER BY osr_application_title
- ', $user_id);
- return $rs;
- }
-
- /**
- * List of all registered applications. Data returned has not sensitive
- * information and therefore is suitable for public displaying.
- *
- * @param int $begin
- * @param int $total
- * @return array
- */
- public function listConsumerApplications($begin = 0, $total = 25)
- {
- $rs = $this->query_all_assoc('
- SELECT osr_id as id,
- osr_enabled as enabled,
- osr_status as status,
- osr_issue_date as issue_date,
- osr_application_uri as application_uri,
- osr_application_title as application_title,
- osr_application_descr as application_descr
- FROM oauth_server_registry
- ORDER BY osr_application_title
- ');
- // TODO: pagination
- return $rs;
- }
-
-
- /**
- * Fetch a list of all consumer tokens accessing the account of the given user.
- *
- * @param int user_id
- * @return array
- */
- public function listConsumerTokens ( $user_id )
- {
- $rs = $this->query_all_assoc('
- SELECT osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret,
- osr_enabled as enabled,
- osr_status as status,
- osr_application_uri as application_uri,
- osr_application_title as application_title,
- osr_application_descr as application_descr,
- ost_timestamp as timestamp,
- ost_token as token,
- ost_token_secret as token_secret,
- ost_referrer_host as token_referrer_host,
- osr_callback_uri as callback_uri
- FROM oauth_server_registry
- JOIN oauth_server_token
- ON ost_osr_id_ref = osr_id
- WHERE ost_usa_id_ref = \'%d\'
- AND ost_token_type = \'access\'
- AND ost_token_ttl >= NOW()
- ORDER BY osr_application_title
- ', $user_id);
- return $rs;
- }
-
-
- /**
- * Check an nonce/timestamp combination. Clears any nonce combinations
- * that are older than the one received.
- *
- * @param string consumer_key
- * @param string token
- * @param int timestamp
- * @param string nonce
- * @exception OAuthException2 thrown when the timestamp is not in sequence or nonce is not unique
- */
- public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce )
- {
- /* removed in Appendix A of RFC 5849
- $r = $this->query_row('
- SELECT MAX(osn_timestamp)
- FROM oauth_server_nonce
- WHERE osn_consumer_key = \'%s\'
- AND osn_token = \'%s\'
- ', $timestamp, $this->max_timestamp_skew, $consumer_key, $token);
-
- if (!empty($r) && $r[1] === 't')
- {
- throw new OAuthException2('Timestamp is out of sequence. Request rejected. Got '.$timestamp.' last max is '.$r[0].' allowed skew is '.$this->max_timestamp_skew);
- }
- */
-
- // Insert the new combination
- $this->query('
- INSERT INTO oauth_server_nonce (
- osn_consumer_key,
- osn_token,
- osn_timestamp,
- osn_nonce
- )
- VALUES (\'%s\', \'%s\', %d, \'%s\')',
- $consumer_key, $token, $timestamp, $nonce);
-
- if ($this->query_affected_rows() == 0)
- {
- throw new OAuthException2('Duplicate timestamp/nonce combination, possible replay attack. Request rejected.');
- }
-
- // Clean up all timestamps older than the one we just received
- $this->query('
- DELETE FROM oauth_server_nonce
- WHERE osn_consumer_key = \'%s\'
- AND osn_token = \'%s\'
- AND osn_timestamp < %d - %d
- ', $consumer_key, $token, $timestamp, $this->max_timestamp_skew);
- }
-
- /**
- * Add an entry to the log table
- *
- * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token)
- * @param string received
- * @param string sent
- * @param string base_string
- * @param string notes
- * @param int (optional) user_id
- */
- public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null )
- {
- $args = array();
- $ps = array();
- foreach ($keys as $key => $value)
- {
- $args[] = $value;
- $ps["olg_$key"] = "'%s'";
- }
-
- if (!empty($_SERVER['REMOTE_ADDR']))
- {
- $remote_ip = $_SERVER['REMOTE_ADDR'];
- }
- else if (!empty($_SERVER['REMOTE_IP']))
- {
- $remote_ip = $_SERVER['REMOTE_IP'];
- }
- else
- {
- $remote_ip = '0.0.0.0';
- }
-
- // Build the SQL
- $ps['olg_received'] = "'%s'"; $args[] = $this->makeUTF8($received);
- $ps['olg_sent'] = "'%s'"; $args[] = $this->makeUTF8($sent);
- $ps['olg_base_string'] = "'%s'"; $args[] = $base_string;
- $ps['olg_notes'] = "'%s'"; $args[] = $this->makeUTF8($notes);
- $ps['olg_usa_id_ref'] = "NULLIF('%d', '0')"; $args[] = $user_id;
- $ps['olg_remote_ip'] = "NULLIF('%s','0.0.0.0')::inet"; $args[] = $remote_ip;
-
- $this->query('
- INSERT INTO oauth_log ('.implode(',', array_keys($ps)) . ')
- VALUES(' . implode(',', $ps) . ')',
- $args
- );
- }
-
- /**
- * Get a page of entries from the log. Returns the last 100 records
- * matching the options given.
- *
- * @param array options
- * @param int user_id current user
- * @return array log records
- */
- public function listLog ( $options, $user_id )
- {
- $where = array();
- $args = array();
- if (empty($options))
- {
- $where[] = 'olg_usa_id_ref = \'%d\'';
- $args[] = $user_id;
- }
- else
- {
- foreach ($options as $option => $value)
- {
- if (strlen($value) > 0)
- {
- switch ($option)
- {
- case 'osr_consumer_key':
- case 'ocr_consumer_key':
- case 'ost_token':
- case 'oct_token':
- $where[] = 'olg_'.$option.' = \'%s\'';
- $args[] = $value;
- break;
- }
- }
- }
-
- $where[] = '(olg_usa_id_ref IS NULL OR olg_usa_id_ref = \'%d\')';
- $args[] = $user_id;
- }
-
- $rs = $this->query_all_assoc('
- SELECT olg_id,
- olg_osr_consumer_key AS osr_consumer_key,
- olg_ost_token AS ost_token,
- olg_ocr_consumer_key AS ocr_consumer_key,
- olg_oct_token AS oct_token,
- olg_usa_id_ref AS user_id,
- olg_received AS received,
- olg_sent AS sent,
- olg_base_string AS base_string,
- olg_notes AS notes,
- olg_timestamp AS timestamp,
- olg_remote_ip AS remote_ip
- FROM oauth_log
- WHERE '.implode(' AND ', $where).'
- ORDER BY olg_id DESC
- LIMIT 0,100', $args);
-
- return $rs;
- }
-
-
- /* ** Some simple helper functions for querying the pgsql db ** */
-
- /**
- * Perform a query, ignore the results
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- */
- protected function query ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = pg_query($this->conn, $sql)))
- {
- $this->sql_errcheck($sql);
- }
- $this->_lastAffectedRows = pg_affected_rows($res);
- if (is_resource($res))
- {
- pg_free_result($res);
- }
- }
-
-
- /**
- * Perform a query, return all rows
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_all_assoc ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = pg_query($this->conn, $sql)))
- {
- $this->sql_errcheck($sql);
- }
- $rs = array();
- while ($row = pg_fetch_assoc($res))
- {
- $rs[] = $row;
- }
- pg_free_result($res);
- return $rs;
- }
-
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_row_assoc ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
-
- if (!($res = pg_query($this->conn, $sql)))
- {
- $this->sql_errcheck($sql);
- }
- if ($row = pg_fetch_assoc($res))
- {
- $rs = $row;
- }
- else
- {
- $rs = false;
- }
- pg_free_result($res);
- return $rs;
- }
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- protected function query_row ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = pg_query($this->conn, $sql)))
- {
- $this->sql_errcheck($sql);
- }
- if ($row = pg_fetch_array($res))
- {
- $rs = $row;
- }
- else
- {
- $rs = false;
- }
- pg_free_result($res);
- return $rs;
- }
-
-
- /**
- * Perform a query, return the first column of the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return mixed
- */
- protected function query_one ( $sql )
- {
- $sql = $this->sql_printf(func_get_args());
- if (!($res = pg_query($this->conn, $sql)))
- {
- $this->sql_errcheck($sql);
- }
- $val = pg_fetch_row($res);
- if ($val && isset($val[0])) {
- $val = $val[0];
- }
- pg_free_result($res);
- return $val;
- }
-
-
- /**
- * Return the number of rows affected in the last query
- */
- protected function query_affected_rows ()
- {
- return $this->_lastAffectedRows;
- }
-
-
- /**
- * Return the id of the last inserted row
- *
- * @return int
- */
- protected function query_insert_id ( $tableName, $primaryKey = null )
- {
- $sequenceName = $tableName;
- if ($primaryKey) {
- $sequenceName .= "_$primaryKey";
- }
- $sequenceName .= '_seq';
-
- $sql = "
- SELECT
- CURRVAL('%s')
- ";
- $args = array($sql, $sequenceName);
- $sql = $this->sql_printf($args);
- if (!($res = pg_query($this->conn, $sql))) {
- return 0;
- }
- $val = pg_fetch_row($res, 0);
- if ($val && isset($val[0])) {
- $val = $val[0];
- }
-
- pg_free_result($res);
- return $val;
- }
-
-
- protected function sql_printf ( $args )
- {
- $sql = array_shift($args);
- if (count($args) == 1 && is_array($args[0]))
- {
- $args = $args[0];
- }
- $args = array_map(array($this, 'sql_escape_string'), $args);
- return vsprintf($sql, $args);
- }
-
-
- protected function sql_escape_string ( $s )
- {
- if (is_string($s))
- {
- return pg_escape_string($this->conn, $s);
- }
- else if (is_null($s))
- {
- return NULL;
- }
- else if (is_bool($s))
- {
- return intval($s);
- }
- else if (is_int($s) || is_float($s))
- {
- return $s;
- }
- else
- {
- return pg_escape_string($this->conn, strval($s));
- }
- }
-
-
- protected function sql_errcheck ( $sql )
- {
- $msg = "SQL Error in OAuthStorePostgreSQL: ".pg_last_error($this->conn)."\n\n" . $sql;
- throw new OAuthException2($msg);
- }
-}
diff --git a/vendor/oauth-php/library/store/OAuthStoreSQL.php b/vendor/oauth-php/library/store/OAuthStoreSQL.php
deleted file mode 100644
index 45a4887..0000000
--- a/vendor/oauth-php/library/store/OAuthStoreSQL.php
+++ /dev/null
@@ -1,1843 +0,0 @@
-<?php
-
-/**
- * Storage container for the oauth credentials, both server and consumer side.
- * Based on MySQL
- *
- * @version $Id: OAuthStoreMySQL.php 76 2010-01-27 19:51:17Z brunobg@corollarium.com $
- * @author Marc Worrell <marcw@pobox.com>
- * @date Nov 16, 2007 4:03:30 PM
- *
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-
-require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php';
-
-
-abstract class OAuthStoreSQL extends OAuthStoreAbstract
-{
- /**
- * Maximum delta a timestamp may be off from a previous timestamp.
- * Allows multiple consumers with some clock skew to work with the same token.
- * Unit is seconds, default max skew is 10 minutes.
- */
- protected $max_timestamp_skew = 600;
-
- /**
- * Default ttl for request tokens
- */
- protected $max_request_token_ttl = 3600;
-
-
- /**
- * Construct the OAuthStoreMySQL.
- * In the options you have to supply either:
- * - server, username, password and database (for a mysql_connect)
- * - conn (for the connection to be used)
- *
- * @param array options
- */
- function __construct ( $options = array() )
- {
- if (isset($options['conn']))
- {
- $this->conn = $options['conn'];
- }
- else
- {
- if (isset($options['server']))
- {
- $server = $options['server'];
- $username = $options['username'];
-
- if (isset($options['password']))
- {
- $this->conn = mysql_connect($server, $username, $options['password']);
- }
- else
- {
- $this->conn = mysql_connect($server, $username);
- }
- }
- else
- {
- // Try the default mysql connect
- $this->conn = mysql_connect();
- }
-
- if ($this->conn === false)
- {
- throw new OAuthException2('Could not connect to MySQL database: ' . mysql_error());
- }
-
- if (isset($options['database']))
- {
- if (!mysql_select_db($options['database'], $this->conn))
- {
- $this->sql_errcheck();
- }
- }
- $this->query('set character set utf8');
- }
- }
-
-
- /**
- * Find stored credentials for the consumer key and token. Used by an OAuth server
- * when verifying an OAuth request.
- *
- * @param string consumer_key
- * @param string token
- * @param string token_type false, 'request' or 'access'
- * @exception OAuthException2 when no secrets where found
- * @return array assoc (consumer_secret, token_secret, osr_id, ost_id, user_id)
- */
- public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' )
- {
- if ($token_type === false)
- {
- $rs = $this->query_row_assoc('
- SELECT osr_id,
- osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret
- FROM oauth_server_registry
- WHERE osr_consumer_key = \'%s\'
- AND osr_enabled = 1
- ',
- $consumer_key);
-
- if ($rs)
- {
- $rs['token'] = false;
- $rs['token_secret'] = false;
- $rs['user_id'] = false;
- $rs['ost_id'] = false;
- }
- }
- else
- {
- $rs = $this->query_row_assoc('
- SELECT osr_id,
- ost_id,
- ost_usa_id_ref as user_id,
- osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret,
- ost_token as token,
- ost_token_secret as token_secret
- FROM oauth_server_registry
- JOIN oauth_server_token
- ON ost_osr_id_ref = osr_id
- WHERE ost_token_type = \'%s\'
- AND osr_consumer_key = \'%s\'
- AND ost_token = \'%s\'
- AND osr_enabled = 1
- AND ost_token_ttl >= NOW()
- ',
- $token_type, $consumer_key, $token);
- }
-
- if (empty($rs))
- {
- throw new OAuthException2('The consumer_key "'.$consumer_key.'" token "'.$token.'" combination does not exist or is not enabled.');
- }
- return $rs;
- }
-
-
- /**
- * Find the server details for signing a request, always looks for an access token.
- * The returned credentials depend on which local user is making the request.
- *
- * The consumer_key must belong to the user or be public (user id is null)
- *
- * For signing we need all of the following:
- *
- * consumer_key consumer key associated with the server
- * consumer_secret consumer secret associated with this server
- * token access token associated with this server
- * token_secret secret for the access token
- * signature_methods signing methods supported by the server (array)
- *
- * @todo filter on token type (we should know how and with what to sign this request, and there might be old access tokens)
- * @param string uri uri of the server
- * @param int user_id id of the logged on user
- * @param string name (optional) name of the token (case sensitive)
- * @exception OAuthException2 when no credentials found
- * @return array
- */
- public function getSecretsForSignature ( $uri, $user_id, $name = '' )
- {
- // Find a consumer key and token for the given uri
- $ps = parse_url($uri);
- $host = isset($ps['host']) ? $ps['host'] : 'localhost';
- $path = isset($ps['path']) ? $ps['path'] : '';
-
- if (empty($path) || substr($path, -1) != '/')
- {
- $path .= '/';
- }
-
- // The owner of the consumer_key is either the user or nobody (public consumer key)
- $secrets = $this->query_row_assoc('
- SELECT ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- oct_token as token,
- oct_token_secret as token_secret,
- ocr_signature_methods as signature_methods
- FROM oauth_consumer_registry
- JOIN oauth_consumer_token ON oct_ocr_id_ref = ocr_id
- WHERE ocr_server_uri_host = \'%s\'
- AND ocr_server_uri_path = LEFT(\'%s\', LENGTH(ocr_server_uri_path))
- AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL)
- AND oct_usa_id_ref = \'%d\'
- AND oct_token_type = \'access\'
- AND oct_name = \'%s\'
- AND oct_token_ttl >= NOW()
- ORDER BY ocr_usa_id_ref DESC, ocr_consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC
- LIMIT 0,1
- ', $host, $path, $user_id, $user_id, $name
- );
-
- if (empty($secrets))
- {
- throw new OAuthException2('No server tokens available for '.$uri);
- }
- $secrets['signature_methods'] = explode(',', $secrets['signature_methods']);
- return $secrets;
- }
-
-
- /**
- * Get the token and token secret we obtained from a server.
- *
- * @param string consumer_key
- * @param string token
- * @param string token_type
- * @param int user_id the user owning the token
- * @param string name optional name for a named token
- * @exception OAuthException2 when no credentials found
- * @return array
- */
- public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' )
- {
- if ($token_type != 'request' && $token_type != 'access')
- {
- throw new OAuthException2('Unkown token type "'.$token_type.'", must be either "request" or "access"');
- }
-
- // Take the most recent token of the given type
- $r = $this->query_row_assoc('
- SELECT ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- oct_token as token,
- oct_token_secret as token_secret,
- oct_name as token_name,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri,
- IF(oct_token_ttl >= \'9999-12-31\', NULL, UNIX_TIMESTAMP(oct_token_ttl) - UNIX_TIMESTAMP(NOW())) as token_ttl
- FROM oauth_consumer_registry
- JOIN oauth_consumer_token
- ON oct_ocr_id_ref = ocr_id
- WHERE ocr_consumer_key = \'%s\'
- AND oct_token_type = \'%s\'
- AND oct_token = \'%s\'
- AND oct_usa_id_ref = %d
- AND oct_token_ttl >= NOW()
- ', $consumer_key, $token_type, $token, $user_id
- );
-
- if (empty($r))
- {
- throw new OAuthException2('Could not find a "'.$token_type.'" token for consumer "'.$consumer_key.'" and user '.$user_id);
- }
- if (isset($r['signature_methods']) && !empty($r['signature_methods']))
- {
- $r['signature_methods'] = explode(',',$r['signature_methods']);
- }
- else
- {
- $r['signature_methods'] = array();
- }
- return $r;
- }
-
-
- /**
- * Add a request token we obtained from a server.
- *
- * @todo remove old tokens for this user and this ocr_id
- * @param string consumer_key key of the server in the consumer registry
- * @param string token_type one of 'request' or 'access'
- * @param string token
- * @param string token_secret
- * @param int user_id the user owning the token
- * @param array options extra options, server_uri, name and token_ttl
- * @exception OAuthException2 when server is not known
- * @exception OAuthException2 when we received a duplicate token
- */
- public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() )
- {
- if ($token_type != 'request' && $token_type != 'access')
- {
- throw new OAuthException2('Unknown token type "'.$token_type.'", must be either "request" or "access"');
- }
-
- // Maximum time to live for this token
- if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
- {
- $ttl = 'DATE_ADD(NOW(), INTERVAL '.intval($options['token_ttl']).' SECOND)';
- }
- else if ($token_type == 'request')
- {
- $ttl = 'DATE_ADD(NOW(), INTERVAL '.$this->max_request_token_ttl.' SECOND)';
- }
- else
- {
- $ttl = "'9999-12-31'";
- }
-
- if (isset($options['server_uri']))
- {
- $ocr_id = $this->query_one('
- SELECT ocr_id
- FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL)
- AND ocr_server_uri = \'%s\'
- ', $consumer_key, $user_id, $options['server_uri']);
- }
- else
- {
- $ocr_id = $this->query_one('
- SELECT ocr_id
- FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL)
- ', $consumer_key, $user_id);
- }
-
- if (empty($ocr_id))
- {
- throw new OAuthException2('No server associated with consumer_key "'.$consumer_key.'"');
- }
-
- // Named tokens, unique per user/consumer key
- if (isset($options['name']) && $options['name'] != '')
- {
- $name = $options['name'];
- }
- else
- {
- $name = '';
- }
-
- // Delete any old tokens with the same type and name for this user/server combination
- $this->query('
- DELETE FROM oauth_consumer_token
- WHERE oct_ocr_id_ref = %d
- AND oct_usa_id_ref = %d
- AND oct_token_type = LOWER(\'%s\')
- AND oct_name = \'%s\'
- ',
- $ocr_id,
- $user_id,
- $token_type,
- $name);
-
- // Insert the new token
- $this->query('
- INSERT IGNORE INTO oauth_consumer_token
- SET oct_ocr_id_ref = %d,
- oct_usa_id_ref = %d,
- oct_name = \'%s\',
- oct_token = \'%s\',
- oct_token_secret= \'%s\',
- oct_token_type = LOWER(\'%s\'),
- oct_timestamp = NOW(),
- oct_token_ttl = '.$ttl.'
- ',
- $ocr_id,
- $user_id,
- $name,
- $token,
- $token_secret,
- $token_type);
-
- if (!$this->query_affected_rows())
- {
- throw new OAuthException2('Received duplicate token "'.$token.'" for the same consumer_key "'.$consumer_key.'"');
- }
- }
-
-
- /**
- * Delete a server key. This removes access to that site.
- *
- * @param string consumer_key
- * @param int user_id user registering this server
- * @param boolean user_is_admin
- */
- public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false )
- {
- if ($user_is_admin)
- {
- $this->query('
- DELETE FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL)
- ', $consumer_key, $user_id);
- }
- else
- {
- $this->query('
- DELETE FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND ocr_usa_id_ref = %d
- ', $consumer_key, $user_id);
- }
- }
-
-
- /**
- * Get a server from the consumer registry using the consumer key
- *
- * @param string consumer_key
- * @param int user_id
- * @param boolean user_is_admin (optional)
- * @exception OAuthException2 when server is not found
- * @return array
- */
- public function getServer ( $consumer_key, $user_id, $user_is_admin = false )
- {
- $r = $this->query_row_assoc('
- SELECT ocr_id as id,
- ocr_usa_id_ref as user_id,
- ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri
- FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL)
- ', $consumer_key, $user_id);
-
- if (empty($r))
- {
- throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" has been registered (for this user)');
- }
-
- if (isset($r['signature_methods']) && !empty($r['signature_methods']))
- {
- $r['signature_methods'] = explode(',',$r['signature_methods']);
- }
- else
- {
- $r['signature_methods'] = array();
- }
- return $r;
- }
-
-
-
- /**
- * Find the server details that might be used for a request
- *
- * The consumer_key must belong to the user or be public (user id is null)
- *
- * @param string uri uri of the server
- * @param int user_id id of the logged on user
- * @exception OAuthException2 when no credentials found
- * @return array
- */
- public function getServerForUri ( $uri, $user_id )
- {
- // Find a consumer key and token for the given uri
- $ps = parse_url($uri);
- $host = isset($ps['host']) ? $ps['host'] : 'localhost';
- $path = isset($ps['path']) ? $ps['path'] : '';
-
- if (empty($path) || substr($path, -1) != '/')
- {
- $path .= '/';
- }
-
- // The owner of the consumer_key is either the user or nobody (public consumer key)
- $server = $this->query_row_assoc('
- SELECT ocr_id as id,
- ocr_usa_id_ref as user_id,
- ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri
- FROM oauth_consumer_registry
- WHERE ocr_server_uri_host = \'%s\'
- AND ocr_server_uri_path = LEFT(\'%s\', LENGTH(ocr_server_uri_path))
- AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL)
- ORDER BY ocr_usa_id_ref DESC, consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC
- LIMIT 0,1
- ', $host, $path, $user_id
- );
-
- if (empty($server))
- {
- throw new OAuthException2('No server available for '.$uri);
- }
- $server['signature_methods'] = explode(',', $server['signature_methods']);
- return $server;
- }
-
-
- /**
- * Get a list of all server token this user has access to.
- *
- * @param int usr_id
- * @return array
- */
- public function listServerTokens ( $user_id )
- {
- $ts = $this->query_all_assoc('
- SELECT ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- oct_id as token_id,
- oct_token as token,
- oct_token_secret as token_secret,
- oct_usa_id_ref as user_id,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_server_uri_host as server_uri_host,
- ocr_server_uri_path as server_uri_path,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri,
- oct_timestamp as timestamp
- FROM oauth_consumer_registry
- JOIN oauth_consumer_token
- ON oct_ocr_id_ref = ocr_id
- WHERE oct_usa_id_ref = %d
- AND oct_token_type = \'access\'
- AND oct_token_ttl >= NOW()
- ORDER BY ocr_server_uri_host, ocr_server_uri_path
- ', $user_id);
- return $ts;
- }
-
-
- /**
- * Count how many tokens we have for the given server
- *
- * @param string consumer_key
- * @return int
- */
- public function countServerTokens ( $consumer_key )
- {
- $count = $this->query_one('
- SELECT COUNT(oct_id)
- FROM oauth_consumer_token
- JOIN oauth_consumer_registry
- ON oct_ocr_id_ref = ocr_id
- WHERE oct_token_type = \'access\'
- AND ocr_consumer_key = \'%s\'
- AND oct_token_ttl >= NOW()
- ', $consumer_key);
-
- return $count;
- }
-
-
- /**
- * Get a specific server token for the given user
- *
- * @param string consumer_key
- * @param string token
- * @param int user_id
- * @exception OAuthException2 when no such token found
- * @return array
- */
- public function getServerToken ( $consumer_key, $token, $user_id )
- {
- $ts = $this->query_row_assoc('
- SELECT ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- oct_token as token,
- oct_token_secret as token_secret,
- oct_usa_id_ref as usr_id,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_server_uri_host as server_uri_host,
- ocr_server_uri_path as server_uri_path,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri,
- oct_timestamp as timestamp
- FROM oauth_consumer_registry
- JOIN oauth_consumer_token
- ON oct_ocr_id_ref = ocr_id
- WHERE ocr_consumer_key = \'%s\'
- AND oct_usa_id_ref = %d
- AND oct_token_type = \'access\'
- AND oct_token = \'%s\'
- AND oct_token_ttl >= NOW()
- ', $consumer_key, $user_id, $token);
-
- if (empty($ts))
- {
- throw new OAuthException2('No such consumer key ('.$consumer_key.') and token ('.$token.') combination for user "'.$user_id.'"');
- }
- return $ts;
- }
-
-
- /**
- * Delete a token we obtained from a server.
- *
- * @param string consumer_key
- * @param string token
- * @param int user_id
- * @param boolean user_is_admin
- */
- public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false )
- {
- if ($user_is_admin)
- {
- $this->query('
- DELETE oauth_consumer_token
- FROM oauth_consumer_token
- JOIN oauth_consumer_registry
- ON oct_ocr_id_ref = ocr_id
- WHERE ocr_consumer_key = \'%s\'
- AND oct_token = \'%s\'
- ', $consumer_key, $token);
- }
- else
- {
- $this->query('
- DELETE oauth_consumer_token
- FROM oauth_consumer_token
- JOIN oauth_consumer_registry
- ON oct_ocr_id_ref = ocr_id
- WHERE ocr_consumer_key = \'%s\'
- AND oct_token = \'%s\'
- AND oct_usa_id_ref = %d
- ', $consumer_key, $token, $user_id);
- }
- }
-
-
- /**
- * Set the ttl of a server access token. This is done when the
- * server receives a valid request with a xoauth_token_ttl parameter in it.
- *
- * @param string consumer_key
- * @param string token
- * @param int token_ttl
- */
- public function setServerTokenTtl ( $consumer_key, $token, $token_ttl, $server_uri = NULL )
- {
- if ($token_ttl <= 0)
- {
- // Immediate delete when the token is past its ttl
- $this->deleteServerToken($consumer_key, $token, 0, true);
- }
- else if ( $server_uri )
- {
- // Set maximum time to live for this token
- $this->query('
- UPDATE oauth_consumer_token, oauth_consumer_registry
- SET ost_token_ttl = DATE_ADD(NOW(), INTERVAL %d SECOND)
- WHERE ocr_consumer_key = \'%s\'
- AND ocr_server_uri = \'%s\'
- AND oct_ocr_id_ref = ocr_id
- AND oct_token = \'%s\'
- ', $token_ttl, $server_uri, $consumer_key, $token);
- }
- else
- {
- // Set maximum time to live for this token
- $this->query('
- UPDATE oauth_consumer_token, oauth_consumer_registry
- SET ost_token_ttl = DATE_ADD(NOW(), INTERVAL %d SECOND)
- WHERE ocr_consumer_key = \'%s\'
- AND oct_ocr_id_ref = ocr_id
- AND oct_token = \'%s\'
- ', $token_ttl, $consumer_key, $token);
- }
- }
-
-
- /**
- * Get a list of all consumers from the consumer registry.
- * The consumer keys belong to the user or are public (user id is null)
- *
- * @param string q query term
- * @param int user_id
- * @return array
- */
- public function listServers ( $q = '', $user_id )
- {
- $q = trim(str_replace('%', '', $q));
- $args = array();
-
- if (!empty($q))
- {
- $where = ' WHERE ( ocr_consumer_key like \'%%%s%%\'
- OR ocr_server_uri like \'%%%s%%\'
- OR ocr_server_uri_host like \'%%%s%%\'
- OR ocr_server_uri_path like \'%%%s%%\')
- AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL)
- ';
-
- $args[] = $q;
- $args[] = $q;
- $args[] = $q;
- $args[] = $q;
- $args[] = $user_id;
- }
- else
- {
- $where = ' WHERE ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL';
- $args[] = $user_id;
- }
-
- $servers = $this->query_all_assoc('
- SELECT ocr_id as id,
- ocr_usa_id_ref as user_id,
- ocr_consumer_key as consumer_key,
- ocr_consumer_secret as consumer_secret,
- ocr_signature_methods as signature_methods,
- ocr_server_uri as server_uri,
- ocr_server_uri_host as server_uri_host,
- ocr_server_uri_path as server_uri_path,
- ocr_request_token_uri as request_token_uri,
- ocr_authorize_uri as authorize_uri,
- ocr_access_token_uri as access_token_uri
- FROM oauth_consumer_registry
- '.$where.'
- ORDER BY ocr_server_uri_host, ocr_server_uri_path
- ', $args);
- return $servers;
- }
-
-
- /**
- * Register or update a server for our site (we will be the consumer)
- *
- * (This is the registry at the consumers, registering servers ;-) )
- *
- * @param array server
- * @param int user_id user registering this server
- * @param boolean user_is_admin
- * @exception OAuthException2 when fields are missing or on duplicate consumer_key
- * @return consumer_key
- */
- public function updateServer ( $server, $user_id, $user_is_admin = false )
- {
- foreach (array('consumer_key', 'server_uri') as $f)
- {
- if (empty($server[$f]))
- {
- throw new OAuthException2('The field "'.$f.'" must be set and non empty');
- }
- }
-
- if (!empty($server['id']))
- {
- $exists = $this->query_one('
- SELECT ocr_id
- FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND ocr_id <> %d
- AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL)
- ', $server['consumer_key'], $server['id'], $user_id);
- }
- else
- {
- $exists = $this->query_one('
- SELECT ocr_id
- FROM oauth_consumer_registry
- WHERE ocr_consumer_key = \'%s\'
- AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL)
- ', $server['consumer_key'], $user_id);
- }
-
- if ($exists)
- {
- throw new OAuthException2('The server with key "'.$server['consumer_key'].'" has already been registered');
- }
-
- $parts = parse_url($server['server_uri']);
- $host = (isset($parts['host']) ? $parts['host'] : 'localhost');
- $path = (isset($parts['path']) ? $parts['path'] : '/');
-
- if (isset($server['signature_methods']))
- {
- if (is_array($server['signature_methods']))
- {
- $server['signature_methods'] = strtoupper(implode(',', $server['signature_methods']));
- }
- }
- else
- {
- $server['signature_methods'] = '';
- }
-
- // When the user is an admin, then the user can update the user_id of this record
- if ($user_is_admin && array_key_exists('user_id', $server))
- {
- if (is_null($server['user_id']))
- {
- $update_user = ', ocr_usa_id_ref = NULL';
- }
- else
- {
- $update_user = ', ocr_usa_id_ref = '.intval($server['user_id']);
- }
- }
- else
- {
- $update_user = '';
- }
-
- if (!empty($server['id']))
- {
- // Check if the current user can update this server definition
- if (!$user_is_admin)
- {
- $ocr_usa_id_ref = $this->query_one('
- SELECT ocr_usa_id_ref
- FROM oauth_consumer_registry
- WHERE ocr_id = %d
- ', $server['id']);
-
- if ($ocr_usa_id_ref != $user_id)
- {
- throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this server');
- }
- }
-
- // Update the consumer registration
- $this->query('
- UPDATE oauth_consumer_registry
- SET ocr_consumer_key = \'%s\',
- ocr_consumer_secret = \'%s\',
- ocr_server_uri = \'%s\',
- ocr_server_uri_host = \'%s\',
- ocr_server_uri_path = \'%s\',
- ocr_timestamp = NOW(),
- ocr_request_token_uri = \'%s\',
- ocr_authorize_uri = \'%s\',
- ocr_access_token_uri = \'%s\',
- ocr_signature_methods = \'%s\'
- '.$update_user.'
- WHERE ocr_id = %d
- ',
- $server['consumer_key'],
- $server['consumer_secret'],
- $server['server_uri'],
- strtolower($host),
- $path,
- isset($server['request_token_uri']) ? $server['request_token_uri'] : '',
- isset($server['authorize_uri']) ? $server['authorize_uri'] : '',
- isset($server['access_token_uri']) ? $server['access_token_uri'] : '',
- $server['signature_methods'],
- $server['id']
- );
- }
- else
- {
- if (empty($update_user))
- {
- // Per default the user owning the key is the user registering the key
- $update_user = ', ocr_usa_id_ref = '.intval($user_id);
- }
-
- $this->query('
- INSERT INTO oauth_consumer_registry
- SET ocr_consumer_key = \'%s\',
- ocr_consumer_secret = \'%s\',
- ocr_server_uri = \'%s\',
- ocr_server_uri_host = \'%s\',
- ocr_server_uri_path = \'%s\',
- ocr_timestamp = NOW(),
- ocr_request_token_uri = \'%s\',
- ocr_authorize_uri = \'%s\',
- ocr_access_token_uri = \'%s\',
- ocr_signature_methods = \'%s\'
- '.$update_user,
- $server['consumer_key'],
- $server['consumer_secret'],
- $server['server_uri'],
- strtolower($host),
- $path,
- isset($server['request_token_uri']) ? $server['request_token_uri'] : '',
- isset($server['authorize_uri']) ? $server['authorize_uri'] : '',
- isset($server['access_token_uri']) ? $server['access_token_uri'] : '',
- $server['signature_methods']
- );
-
- $ocr_id = $this->query_insert_id();
- }
- return $server['consumer_key'];
- }
-
-
- /**
- * Insert/update a new consumer with this server (we will be the server)
- * When this is a new consumer, then also generate the consumer key and secret.
- * Never updates the consumer key and secret.
- * When the id is set, then the key and secret must correspond to the entry
- * being updated.
- *
- * (This is the registry at the server, registering consumers ;-) )
- *
- * @param array consumer
- * @param int user_id user registering this consumer
- * @param boolean user_is_admin
- * @return string consumer key
- */
- public function updateConsumer ( $consumer, $user_id, $user_is_admin = false )
- {
- if (!$user_is_admin)
- {
- foreach (array('requester_name', 'requester_email') as $f)
- {
- if (empty($consumer[$f]))
- {
- throw new OAuthException2('The field "'.$f.'" must be set and non empty');
- }
- }
- }
-
- if (!empty($consumer['id']))
- {
- if (empty($consumer['consumer_key']))
- {
- throw new OAuthException2('The field "consumer_key" must be set and non empty');
- }
- if (!$user_is_admin && empty($consumer['consumer_secret']))
- {
- throw new OAuthException2('The field "consumer_secret" must be set and non empty');
- }
-
- // Check if the current user can update this server definition
- if (!$user_is_admin)
- {
- $osr_usa_id_ref = $this->query_one('
- SELECT osr_usa_id_ref
- FROM oauth_server_registry
- WHERE osr_id = %d
- ', $consumer['id']);
-
- if ($osr_usa_id_ref != $user_id)
- {
- throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this consumer');
- }
- }
- else
- {
- // User is an admin, allow a key owner to be changed or key to be shared
- if (array_key_exists('user_id',$consumer))
- {
- if (is_null($consumer['user_id']))
- {
- $this->query('
- UPDATE oauth_server_registry
- SET osr_usa_id_ref = NULL
- WHERE osr_id = %d
- ', $consumer['id']);
- }
- else
- {
- $this->query('
- UPDATE oauth_server_registry
- SET osr_usa_id_ref = %d
- WHERE osr_id = %d
- ', $consumer['user_id'], $consumer['id']);
- }
- }
- }
-
- $this->query('
- UPDATE oauth_server_registry
- SET osr_requester_name = \'%s\',
- osr_requester_email = \'%s\',
- osr_callback_uri = \'%s\',
- osr_application_uri = \'%s\',
- osr_application_title = \'%s\',
- osr_application_descr = \'%s\',
- osr_application_notes = \'%s\',
- osr_application_type = \'%s\',
- osr_application_commercial = IF(%d,1,0),
- osr_timestamp = NOW()
- WHERE osr_id = %d
- AND osr_consumer_key = \'%s\'
- AND osr_consumer_secret = \'%s\'
- ',
- $consumer['requester_name'],
- $consumer['requester_email'],
- isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '',
- isset($consumer['application_uri']) ? $consumer['application_uri'] : '',
- isset($consumer['application_title']) ? $consumer['application_title'] : '',
- isset($consumer['application_descr']) ? $consumer['application_descr'] : '',
- isset($consumer['application_notes']) ? $consumer['application_notes'] : '',
- isset($consumer['application_type']) ? $consumer['application_type'] : '',
- isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0,
- $consumer['id'],
- $consumer['consumer_key'],
- $consumer['consumer_secret']
- );
-
-
- $consumer_key = $consumer['consumer_key'];
- }
- else
- {
- $consumer_key = $this->generateKey(true);
- $consumer_secret= $this->generateKey();
-
- // When the user is an admin, then the user can be forced to something else that the user
- if ($user_is_admin && array_key_exists('user_id',$consumer))
- {
- if (is_null($consumer['user_id']))
- {
- $owner_id = 'NULL';
- }
- else
- {
- $owner_id = intval($consumer['user_id']);
- }
- }
- else
- {
- // No admin, take the user id as the owner id.
- $owner_id = intval($user_id);
- }
-
- $this->query('
- INSERT INTO oauth_server_registry
- SET osr_enabled = 1,
- osr_status = \'active\',
- osr_usa_id_ref = \'%s\',
- osr_consumer_key = \'%s\',
- osr_consumer_secret = \'%s\',
- osr_requester_name = \'%s\',
- osr_requester_email = \'%s\',
- osr_callback_uri = \'%s\',
- osr_application_uri = \'%s\',
- osr_application_title = \'%s\',
- osr_application_descr = \'%s\',
- osr_application_notes = \'%s\',
- osr_application_type = \'%s\',
- osr_application_commercial = IF(%d,1,0),
- osr_timestamp = NOW(),
- osr_issue_date = NOW()
- ',
- $owner_id,
- $consumer_key,
- $consumer_secret,
- $consumer['requester_name'],
- $consumer['requester_email'],
- isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '',
- isset($consumer['application_uri']) ? $consumer['application_uri'] : '',
- isset($consumer['application_title']) ? $consumer['application_title'] : '',
- isset($consumer['application_descr']) ? $consumer['application_descr'] : '',
- isset($consumer['application_notes']) ? $consumer['application_notes'] : '',
- isset($consumer['application_type']) ? $consumer['application_type'] : '',
- isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0
- );
- }
- return $consumer_key;
-
- }
-
-
-
- /**
- * Delete a consumer key. This removes access to our site for all applications using this key.
- *
- * @param string consumer_key
- * @param int user_id user registering this server
- * @param boolean user_is_admin
- */
- public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false )
- {
- if ($user_is_admin)
- {
- $this->query('
- DELETE FROM oauth_server_registry
- WHERE osr_consumer_key = \'%s\'
- AND (osr_usa_id_ref = %d OR osr_usa_id_ref IS NULL)
- ', $consumer_key, $user_id);
- }
- else
- {
- $this->query('
- DELETE FROM oauth_server_registry
- WHERE osr_consumer_key = \'%s\'
- AND osr_usa_id_ref = %d
- ', $consumer_key, $user_id);
- }
- }
-
-
-
- /**
- * Fetch a consumer of this server, by consumer_key.
- *
- * @param string consumer_key
- * @param int user_id
- * @param boolean user_is_admin (optional)
- * @exception OAuthException2 when consumer not found
- * @return array
- */
- public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false )
- {
- $consumer = $this->query_row_assoc('
- SELECT *
- FROM oauth_server_registry
- WHERE osr_consumer_key = \'%s\'
- ', $consumer_key);
-
- if (!is_array($consumer))
- {
- throw new OAuthException2('No consumer with consumer_key "'.$consumer_key.'"');
- }
-
- $c = array();
- foreach ($consumer as $key => $value)
- {
- $c[substr($key, 4)] = $value;
- }
- $c['user_id'] = $c['usa_id_ref'];
-
- if (!$user_is_admin && !empty($c['user_id']) && $c['user_id'] != $user_id)
- {
- throw new OAuthException2('No access to the consumer information for consumer_key "'.$consumer_key.'"');
- }
- return $c;
- }
-
-
- /**
- * Fetch the static consumer key for this provider. The user for the static consumer
- * key is NULL (no user, shared key). If the key did not exist then the key is created.
- *
- * @return string
- */
- public function getConsumerStatic ()
- {
- $consumer = $this->query_one('
- SELECT osr_consumer_key
- FROM oauth_server_registry
- WHERE osr_consumer_key LIKE \'sc-%%\'
- AND osr_usa_id_ref IS NULL
- ');
-
- if (empty($consumer))
- {
- $consumer_key = 'sc-'.$this->generateKey(true);
- $this->query('
- INSERT INTO oauth_server_registry
- SET osr_enabled = 1,
- osr_status = \'active\',
- osr_usa_id_ref = NULL,
- osr_consumer_key = \'%s\',
- osr_consumer_secret = \'\',
- osr_requester_name = \'\',
- osr_requester_email = \'\',
- osr_callback_uri = \'\',
- osr_application_uri = \'\',
- osr_application_title = \'Static shared consumer key\',
- osr_application_descr = \'\',
- osr_application_notes = \'Static shared consumer key\',
- osr_application_type = \'\',
- osr_application_commercial = 0,
- osr_timestamp = NOW(),
- osr_issue_date = NOW()
- ',
- $consumer_key
- );
-
- // Just make sure that if the consumer key is truncated that we get the truncated string
- $consumer = $this->getConsumerStatic();
- }
- return $consumer;
- }
-
-
- /**
- * Add an unautorized request token to our server.
- *
- * @param string consumer_key
- * @param array options (eg. token_ttl)
- * @return array (token, token_secret)
- */
- public function addConsumerRequestToken ( $consumer_key, $options = array() )
- {
- $token = $this->generateKey(true);
- $secret = !isset($options['secret']) ? $this->generateKey() : $options['secret'];
- $osr_id = $this->query_one('
- SELECT osr_id
- FROM oauth_server_registry
- WHERE osr_consumer_key = \'%s\'
- AND osr_enabled = 1
- ', $consumer_key);
-
- if (!$osr_id)
- {
- throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" or consumer_key is disabled');
- }
-
- if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
- {
- $ttl = intval($options['token_ttl']);
- }
- else
- {
- $ttl = $this->max_request_token_ttl;
- }
-
- if (!isset($options['oauth_callback'])) {
- // 1.0a Compatibility : store callback url associated with request token
- $options['oauth_callback']='oob';
- }
-
- $this->query('
- INSERT INTO oauth_server_token
- SET ost_osr_id_ref = %d,
- ost_usa_id_ref = 1,
- ost_token = \'%s\',
- ost_token_secret = \'%s\',
- ost_token_type = \'request\',
- ost_token_ttl = DATE_ADD(NOW(), INTERVAL %d SECOND),
- ost_callback_url = \'%s\'
- ON DUPLICATE KEY UPDATE
- ost_osr_id_ref = VALUES(ost_osr_id_ref),
- ost_usa_id_ref = VALUES(ost_usa_id_ref),
- ost_token = VALUES(ost_token),
- ost_token_secret = VALUES(ost_token_secret),
- ost_token_type = VALUES(ost_token_type),
- ost_token_ttl = VALUES(ost_token_ttl),
- ost_callback_url = VALUES(ost_callback_url),
- ost_timestamp = NOW()
- ', $osr_id, $token, $secret, $ttl, $options['oauth_callback']);
-
- return array('token'=>$token, 'token_secret'=>$secret, 'token_ttl'=>$ttl);
- }
-
-
- /**
- * Fetch the consumer request token, by request token.
- *
- * @param string token
- * @return array token and consumer details
- */
- public function getConsumerRequestToken ( $token )
- {
- $rs = $this->query_row_assoc('
- SELECT ost_token as token,
- ost_token_secret as token_secret,
- osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret,
- ost_token_type as token_type,
- ost_callback_url as callback_url,
- osr_application_title as application_title,
- osr_application_descr as application_descr,
- osr_application_uri as application_uri
- FROM oauth_server_token
- JOIN oauth_server_registry
- ON ost_osr_id_ref = osr_id
- WHERE ost_token_type = \'request\'
- AND ost_token = \'%s\'
- AND ost_token_ttl >= NOW()
- ', $token);
-
- return $rs;
- }
-
-
- /**
- * Delete a consumer token. The token must be a request or authorized token.
- *
- * @param string token
- */
- public function deleteConsumerRequestToken ( $token )
- {
- $this->query('
- DELETE FROM oauth_server_token
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'request\'
- ', $token);
- }
-
-
- /**
- * Upgrade a request token to be an authorized request token.
- *
- * @param string token
- * @param int user_id user authorizing the token
- * @param string referrer_host used to set the referrer host for this token, for user feedback
- */
- public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' )
- {
- // 1.0a Compatibility : create a token verifier
- $verifier = substr(md5(rand()),0,10);
-
- $this->query('
- UPDATE oauth_server_token
- SET ost_authorized = 1,
- ost_usa_id_ref = %d,
- ost_timestamp = NOW(),
- ost_referrer_host = \'%s\',
- ost_verifier = \'%s\'
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'request\'
- ', $user_id, $referrer_host, $verifier, $token);
- return $verifier;
- }
-
-
- /**
- * Count the consumer access tokens for the given consumer.
- *
- * @param string consumer_key
- * @return int
- */
- public function countConsumerAccessTokens ( $consumer_key )
- {
- $count = $this->query_one('
- SELECT COUNT(ost_id)
- FROM oauth_server_token
- JOIN oauth_server_registry
- ON ost_osr_id_ref = osr_id
- WHERE ost_token_type = \'access\'
- AND osr_consumer_key = \'%s\'
- AND ost_token_ttl >= NOW()
- ', $consumer_key);
-
- return $count;
- }
-
-
- /**
- * Exchange an authorized request token for new access token.
- *
- * @param string token
- * @param array options options for the token, token_ttl
- * @exception OAuthException2 when token could not be exchanged
- * @return array (token, token_secret)
- */
- public function exchangeConsumerRequestForAccessToken ( $token, $options = array() )
- {
- $new_token = $this->generateKey(true);
- $new_secret = $this->generateKey();
-
- // Maximum time to live for this token
- if (isset($options['token_ttl']) && is_numeric($options['token_ttl']))
- {
- $ttl_sql = 'DATE_ADD(NOW(), INTERVAL '.intval($options['token_ttl']).' SECOND)';
- }
- else
- {
- $ttl_sql = "'9999-12-31'";
- }
-
- if (isset($options['verifier'])) {
- $verifier = $options['verifier'];
-
- // 1.0a Compatibility : check token against oauth_verifier
- $this->query('
- UPDATE oauth_server_token
- SET ost_token = \'%s\',
- ost_token_secret = \'%s\',
- ost_token_type = \'access\',
- ost_timestamp = NOW(),
- ost_token_ttl = '.$ttl_sql.'
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'request\'
- AND ost_authorized = 1
- AND ost_token_ttl >= NOW()
- AND ost_verifier = \'%s\'
- ', $new_token, $new_secret, $token, $verifier);
- } else {
-
- // 1.0
- $this->query('
- UPDATE oauth_server_token
- SET ost_token = \'%s\',
- ost_token_secret = \'%s\',
- ost_token_type = \'access\',
- ost_timestamp = NOW(),
- ost_token_ttl = '.$ttl_sql.'
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'request\'
- AND ost_authorized = 1
- AND ost_token_ttl >= NOW()
- ', $new_token, $new_secret, $token);
- }
-
- if ($this->query_affected_rows() != 1)
- {
- throw new OAuthException2('Can\'t exchange request token "'.$token.'" for access token. No such token or not authorized');
- }
-
- $ret = array('token' => $new_token, 'token_secret' => $new_secret);
- $ttl = $this->query_one('
- SELECT IF(ost_token_ttl >= \'9999-12-31\', NULL, UNIX_TIMESTAMP(ost_token_ttl) - UNIX_TIMESTAMP(NOW())) as token_ttl
- FROM oauth_server_token
- WHERE ost_token = \'%s\'', $new_token);
-
- if (is_numeric($ttl))
- {
- $ret['token_ttl'] = intval($ttl);
- }
- return $ret;
- }
-
-
- /**
- * Fetch the consumer access token, by access token.
- *
- * @param string token
- * @param int user_id
- * @exception OAuthException2 when token is not found
- * @return array token and consumer details
- */
- public function getConsumerAccessToken ( $token, $user_id )
- {
- $rs = $this->query_row_assoc('
- SELECT ost_token as token,
- ost_token_secret as token_secret,
- ost_referrer_host as token_referrer_host,
- osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret,
- osr_application_uri as application_uri,
- osr_application_title as application_title,
- osr_application_descr as application_descr,
- osr_callback_uri as callback_uri
- FROM oauth_server_token
- JOIN oauth_server_registry
- ON ost_osr_id_ref = osr_id
- WHERE ost_token_type = \'access\'
- AND ost_token = \'%s\'
- AND ost_usa_id_ref = %d
- AND ost_token_ttl >= NOW()
- ', $token, $user_id);
-
- if (empty($rs))
- {
- throw new OAuthException2('No server_token "'.$token.'" for user "'.$user_id.'"');
- }
- return $rs;
- }
-
-
- /**
- * Delete a consumer access token.
- *
- * @param string token
- * @param int user_id
- * @param boolean user_is_admin
- */
- public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false )
- {
- if ($user_is_admin)
- {
- $this->query('
- DELETE FROM oauth_server_token
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'access\'
- ', $token);
- }
- else
- {
- $this->query('
- DELETE FROM oauth_server_token
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'access\'
- AND ost_usa_id_ref = %d
- ', $token, $user_id);
- }
- }
-
-
- /**
- * Set the ttl of a consumer access token. This is done when the
- * server receives a valid request with a xoauth_token_ttl parameter in it.
- *
- * @param string token
- * @param int ttl
- */
- public function setConsumerAccessTokenTtl ( $token, $token_ttl )
- {
- if ($token_ttl <= 0)
- {
- // Immediate delete when the token is past its ttl
- $this->deleteConsumerAccessToken($token, 0, true);
- }
- else
- {
- // Set maximum time to live for this token
- $this->query('
- UPDATE oauth_server_token
- SET ost_token_ttl = DATE_ADD(NOW(), INTERVAL %d SECOND)
- WHERE ost_token = \'%s\'
- AND ost_token_type = \'access\'
- ', $token_ttl, $token);
- }
- }
-
-
- /**
- * Fetch a list of all consumer keys, secrets etc.
- * Returns the public (user_id is null) and the keys owned by the user
- *
- * @param int user_id
- * @return array
- */
- public function listConsumers ( $user_id )
- {
- $rs = $this->query_all_assoc('
- SELECT osr_id as id,
- osr_usa_id_ref as user_id,
- osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret,
- osr_enabled as enabled,
- osr_status as status,
- osr_issue_date as issue_date,
- osr_application_uri as application_uri,
- osr_application_title as application_title,
- osr_application_descr as application_descr,
- osr_application_type as application_type,
- osr_application_commercial as application_commercial,
- osr_requester_name as requester_name,
- osr_requester_email as requester_email,
- osr_callback_uri as callback_uri
- FROM oauth_server_registry
- WHERE (osr_usa_id_ref = %d OR osr_usa_id_ref IS NULL)
- ORDER BY osr_application_title
- ', $user_id);
- return $rs;
- }
-
- /**
- * List of all registered applications. Data returned has not sensitive
- * information and therefore is suitable for public displaying.
- *
- * @param int $begin
- * @param int $total
- * @return array
- */
- public function listConsumerApplications($begin = 0, $total = 25)
- {
- $rs = $this->query_all_assoc('
- SELECT osr_id as id,
- osr_enabled as enabled,
- osr_status as status,
- osr_issue_date as issue_date,
- osr_application_uri as application_uri,
- osr_application_title as application_title,
- osr_application_descr as application_descr
- FROM oauth_server_registry
- ORDER BY osr_application_title
- ');
- // TODO: pagination
- return $rs;
- }
-
- /**
- * Fetch a list of all consumer tokens accessing the account of the given user.
- *
- * @param int user_id
- * @return array
- */
- public function listConsumerTokens ( $user_id )
- {
- $rs = $this->query_all_assoc('
- SELECT osr_consumer_key as consumer_key,
- osr_consumer_secret as consumer_secret,
- osr_enabled as enabled,
- osr_status as status,
- osr_application_uri as application_uri,
- osr_application_title as application_title,
- osr_application_descr as application_descr,
- ost_timestamp as timestamp,
- ost_token as token,
- ost_token_secret as token_secret,
- ost_referrer_host as token_referrer_host,
- osr_callback_uri as callback_uri
- FROM oauth_server_registry
- JOIN oauth_server_token
- ON ost_osr_id_ref = osr_id
- WHERE ost_usa_id_ref = %d
- AND ost_token_type = \'access\'
- AND ost_token_ttl >= NOW()
- ORDER BY osr_application_title
- ', $user_id);
- return $rs;
- }
-
-
- /**
- * Check an nonce/timestamp combination. Clears any nonce combinations
- * that are older than the one received.
- *
- * @param string consumer_key
- * @param string token
- * @param int timestamp
- * @param string nonce
- * @exception OAuthException2 thrown when the timestamp is not in sequence or nonce is not unique
- */
- public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce )
- {
- /* removed in Appendix A of RFC 5849
- $r = $this->query_row('
- SELECT MAX(osn_timestamp), MAX(osn_timestamp) > %d + %d
- FROM oauth_server_nonce
- WHERE osn_consumer_key = \'%s\'
- AND osn_token = \'%s\'
- ', $timestamp, $this->max_timestamp_skew, $consumer_key, $token);
-
- if (!empty($r) && $r[1])
- {
- throw new OAuthException2('Timestamp is out of sequence. Request rejected. Got '.$timestamp.' last max is '.$r[0].' allowed skew is '.$this->max_timestamp_skew);
- }*/
-
- // Insert the new combination
- $this->query('
- INSERT IGNORE INTO oauth_server_nonce
- SET osn_consumer_key = \'%s\',
- osn_token = \'%s\',
- osn_timestamp = %d,
- osn_nonce = \'%s\'
- ', $consumer_key, $token, $timestamp, $nonce);
-
- if ($this->query_affected_rows() == 0)
- {
- throw new OAuthException2('Duplicate timestamp/nonce combination, possible replay attack. Request rejected.');
- }
-
- // Clean up all timestamps older than the one we just received
- $this->query('
- DELETE FROM oauth_server_nonce
- WHERE osn_consumer_key = \'%s\'
- AND osn_token = \'%s\'
- AND osn_timestamp < %d - %d
- ', $consumer_key, $token, $timestamp, $this->max_timestamp_skew);
- }
-
-
- /**
- * Add an entry to the log table
- *
- * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token)
- * @param string received
- * @param string sent
- * @param string base_string
- * @param string notes
- * @param int (optional) user_id
- */
- public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null )
- {
- $args = array();
- $ps = array();
- foreach ($keys as $key => $value)
- {
- $args[] = $value;
- $ps[] = "olg_$key = '%s'";
- }
-
- if (!empty($_SERVER['REMOTE_ADDR']))
- {
- $remote_ip = $_SERVER['REMOTE_ADDR'];
- }
- else if (!empty($_SERVER['REMOTE_IP']))
- {
- $remote_ip = $_SERVER['REMOTE_IP'];
- }
- else
- {
- $remote_ip = '0.0.0.0';
- }
-
- // Build the SQL
- $ps[] = "olg_received = '%s'"; $args[] = $this->makeUTF8($received);
- $ps[] = "olg_sent = '%s'"; $args[] = $this->makeUTF8($sent);
- $ps[] = "olg_base_string= '%s'"; $args[] = $base_string;
- $ps[] = "olg_notes = '%s'"; $args[] = $this->makeUTF8($notes);
- $ps[] = "olg_usa_id_ref = NULLIF(%d,0)"; $args[] = $user_id;
- $ps[] = "olg_remote_ip = IFNULL(INET_ATON('%s'),0)"; $args[] = $remote_ip;
-
- $this->query('INSERT INTO oauth_log SET '.implode(',', $ps), $args);
- }
-
-
- /**
- * Get a page of entries from the log. Returns the last 100 records
- * matching the options given.
- *
- * @param array options
- * @param int user_id current user
- * @return array log records
- */
- public function listLog ( $options, $user_id )
- {
- $where = array();
- $args = array();
- if (empty($options))
- {
- $where[] = 'olg_usa_id_ref = %d';
- $args[] = $user_id;
- }
- else
- {
- foreach ($options as $option => $value)
- {
- if (strlen($value) > 0)
- {
- switch ($option)
- {
- case 'osr_consumer_key':
- case 'ocr_consumer_key':
- case 'ost_token':
- case 'oct_token':
- $where[] = 'olg_'.$option.' = \'%s\'';
- $args[] = $value;
- break;
- }
- }
- }
-
- $where[] = '(olg_usa_id_ref IS NULL OR olg_usa_id_ref = %d)';
- $args[] = $user_id;
- }
-
- $rs = $this->query_all_assoc('
- SELECT olg_id,
- olg_osr_consumer_key AS osr_consumer_key,
- olg_ost_token AS ost_token,
- olg_ocr_consumer_key AS ocr_consumer_key,
- olg_oct_token AS oct_token,
- olg_usa_id_ref AS user_id,
- olg_received AS received,
- olg_sent AS sent,
- olg_base_string AS base_string,
- olg_notes AS notes,
- olg_timestamp AS timestamp,
- INET_NTOA(olg_remote_ip) AS remote_ip
- FROM oauth_log
- WHERE '.implode(' AND ', $where).'
- ORDER BY olg_id DESC
- LIMIT 0,100', $args);
-
- return $rs;
- }
-
-
- /* ** Some simple helper functions for querying the mysql db ** */
-
- /**
- * Perform a query, ignore the results
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- */
- abstract protected function query ( $sql );
-
-
- /**
- * Perform a query, ignore the results
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- abstract protected function query_all_assoc ( $sql );
-
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- abstract protected function query_row_assoc ( $sql );
-
- /**
- * Perform a query, return the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return array
- */
- abstract protected function query_row ( $sql );
-
-
- /**
- * Perform a query, return the first column of the first row
- *
- * @param string sql
- * @param vararg arguments (for sprintf)
- * @return mixed
- */
- abstract protected function query_one ( $sql );
-
-
- /**
- * Return the number of rows affected in the last query
- */
- abstract protected function query_affected_rows ();
-
-
- /**
- * Return the id of the last inserted row
- *
- * @return int
- */
- abstract protected function query_insert_id ();
-
-
- abstract protected function sql_printf ( $args );
-
-
- abstract protected function sql_escape_string ( $s );
-
-
- abstract protected function sql_errcheck ( $sql );
-}
-
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/OAuthStoreSession.php b/vendor/oauth-php/library/store/OAuthStoreSession.php
deleted file mode 100644
index ecb30c8..0000000
--- a/vendor/oauth-php/library/store/OAuthStoreSession.php
+++ /dev/null
@@ -1,157 +0,0 @@
-<?php
-
-/**
- * OAuthSession is a really *dirty* storage. It's useful for testing and may
- * be enough for some very simple applications, but it's not recommended for
- * production use.
- *
- * @version $Id: OAuthStoreSession.php 183 2011-01-14 11:43:27Z brunobg@corollarium.com $
- * @author BBG
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php';
-
-class OAuthStoreSession extends OAuthStoreAbstract
-{
- private $session;
-
- /*
- * Takes two options: consumer_key and consumer_secret
- */
- public function __construct( $options = array() )
- {
- if (!session_id()) {
- session_start();
- }
- if(isset($options['consumer_key']) && isset($options['consumer_secret']))
- {
- $this->session = &$_SESSION['oauth_' . $options['consumer_key']];
- $this->session['consumer_key'] = $options['consumer_key'];
- $this->session['consumer_secret'] = $options['consumer_secret'];
- $this->session['signature_methods'] = array('HMAC-SHA1');
- $this->session['server_uri'] = $options['server_uri'];
- $this->session['request_token_uri'] = $options['request_token_uri'];
- $this->session['authorize_uri'] = $options['authorize_uri'];
- $this->session['access_token_uri'] = $options['access_token_uri'];
-
- }
- else
- {
- throw new OAuthException2("OAuthStoreSession needs consumer_key and consumer_secret");
- }
- }
-
- public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function getSecretsForSignature ( $uri, $user_id )
- {
- return $this->session;
- }
-
- public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '')
- {
- if ($consumer_key != $this->session['consumer_key']) {
- return array();
- }
- return array(
- 'consumer_key' => $consumer_key,
- 'consumer_secret' => $this->session['consumer_secret'],
- 'token' => $token,
- 'token_secret' => $this->session['token_secret'],
- 'token_name' => $name,
- 'signature_methods' => $this->session['signature_methods'],
- 'server_uri' => $this->session['server_uri'],
- 'request_token_uri' => $this->session['request_token_uri'],
- 'authorize_uri' => $this->session['authorize_uri'],
- 'access_token_uri' => $this->session['access_token_uri'],
- 'token_ttl' => 3600,
- );
- }
-
- public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() )
- {
- $this->session['token_type'] = $token_type;
- $this->session['token'] = $token;
- $this->session['token_secret'] = $token_secret;
- }
-
- public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function getServer( $consumer_key, $user_id, $user_is_admin = false ) {
- return array(
- 'id' => 0,
- 'user_id' => $user_id,
- 'consumer_key' => $this->session['consumer_key'],
- 'consumer_secret' => $this->session['consumer_secret'],
- 'signature_methods' => $this->session['signature_methods'],
- 'server_uri' => $this->session['server_uri'],
- 'request_token_uri' => $this->session['request_token_uri'],
- 'authorize_uri' => $this->session['authorize_uri'],
- 'access_token_uri' => $this->session['access_token_uri'],
- );
- }
-
- public function getServerForUri ( $uri, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function listServerTokens ( $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function countServerTokens ( $consumer_key ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function getServerToken ( $consumer_key, $token, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) {
- // TODO
- }
-
- public function setServerTokenTtl ( $consumer_key, $token, $token_ttl, $server_uri = NULL )
- {
- //This method just needs to exist. It doesn't have to do anything!
- }
-
- public function listServers ( $q = '', $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function updateServer ( $server, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
-
- public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function getConsumerStatic () { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
-
- public function addConsumerRequestToken ( $consumer_key, $options = array() ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function getConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function deleteConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function countConsumerAccessTokens ( $consumer_key ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function getConsumerAccessToken ( $token, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function setConsumerAccessTokenTtl ( $token, $ttl ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
-
- public function listConsumers ( $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function listConsumerApplications( $begin = 0, $total = 25 ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function listConsumerTokens ( $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
-
- public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
-
- public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
- public function listLog ( $options, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
-
- public function install () { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); }
-}
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/mysql/install.php b/vendor/oauth-php/library/store/mysql/install.php
deleted file mode 100644
index 0015da5..0000000
--- a/vendor/oauth-php/library/store/mysql/install.php
+++ /dev/null
@@ -1,32 +0,0 @@
-<?php
-
-/**
- * Installs all tables in the mysql.sql file, using the default mysql connection
- */
-
-/* Change and uncomment this when you need to: */
-
-/*
-mysql_connect('localhost', 'root');
-if (mysql_errno())
-{
- die(' Error '.mysql_errno().': '.mysql_error());
-}
-mysql_select_db('test');
-*/
-
-$sql = file_get_contents(dirname(__FILE__) . '/mysql.sql');
-$ps = explode('#--SPLIT--', $sql);
-
-foreach ($ps as $p)
-{
- $p = preg_replace('/^\s*#.*$/m', '', $p);
-
- mysql_query($p);
- if (mysql_errno())
- {
- die(' Error '.mysql_errno().': '.mysql_error());
- }
-}
-
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/mysql/mysql.sql b/vendor/oauth-php/library/store/mysql/mysql.sql
deleted file mode 100644
index ca8eb08..0000000
--- a/vendor/oauth-php/library/store/mysql/mysql.sql
+++ /dev/null
@@ -1,240 +0,0 @@
-# Datamodel for OAuthStoreMySQL
-#
-# You need to add the foreign key constraints for the user ids your are using.
-# I have commented the constraints out, just look for 'usa_id_ref' to enable them.
-#
-# The --SPLIT-- markers are used by the install.php script
-#
-# @version $Id: mysql.sql 188 2011-02-25 14:40:26Z scherpenisse $
-# @author Marc Worrell
-#
-
-# Changes:
-#
-# 2011-02-25
-# ALTER TABLE oauth_consumer_token MODIFY oct_token varchar(255) binary not null;
-# ALTER TABLE oauth_consumer_token MODIFY oct_token_secret varchar(255) binary not null;
-#
-# 2010-09-15
-# ALTER TABLE oauth_server_token MODIFY ost_referrer_host varchar(128) not null default '';
-#
-# 2010-07-22
-# ALTER TABLE oauth_consumer_registry DROP INDEX ocr_consumer_key;
-# ALTER TABLE oauth_consumer_registry ADD UNIQUE ocr_consumer_key(ocr_consumer_key,ocr_usa_id_ref,ocr_server_uri)
-#
-# 2010-04-20 (on 103 and 110)
-# ALTER TABLE oauth_consumer_registry MODIFY ocr_consumer_key varchar(128) binary not null;
-# ALTER TABLE oauth_consumer_registry MODIFY ocr_consumer_secret varchar(128) binary not null;
-#
-# 2010-04-20 (on 103 and 110)
-# ALTER TABLE oauth_server_token ADD ost_verifier char(10);
-# ALTER TABLE oauth_server_token ADD ost_callback_url varchar(512);
-#
-# 2008-10-15 (on r48) Added ttl to consumer and server tokens, added named server tokens
-#
-# ALTER TABLE oauth_server_token
-# ADD ost_token_ttl datetime not null default '9999-12-31',
-# ADD KEY (ost_token_ttl);
-#
-# ALTER TABLE oauth_consumer_token
-# ADD oct_name varchar(64) binary not null default '',
-# ADD oct_token_ttl datetime not null default '9999-12-31',
-# DROP KEY oct_usa_id_ref,
-# ADD UNIQUE KEY (oct_usa_id_ref, oct_ocr_id_ref, oct_token_type, oct_name),
-# ADD KEY (oct_token_ttl);
-#
-# 2008-09-09 (on r5) Added referrer host to server access token
-#
-# ALTER TABLE oauth_server_token ADD ost_referrer_host VARCHAR(128) NOT NULL;
-#
-
-
-#
-# Log table to hold all OAuth request when you enabled logging
-#
-
-CREATE TABLE IF NOT EXISTS oauth_log (
- olg_id int(11) not null auto_increment,
- olg_osr_consumer_key varchar(64) binary,
- olg_ost_token varchar(64) binary,
- olg_ocr_consumer_key varchar(64) binary,
- olg_oct_token varchar(64) binary,
- olg_usa_id_ref int(11),
- olg_received text not null,
- olg_sent text not null,
- olg_base_string text not null,
- olg_notes text not null,
- olg_timestamp timestamp not null default current_timestamp,
- olg_remote_ip bigint not null,
-
- primary key (olg_id),
- key (olg_osr_consumer_key, olg_id),
- key (olg_ost_token, olg_id),
- key (olg_ocr_consumer_key, olg_id),
- key (olg_oct_token, olg_id),
- key (olg_usa_id_ref, olg_id)
-
-# , foreign key (olg_usa_id_ref) references any_user_auth (usa_id_ref)
-# on update cascade
-# on delete cascade
-) engine=InnoDB default charset=utf8;
-
-#--SPLIT--
-
-#
-# /////////////////// CONSUMER SIDE ///////////////////
-#
-
-# This is a registry of all consumer codes we got from other servers
-# The consumer_key/secret is obtained from the server
-# We also register the server uri, so that we can find the consumer key and secret
-# for a certain server. From that server we can check if we have a token for a
-# particular user.
-
-CREATE TABLE IF NOT EXISTS oauth_consumer_registry (
- ocr_id int(11) not null auto_increment,
- ocr_usa_id_ref int(11),
- ocr_consumer_key varchar(128) binary not null,
- ocr_consumer_secret varchar(128) binary not null,
- ocr_signature_methods varchar(255) not null default 'HMAC-SHA1,PLAINTEXT',
- ocr_server_uri varchar(255) not null,
- ocr_server_uri_host varchar(128) not null,
- ocr_server_uri_path varchar(128) binary not null,
-
- ocr_request_token_uri varchar(255) not null,
- ocr_authorize_uri varchar(255) not null,
- ocr_access_token_uri varchar(255) not null,
- ocr_timestamp timestamp not null default current_timestamp,
-
- primary key (ocr_id),
- unique key (ocr_consumer_key, ocr_usa_id_ref, ocr_server_uri),
- key (ocr_server_uri),
- key (ocr_server_uri_host, ocr_server_uri_path),
- key (ocr_usa_id_ref)
-
-# , foreign key (ocr_usa_id_ref) references any_user_auth(usa_id_ref)
-# on update cascade
-# on delete set null
-) engine=InnoDB default charset=utf8;
-
-#--SPLIT--
-
-# Table used to sign requests for sending to a server by the consumer
-# The key is defined for a particular user. Only one single named
-# key is allowed per user/server combination
-
-CREATE TABLE IF NOT EXISTS oauth_consumer_token (
- oct_id int(11) not null auto_increment,
- oct_ocr_id_ref int(11) not null,
- oct_usa_id_ref int(11) not null,
- oct_name varchar(64) binary not null default '',
- oct_token varchar(255) binary not null,
- oct_token_secret varchar(255) binary not null,
- oct_token_type enum('request','authorized','access'),
- oct_token_ttl datetime not null default '9999-12-31',
- oct_timestamp timestamp not null default current_timestamp,
-
- primary key (oct_id),
- unique key (oct_ocr_id_ref, oct_token),
- unique key (oct_usa_id_ref, oct_ocr_id_ref, oct_token_type, oct_name),
- key (oct_token_ttl),
-
- foreign key (oct_ocr_id_ref) references oauth_consumer_registry (ocr_id)
- on update cascade
- on delete cascade
-
-# , foreign key (oct_usa_id_ref) references any_user_auth (usa_id_ref)
-# on update cascade
-# on delete cascade
-) engine=InnoDB default charset=utf8;
-
-#--SPLIT--
-
-
-#
-# ////////////////// SERVER SIDE /////////////////
-#
-
-# Table holding consumer key/secret combos an user issued to consumers.
-# Used for verification of incoming requests.
-
-CREATE TABLE IF NOT EXISTS oauth_server_registry (
- osr_id int(11) not null auto_increment,
- osr_usa_id_ref int(11),
- osr_consumer_key varchar(64) binary not null,
- osr_consumer_secret varchar(64) binary not null,
- osr_enabled tinyint(1) not null default '1',
- osr_status varchar(16) not null,
- osr_requester_name varchar(64) not null,
- osr_requester_email varchar(64) not null,
- osr_callback_uri varchar(255) not null,
- osr_application_uri varchar(255) not null,
- osr_application_title varchar(80) not null,
- osr_application_descr text not null,
- osr_application_notes text not null,
- osr_application_type varchar(20) not null,
- osr_application_commercial tinyint(1) not null default '0',
- osr_issue_date datetime not null,
- osr_timestamp timestamp not null default current_timestamp,
-
- primary key (osr_id),
- unique key (osr_consumer_key),
- key (osr_usa_id_ref)
-
-# , foreign key (osr_usa_id_ref) references any_user_auth(usa_id_ref)
-# on update cascade
-# on delete set null
-) engine=InnoDB default charset=utf8;
-
-#--SPLIT--
-
-# Nonce used by a certain consumer, every used nonce should be unique, this prevents
-# replaying attacks. We need to store all timestamp/nonce combinations for the
-# maximum timestamp received.
-
-CREATE TABLE IF NOT EXISTS oauth_server_nonce (
- osn_id int(11) not null auto_increment,
- osn_consumer_key varchar(64) binary not null,
- osn_token varchar(64) binary not null,
- osn_timestamp bigint not null,
- osn_nonce varchar(80) binary not null,
-
- primary key (osn_id),
- unique key (osn_consumer_key, osn_token, osn_timestamp, osn_nonce)
-) engine=InnoDB default charset=utf8;
-
-#--SPLIT--
-
-# Table used to verify signed requests sent to a server by the consumer
-# When the verification is succesful then the associated user id is returned.
-
-CREATE TABLE IF NOT EXISTS oauth_server_token (
- ost_id int(11) not null auto_increment,
- ost_osr_id_ref int(11) not null,
- ost_usa_id_ref int(11) not null,
- ost_token varchar(64) binary not null,
- ost_token_secret varchar(64) binary not null,
- ost_token_type enum('request','access'),
- ost_authorized tinyint(1) not null default '0',
- ost_referrer_host varchar(128) not null default '',
- ost_token_ttl datetime not null default '9999-12-31',
- ost_timestamp timestamp not null default current_timestamp,
- ost_verifier char(10),
- ost_callback_url varchar(512),
-
- primary key (ost_id),
- unique key (ost_token),
- key (ost_osr_id_ref),
- key (ost_token_ttl),
-
- foreign key (ost_osr_id_ref) references oauth_server_registry (osr_id)
- on update cascade
- on delete cascade
-
-# , foreign key (ost_usa_id_ref) references any_user_auth (usa_id_ref)
-# on update cascade
-# on delete cascade
-) engine=InnoDB default charset=utf8;
-
-
-
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql b/vendor/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql
deleted file mode 100644
index 3d4fa22..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql
+++ /dev/null
@@ -1,114 +0,0 @@
-CREATE TABLE oauth_log
-(
- olg_id number,
- olg_osr_consumer_key varchar2(64),
- olg_ost_token varchar2(64),
- olg_ocr_consumer_key varchar2(64),
- olg_oct_token varchar2(64),
- olg_usa_id_ref number,
- olg_received varchar2(500),
- olg_sent varchar2(500),
- olg_base_string varchar2(500),
- olg_notes varchar2(500),
- olg_timestamp date default sysdate,
- olg_remote_ip varchar2(50)
-);
-
-alter table oauth_log
- add constraint oauth_log_pk primary key (olg_id);
-
-
-CREATE TABLE oauth_consumer_registry
-(
- ocr_id number,
- ocr_usa_id_ref number,
- ocr_consumer_key varchar2(64),
- ocr_consumer_secret varchar2(64),
- ocr_signature_methods varchar2(255)default 'HMAC-SHA1,PLAINTEXT',
- ocr_server_uri varchar2(255),
- ocr_server_uri_host varchar2(128),
- ocr_server_uri_path varchar2(128),
- ocr_request_token_uri varchar2(255),
- ocr_authorize_uri varchar2(255),
- ocr_access_token_uri varchar2(255),
- ocr_timestamp date default sysdate
-)
-
-alter table oauth_consumer_registry
- add constraint oauth_consumer_registry_pk primary key (ocr_id);
-
-
-CREATE TABLE oauth_consumer_token
-(
- oct_id number,
- oct_ocr_id_ref number,
- oct_usa_id_ref number,
- oct_name varchar2(64) default '',
- oct_token varchar2(64),
- oct_token_secret varchar2(64),
- oct_token_type varchar2(20), -- enum('request','authorized','access'),
- oct_token_ttl date default TO_DATE('9999.12.31', 'yyyy.mm.dd'),
- oct_timestamp date default sysdate
-);
-
-alter table oauth_consumer_token
- add constraint oauth_consumer_token_pk primary key (oct_id);
-
-
-CREATE TABLE oauth_server_registry
-(
- osr_id number,
- osr_usa_id_ref number,
- osr_consumer_key varchar2(64),
- osr_consumer_secret varchar2(64),
- osr_enabled integer default '1',
- osr_status varchar2(16),
- osr_requester_name varchar2(64),
- osr_requester_email varchar2(64),
- osr_callback_uri varchar2(255),
- osr_application_uri varchar2(255),
- osr_application_title varchar2(80),
- osr_application_descr varchar2(500),
- osr_application_notes varchar2(500),
- osr_application_type varchar2(20),
- osr_application_commercial integer default '0',
- osr_issue_date date,
- osr_timestamp date default sysdate
-);
-
-
-alter table oauth_server_registry
- add constraint oauth_server_registry_pk primary key (osr_id);
-
-
-CREATE TABLE oauth_server_nonce
-(
- osn_id number,
- osn_consumer_key varchar2(64),
- osn_token varchar2(64),
- osn_timestamp number,
- osn_nonce varchar2(80)
-);
-
-alter table oauth_server_nonce
- add constraint oauth_server_nonce_pk primary key (osn_id);
-
-
-CREATE TABLE oauth_server_token
-(
- ost_id number,
- ost_osr_id_ref number,
- ost_usa_id_ref number,
- ost_token varchar2(64),
- ost_token_secret varchar2(64),
- ost_token_type varchar2(20), -- enum('request','access'),
- ost_authorized integer default '0',
- ost_referrer_host varchar2(128),
- ost_token_ttl date default TO_DATE('9999.12.31', 'yyyy.mm.dd'),
- ost_timestamp date default sysdate,
- ost_verifier varchar2(10),
- ost_callback_url varchar2(512)
-);
-
-alter table oauth_server_token
- add constraint oauth_server_token_pk primary key (ost_id); \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql b/vendor/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql
deleted file mode 100644
index 53e4227..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql
+++ /dev/null
@@ -1,9 +0,0 @@
-CREATE SEQUENCE SEQ_OCT_ID NOCACHE;
-
-CREATE SEQUENCE SEQ_OCR_ID NOCACHE;
-
-CREATE SEQUENCE SEQ_OSR_ID NOCACHE;
-
-CREATE SEQUENCE SEQ_OSN_ID NOCACHE;
-
-CREATE SEQUENCE SEQ_OLG_ID NOCACHE;
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc
deleted file mode 100644
index efb9536..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc
+++ /dev/null
@@ -1,71 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_ADD_CONSUMER_REQUEST_TOKEN
-(
-P_TOKEN_TTL IN NUMBER, -- IN SECOND
-P_CONSUMER_KEY IN VARCHAR2,
-P_TOKEN IN VARCHAR2,
-P_TOKEN_SECRET IN VARCHAR2,
-P_CALLBACK_URL IN VARCHAR2,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Add an unautorized request token to our server.
-
-V_OSR_ID NUMBER;
-V_OSR_ID_REF NUMBER;
-
-V_EXC_NO_SERVER_EXIST EXCEPTION;
-BEGIN
-
- P_RESULT := 0;
-
- BEGIN
- SELECT OSR_ID INTO V_OSR_ID
- FROM OAUTH_SERVER_REGISTRY
- WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY
- AND OSR_ENABLED = 1;
- EXCEPTION
- WHEN NO_DATA_FOUND THEN
- RAISE V_EXC_NO_SERVER_EXIST;
- END;
-
-
-BEGIN
- SELECT OST_OSR_ID_REF INTO V_OSR_ID_REF
- FROM OAUTH_SERVER_TOKEN
- WHERE OST_OSR_ID_REF = V_OSR_ID;
-
- UPDATE OAUTH_SERVER_TOKEN
- SET OST_OSR_ID_REF = V_OSR_ID,
- OST_USA_ID_REF = 1,
- OST_TOKEN = P_TOKEN,
- OST_TOKEN_SECRET = P_TOKEN_SECRET,
- OST_TOKEN_TYPE = 'REQUEST',
- OST_TOKEN_TTL = SYSDATE + (P_TOKEN_TTL/(24*60*60)),
- OST_CALLBACK_URL = P_CALLBACK_URL,
- OST_TIMESTAMP = SYSDATE
- WHERE OST_OSR_ID_REF = V_OSR_ID_REF;
-
-
- EXCEPTION
- WHEN NO_DATA_FOUND THEN
-
- INSERT INTO OAUTH_SERVER_TOKEN
- (OST_ID, OST_OSR_ID_REF, OST_USA_ID_REF, OST_TOKEN, OST_TOKEN_SECRET, OST_TOKEN_TYPE,
- OST_TOKEN_TTL, OST_CALLBACK_URL)
- VALUES
- (SEQ_OCT_ID.NEXTVAL, V_OSR_ID, 1, P_TOKEN, P_TOKEN_SECRET, 'REQUEST', SYSDATE + (P_TOKEN_TTL/(24*60*60)),
- P_CALLBACK_URL);
-
- END;
-
-
-EXCEPTION
-WHEN V_EXC_NO_SERVER_EXIST THEN
-P_RESULT := 2; -- NO_SERVER_EXIST
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc
deleted file mode 100644
index 329499d..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc
+++ /dev/null
@@ -1,31 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_ADD_LOG
-(
-P_RECEIVED IN VARCHAR2,
-P_SENT IN VARCHAR2,
-P_BASE_STRING IN VARCHAR2,
-P_NOTES IN VARCHAR2,
-P_USA_ID_REF IN NUMBER,
-P_REMOTE_IP IN VARCHAR2,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Add an entry to the log table
-
-BEGIN
-
- P_RESULT := 0;
-
- INSERT INTO oauth_log
- (OLG_ID, olg_received, olg_sent, olg_base_string, olg_notes, olg_usa_id_ref, olg_remote_ip)
- VALUES
- (SEQ_OLG_ID.NEXTVAL, P_RECEIVED, P_SENT, P_BASE_STRING, P_NOTES, NVL(P_USA_ID_REF, 0), P_REMOTE_IP);
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc
deleted file mode 100644
index 371134c..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc
+++ /dev/null
@@ -1,55 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_ADD_SERVER_TOKEN
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_USER_ID IN NUMBER,
-P_NAME IN VARCHAR2,
-P_TOKEN_TYPE IN VARCHAR2,
-P_TOKEN IN VARCHAR2,
-P_TOKEN_SECRET IN VARCHAR2,
-P_TOKEN_INTERVAL_IN_SEC IN NUMBER,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- Add a request token we obtained from a server.
-V_OCR_ID NUMBER;
-V_TOKEN_TTL DATE;
-
-V_EXC_INVALID_CONSUMER_KEY EXCEPTION;
-BEGIN
-P_RESULT := 0;
-
- BEGIN
- SELECT OCR_ID INTO V_OCR_ID FROM OAUTH_CONSUMER_REGISTRY
- WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY AND OCR_USA_ID_REF = P_USER_ID;
- EXCEPTION
- WHEN NO_DATA_FOUND THEN
- RAISE V_EXC_INVALID_CONSUMER_KEY;
- END;
-
- DELETE FROM OAUTH_CONSUMER_TOKEN
- WHERE OCT_OCR_ID_REF = V_OCR_ID
- AND OCT_USA_ID_REF = P_USER_ID
- AND UPPER(OCT_TOKEN_TYPE) = UPPER(P_TOKEN_TYPE)
- AND OCT_NAME = P_NAME;
-
- IF P_TOKEN_INTERVAL_IN_SEC IS NOT NULL THEN
- V_TOKEN_TTL := SYSDATE + (P_TOKEN_INTERVAL_IN_SEC/(24*60*60));
- ELSE
- V_TOKEN_TTL := TO_DATE('9999.12.31', 'yyyy.mm.dd');
- END IF;
-
- INSERT INTO OAUTH_CONSUMER_TOKEN
- (OCT_ID, OCT_OCR_ID_REF,OCT_USA_ID_REF, OCT_NAME, OCT_TOKEN, OCT_TOKEN_SECRET, OCT_TOKEN_TYPE, OCT_TIMESTAMP, OCT_TOKEN_TTL)
- VALUES
- (SEQ_OCT_ID.NEXTVAL, V_OCR_ID, P_USER_ID, P_NAME, P_TOKEN, P_TOKEN_SECRET, UPPER(P_TOKEN_TYPE), SYSDATE, V_TOKEN_TTL);
-
-EXCEPTION
-WHEN V_EXC_INVALID_CONSUMER_KEY THEN
-P_RESULT := 2; -- INVALID_CONSUMER_KEY
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc
deleted file mode 100644
index c369349..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc
+++ /dev/null
@@ -1,32 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_AUTH_CONSUMER_REQ_TOKEN
-(
-P_USER_ID IN NUMBER,
-P_REFERRER_HOST IN VARCHAR2,
-P_VERIFIER IN VARCHAR2,
-P_TOKEN IN VARCHAR2,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Fetch the consumer request token, by request token.
-BEGIN
-P_RESULT := 0;
-
-
-UPDATE OAUTH_SERVER_TOKEN
- SET OST_AUTHORIZED = 1,
- OST_USA_ID_REF = P_USER_ID,
- OST_TIMESTAMP = SYSDATE,
- OST_REFERRER_HOST = P_REFERRER_HOST,
- OST_VERIFIER = P_VERIFIER
- WHERE OST_TOKEN = P_TOKEN
- AND OST_TOKEN_TYPE = 'REQUEST';
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc
deleted file mode 100644
index 765dd3b..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc
+++ /dev/null
@@ -1,82 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_CHECK_SERVER_NONCE
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_TOKEN IN VARCHAR2,
-P_TIMESTAMP IN NUMBER,
-P_MAX_TIMESTAMP_SKEW IN NUMBER,
-P_NONCE IN VARCHAR2,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Check an nonce/timestamp combination. Clears any nonce combinations
- -- that are older than the one received.
-V_IS_MAX NUMBER;
-V_MAX_TIMESTAMP NUMBER;
-V_IS_DUPLICATE_TIMESTAMP NUMBER;
-
-V_EXC_INVALID_TIMESTAMP EXCEPTION;
-V_EXC_DUPLICATE_TIMESTAMP EXCEPTION;
-BEGIN
-
- P_RESULT := 0;
-
- -- removed in Appendix A of RFC 5849
- -- BEGIN
- -- SELECT MAX(OSN_TIMESTAMP),
- -- CASE
- -- WHEN MAX(OSN_TIMESTAMP) > (P_TIMESTAMP + P_MAX_TIMESTAMP_SKEW) THEN 1 ELSE 0
- -- END "IS_MAX" INTO V_MAX_TIMESTAMP, V_IS_MAX
- -- FROM OAUTH_SERVER_NONCE
- -- WHERE OSN_CONSUMER_KEY = P_CONSUMER_KEY
- -- AND OSN_TOKEN = P_TOKEN;
- --
- -- IF V_IS_MAX = 1 THEN
- -- RAISE V_EXC_INVALID_TIMESTAMP;
- -- END IF;
- --
- -- EXCEPTION
- -- WHEN NO_DATA_FOUND THEN
- -- NULL;
- -- END;
-
- BEGIN
- SELECT 1 INTO V_IS_DUPLICATE_TIMESTAMP FROM DUAL WHERE EXISTS
- (SELECT OSN_ID FROM OAUTH_SERVER_NONCE
- WHERE OSN_CONSUMER_KEY = P_CONSUMER_KEY
- AND OSN_TOKEN = P_TOKEN
- AND OSN_TIMESTAMP = P_TIMESTAMP
- AND OSN_NONCE = P_NONCE);
-
- IF V_IS_DUPLICATE_TIMESTAMP = 1 THEN
- RAISE V_EXC_DUPLICATE_TIMESTAMP;
- END IF;
- EXCEPTION
- WHEN NO_DATA_FOUND THEN
- NULL;
- END;
-
- -- Insert the new combination
- INSERT INTO OAUTH_SERVER_NONCE
- (OSN_ID, OSN_CONSUMER_KEY, OSN_TOKEN, OSN_TIMESTAMP, OSN_NONCE)
- VALUES
- (SEQ_OSN_ID.NEXTVAL, P_CONSUMER_KEY, P_TOKEN, P_TIMESTAMP, P_NONCE);
-
- -- Clean up all timestamps older than the one we just received
- DELETE FROM OAUTH_SERVER_NONCE
- WHERE OSN_CONSUMER_KEY = P_CONSUMER_KEY
- AND OSN_TOKEN = P_TOKEN
- AND OSN_TIMESTAMP < (P_TIMESTAMP - P_MAX_TIMESTAMP_SKEW);
-
-
-EXCEPTION
-WHEN V_EXC_INVALID_TIMESTAMP THEN
-P_RESULT := 2; -- INVALID_TIMESTAMP
-WHEN V_EXC_DUPLICATE_TIMESTAMP THEN
-P_RESULT := 3; -- DUPLICATE_TIMESTAMP
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc
deleted file mode 100644
index 047c77b..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc
+++ /dev/null
@@ -1,28 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_CONSUMER_STATIC_SAVE
-(
-P_OSR_CONSUMER_KEY IN VARCHAR2,
-P_RESULT OUT NUMBER
-)
-AS
-
--- PROCEDURE TO Fetch the static consumer key for this provider.
-BEGIN
-P_RESULT := 0;
-
-
- INSERT INTO OAUTH_SERVER_REGISTRY
- (OSR_ID, OSR_ENABLED, OSR_STATUS, OSR_USA_ID_REF, OSR_CONSUMER_KEY, OSR_CONSUMER_SECRET, OSR_REQUESTER_NAME, OSR_REQUESTER_EMAIL, OSR_CALLBACK_URI,
- OSR_APPLICATION_URI, OSR_APPLICATION_TITLE, OSR_APPLICATION_DESCR, OSR_APPLICATION_NOTES,
- OSR_APPLICATION_TYPE, OSR_APPLICATION_COMMERCIAL, OSR_TIMESTAMP,OSR_ISSUE_DATE)
- VALUES
- (SEQ_OSR_ID.NEXTVAL, 1, 'ACTIVE', NULL, P_OSR_CONSUMER_KEY, '\', '\', '\', '\', '\',
- 'STATIC SHARED CONSUMER KEY', '\', 'STATIC SHARED CONSUMER KEY', '\', 0, SYSDATE, SYSDATE);
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc
deleted file mode 100644
index f7099b9..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc
+++ /dev/null
@@ -1,27 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_COUNT_CONSUMER_ACCESS_TOKEN
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_COUNT OUT NUMBER,
-P_RESULT OUT NUMBER
-)
-AS
--- PROCEDURE TO Count the consumer access tokens for the given consumer.
-BEGIN
-P_RESULT := 0;
-
-SELECT COUNT(OST_ID) INTO P_COUNT
- FROM OAUTH_SERVER_TOKEN
- JOIN OAUTH_SERVER_REGISTRY
- ON OST_OSR_ID_REF = OSR_ID
- WHERE OST_TOKEN_TYPE = 'ACCESS'
- AND OSR_CONSUMER_KEY = P_CONSUMER_KEY
- AND OST_TOKEN_TTL >= SYSDATE;
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc
deleted file mode 100644
index c73b366..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc
+++ /dev/null
@@ -1,28 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_COUNT_SERVICE_TOKENS
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_COUNT OUT NUMBER,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Count how many tokens we have for the given server
-BEGIN
-P_RESULT := 0;
-
- SELECT COUNT(OCT_ID) INTO P_COUNT
- FROM OAUTH_CONSUMER_TOKEN
- JOIN OAUTH_CONSUMER_REGISTRY
- ON OCT_OCR_ID_REF = OCR_ID
- WHERE OCT_TOKEN_TYPE = 'ACCESS'
- AND OCR_CONSUMER_KEY = P_CONSUMER_KEY
- AND OCT_TOKEN_TTL >= SYSDATE;
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc
deleted file mode 100644
index 3f18562..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc
+++ /dev/null
@@ -1,35 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_DELETE_CONSUMER
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_USER_ID IN NUMBER,
-P_USER_IS_ADMIN IN NUMBER, --0:NO; 1:YES
-P_RESULT OUT NUMBER
-)
-AS
-
- -- Delete a consumer key. This removes access to our site for all applications using this key.
-
-BEGIN
-P_RESULT := 0;
-
-IF P_USER_IS_ADMIN = 1 THEN
-
- DELETE FROM OAUTH_SERVER_REGISTRY
- WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY
- AND (OSR_USA_ID_REF = P_USER_ID OR OSR_USA_ID_REF IS NULL);
-
-ELSIF P_USER_IS_ADMIN = 0 THEN
-
- DELETE FROM OAUTH_SERVER_REGISTRY
- WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY
- AND OSR_USA_ID_REF = P_USER_ID;
-
-END IF;
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc
deleted file mode 100644
index ba259de..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc
+++ /dev/null
@@ -1,35 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_DELETE_SERVER
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_USER_ID IN NUMBER,
-P_USER_IS_ADMIN IN NUMBER, --0:NO; 1:YES
-P_RESULT OUT NUMBER
-)
-AS
-
- -- Delete a server key. This removes access to that site.
-
-BEGIN
-P_RESULT := 0;
-
-IF P_USER_IS_ADMIN = 1 THEN
-
- DELETE FROM OAUTH_CONSUMER_REGISTRY
- WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY
- AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL);
-
-ELSIF P_USER_IS_ADMIN = 0 THEN
-
- DELETE FROM OAUTH_CONSUMER_REGISTRY
- WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY
- AND OCR_USA_ID_REF = P_USER_ID;
-
-END IF;
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc
deleted file mode 100644
index de9d450..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc
+++ /dev/null
@@ -1,37 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_DELETE_SERVER_TOKEN
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_USER_ID IN NUMBER,
-P_TOKEN IN VARCHAR2,
-P_USER_IS_ADMIN IN NUMBER, --0:NO; 1:YES
-P_RESULT OUT NUMBER
-)
-AS
-
- -- Delete a token we obtained from a server.
-
-BEGIN
-P_RESULT := 0;
-
-IF P_USER_IS_ADMIN = 1 THEN
-
- DELETE FROM OAUTH_CONSUMER_TOKEN
- WHERE OCT_TOKEN = P_TOKEN
- AND OCT_OCR_ID_REF IN (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY);
-
-ELSIF P_USER_IS_ADMIN = 0 THEN
-
- DELETE FROM OAUTH_CONSUMER_TOKEN
- WHERE OCT_TOKEN = P_TOKEN
- AND OCT_USA_ID_REF = P_USER_ID
- AND OCT_OCR_ID_REF IN (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY);
-
-END IF;
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc
deleted file mode 100644
index 4281bdb..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc
+++ /dev/null
@@ -1,33 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_DEL_CONSUMER_ACCESS_TOKEN
-(
-P_USER_ID IN NUMBER,
-P_TOKEN IN VARCHAR2,
-P_USER_IS_ADMIN IN NUMBER, -- 1:YES; 0:NO
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Delete a consumer access token.
-
-BEGIN
-
- P_RESULT := 0;
-
- IF P_USER_IS_ADMIN = 1 THEN
- DELETE FROM OAUTH_SERVER_TOKEN
- WHERE OST_TOKEN = P_TOKEN
- AND OST_TOKEN_TYPE = 'ACCESS';
- ELSE
- DELETE FROM OAUTH_SERVER_TOKEN
- WHERE OST_TOKEN = P_TOKEN
- AND OST_TOKEN_TYPE = 'ACCESS'
- AND OST_USA_ID_REF = P_USER_ID;
- END IF;
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc
deleted file mode 100644
index 01678d6..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc
+++ /dev/null
@@ -1,25 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_DEL_CONSUMER_REQUEST_TOKEN
-(
-P_TOKEN IN VARCHAR2,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Delete a consumer token. The token must be a request or authorized token.
-
-BEGIN
-
- P_RESULT := 0;
-
- DELETE FROM OAUTH_SERVER_TOKEN
- WHERE OST_TOKEN = P_TOKEN
- AND OST_TOKEN_TYPE = 'REQUEST';
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc
deleted file mode 100644
index 66a53ed..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc
+++ /dev/null
@@ -1,96 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_EXCH_CONS_REQ_FOR_ACC_TOKEN
-(
-P_TOKEN_TTL IN NUMBER, -- IN SECOND
-P_NEW_TOKEN IN VARCHAR2,
-P_TOKEN IN VARCHAR2,
-P_TOKEN_SECRET IN VARCHAR2,
-P_VERIFIER IN VARCHAR2,
-P_OUT_TOKEN_TTL OUT NUMBER,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Add an unautorized request token to our server.
-
-V_TOKEN_EXIST NUMBER;
-
-
-V_EXC_NO_TOKEN_EXIST EXCEPTION;
-BEGIN
-
- P_RESULT := 0;
-
- IF P_VERIFIER IS NOT NULL THEN
-
- BEGIN
- SELECT 1 INTO V_TOKEN_EXIST FROM DUAL WHERE EXISTS
- (SELECT OST_TOKEN FROM OAUTH_SERVER_TOKEN
- WHERE OST_TOKEN = P_TOKEN
- AND OST_TOKEN_TYPE = 'REQUEST'
- AND OST_AUTHORIZED = 1
- AND OST_TOKEN_TTL >= SYSDATE
- AND OST_VERIFIER = P_VERIFIER);
- EXCEPTION
- WHEN NO_DATA_FOUND THEN
- RAISE V_EXC_NO_TOKEN_EXIST;
- END;
-
- UPDATE OAUTH_SERVER_TOKEN
- SET OST_TOKEN = P_NEW_TOKEN,
- OST_TOKEN_SECRET = P_TOKEN_SECRET,
- OST_TOKEN_TYPE = 'ACCESS',
- OST_TIMESTAMP = SYSDATE,
- OST_TOKEN_TTL = NVL(SYSDATE + (P_TOKEN_TTL/(24*60*60)), TO_DATE('9999.12.31', 'yyyy.mm.dd'))
- WHERE OST_TOKEN = P_TOKEN
- AND OST_TOKEN_TYPE = 'REQUEST'
- AND OST_AUTHORIZED = 1
- AND OST_TOKEN_TTL >= SYSDATE
- AND OST_VERIFIER = P_VERIFIER;
-
- ELSE
- BEGIN
- SELECT 1 INTO V_TOKEN_EXIST FROM DUAL WHERE EXISTS
- (SELECT OST_TOKEN FROM OAUTH_SERVER_TOKEN
- WHERE OST_TOKEN = P_TOKEN
- AND OST_TOKEN_TYPE = 'REQUEST'
- AND OST_AUTHORIZED = 1
- AND OST_TOKEN_TTL >= SYSDATE);
- EXCEPTION
- WHEN NO_DATA_FOUND THEN
- RAISE V_EXC_NO_TOKEN_EXIST;
- END;
-
- UPDATE OAUTH_SERVER_TOKEN
- SET OST_TOKEN = P_NEW_TOKEN,
- OST_TOKEN_SECRET = P_TOKEN_SECRET,
- OST_TOKEN_TYPE = 'ACCESS',
- OST_TIMESTAMP = SYSDATE,
- OST_TOKEN_TTL = NVL(SYSDATE + (P_TOKEN_TTL/(24*60*60)), TO_DATE('9999.12.31', 'yyyy.mm.dd'))
- WHERE OST_TOKEN = P_TOKEN
- AND OST_TOKEN_TYPE = 'REQUEST'
- AND OST_AUTHORIZED = 1
- AND OST_TOKEN_TTL >= SYSDATE;
-
-
- END IF;
-
- SELECT CASE
- WHEN OST_TOKEN_TTL >= TO_DATE('9999.12.31', 'yyyy.mm.dd') THEN NULL ELSE (OST_TOKEN_TTL - SYSDATE)*24*60*60
- END "TOKEN_TTL" INTO P_OUT_TOKEN_TTL
- FROM OAUTH_SERVER_TOKEN
- WHERE OST_TOKEN = P_NEW_TOKEN;
-
-
-
-
-
-
-EXCEPTION
-WHEN V_EXC_NO_TOKEN_EXIST THEN
-P_RESULT := 2; -- NO_TOKEN_EXIST
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc
deleted file mode 100644
index 4225ff2..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc
+++ /dev/null
@@ -1,41 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER
-(
-P_CONSUMER_KEY IN STRING,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Fetch a consumer of this server, by consumer_key.
-BEGIN
-P_RESULT := 0;
-
-OPEN P_ROWS FOR
- SELECT OSR_ID "osr_id",
- OSR_USA_ID_REF "osr_usa_id_ref",
- OSR_CONSUMER_KEY "osr_consumer_key",
- OSR_CONSUMER_SECRET "osr_consumer_secret",
- OSR_ENABLED "osr_enabled",
- OSR_STATUS "osr_status",
- OSR_REQUESTER_NAME "osr_requester_name",
- OSR_REQUESTER_EMAIL "osr_requester_email",
- OSR_CALLBACK_URI "osr_callback_uri",
- OSR_APPLICATION_URI "osr_application_uri",
- OSR_APPLICATION_TITLE "osr_application_title",
- OSR_APPLICATION_DESCR "osr_application_descr",
- OSR_APPLICATION_NOTES "osr_application_notes",
- OSR_APPLICATION_TYPE "osr_application_type",
- OSR_APPLICATION_COMMERCIAL "osr_application_commercial",
- OSR_ISSUE_DATE "osr_issue_date",
- OSR_TIMESTAMP "osr_timestamp"
- FROM OAUTH_SERVER_REGISTRY
- WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY;
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc
deleted file mode 100644
index 0db2ea9..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc
+++ /dev/null
@@ -1,43 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER_ACCESS_TOKEN
-(
-P_USER_ID IN NUMBER,
-P_TOKEN IN VARCHAR2,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Fetch the consumer access token, by access token.
-
-BEGIN
-
- P_RESULT := 0;
-
-
- OPEN P_ROWS FOR
- SELECT OST_TOKEN "token",
- OST_TOKEN_SECRET "token_secret",
- OST_REFERRER_HOST "token_referrer_host",
- OSR_CONSUMER_KEY "consumer_key",
- OSR_CONSUMER_SECRET "consumer_secret",
- OSR_APPLICATION_URI "application_uri",
- OSR_APPLICATION_TITLE "application_title",
- OSR_APPLICATION_DESCR "application_descr",
- OSR_CALLBACK_URI "callback_uri"
- FROM OAUTH_SERVER_TOKEN
- JOIN OAUTH_SERVER_REGISTRY
- ON OST_OSR_ID_REF = OSR_ID
- WHERE OST_TOKEN_TYPE = 'ACCESS'
- AND OST_TOKEN = P_TOKEN
- AND OST_USA_ID_REF = P_USER_ID
- AND OST_TOKEN_TTL >= SYSDATE;
-
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc
deleted file mode 100644
index 6d3b590..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc
+++ /dev/null
@@ -1,41 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER_REQUEST_TOKEN
-(
-P_TOKEN IN VARCHAR2,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Fetch the consumer request token, by request token.
-BEGIN
-P_RESULT := 0;
-
-OPEN P_ROWS FOR
-
-SELECT OST_TOKEN "token",
- OST_TOKEN_SECRET "token_secret",
- OSR_CONSUMER_KEY "consumer_key",
- OSR_CONSUMER_SECRET "consumer_secret",
- OST_TOKEN_TYPE "token_type",
- OST_CALLBACK_URL "callback_url",
- OSR_APPLICATION_TITLE "application_title",
- OSR_APPLICATION_DESCR "application_descr",
- OSR_APPLICATION_URI "application_uri"
- FROM OAUTH_SERVER_TOKEN
- JOIN OAUTH_SERVER_REGISTRY
- ON OST_OSR_ID_REF = OSR_ID
- WHERE OST_TOKEN_TYPE = 'REQUEST'
- AND OST_TOKEN = P_TOKEN
- AND OST_TOKEN_TTL >= SYSDATE;
-
-
-
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc
deleted file mode 100644
index 1126ef6..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc
+++ /dev/null
@@ -1,25 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER_STATIC_SELECT
-(
-P_OSR_CONSUMER_KEY OUT VARCHAR2,
-P_RESULT OUT NUMBER
-)
-AS
-
--- PROCEDURE TO Fetch the static consumer key for this provider.
-BEGIN
-P_RESULT := 0;
-
-
- SELECT OSR_CONSUMER_KEY INTO P_OSR_CONSUMER_KEY
- FROM OAUTH_SERVER_REGISTRY
- WHERE OSR_CONSUMER_KEY LIKE 'sc-%%'
- AND OSR_USA_ID_REF IS NULL;
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc
deleted file mode 100644
index 2af7847..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc
+++ /dev/null
@@ -1,43 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_GET_SECRETS_FOR_SIGNATURE
-(
-P_HOST IN VARCHAR2,
-P_PATH IN VARCHAR2,
-P_USER_ID IN NUMBER,
-P_NAME IN VARCHAR2,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Find the server details for signing a request, always looks for an access token.
- -- The returned credentials depend on which local user is making the request.
-BEGIN
-P_RESULT := 0;
-
- OPEN P_ROWS FOR
- SELECT * FROM (
- SELECT OCR_CONSUMER_KEY "consumer_key",
- OCR_CONSUMER_SECRET "consumer_secret",
- OCT_TOKEN "token",
- OCT_TOKEN_SECRET "token_secret",
- OCR_SIGNATURE_METHODS "signature_methods"
- FROM OAUTH_CONSUMER_REGISTRY
- JOIN OAUTH_CONSUMER_TOKEN ON OCT_OCR_ID_REF = OCR_ID
- WHERE OCR_SERVER_URI_HOST = P_HOST
- AND OCR_SERVER_URI_PATH = SUBSTR(P_PATH, 1, LENGTH(OCR_SERVER_URI_PATH))
- AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL)
- AND OCT_USA_ID_REF = P_USER_ID
- AND OCT_TOKEN_TYPE = 'ACCESS'
- AND OCT_NAME = P_NAME
- AND OCT_TOKEN_TTL >= SYSDATE
- ORDER BY OCR_USA_ID_REF DESC, OCR_CONSUMER_SECRET DESC, LENGTH(OCR_SERVER_URI_PATH) DESC
- ) WHERE ROWNUM<=1;
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc
deleted file mode 100644
index 4fbb435..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc
+++ /dev/null
@@ -1,52 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_GET_SECRETS_FOR_VERIFY
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_TOKEN IN VARCHAR2,
-P_TOKEN_TYPE IN VARCHAR2,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE to Find stored credentials for the consumer key and token. Used by an OAuth server
- -- when verifying an OAuth request.
-
-BEGIN
-P_RESULT := 0;
-
-IF P_TOKEN_TYPE IS NULL THEN
- OPEN P_ROWS FOR
- SELECT OSR.OSR_ID "osr_id",
- OSR.OSR_CONSUMER_KEY "consumer_key",
- OSR.OSR_CONSUMER_SECRET "consumer_secret"
- FROM OAUTH_SERVER_REGISTRY OSR
- WHERE OSR.OSR_CONSUMER_KEY = P_CONSUMER_KEY
- AND OSR.OSR_ENABLED = 1;
-ELSE
- OPEN P_ROWS FOR
- SELECT OSR.OSR_ID "osr_id",
- OST.OST_ID "ost_id",
- OST.OST_USA_ID_REF "user_id",
- OSR.OSR_CONSUMER_KEY "consumer_key",
- OSR.OSR_CONSUMER_SECRET "consumer_secret",
- OST.OST_TOKEN "token",
- OST.OST_TOKEN_SECRET "token_secret"
- FROM OAUTH_SERVER_REGISTRY OSR, OAUTH_SERVER_TOKEN OST
- WHERE OST.OST_OSR_ID_REF = OSR.OSR_ID
- AND upper(OST.OST_TOKEN_TYPE) = upper(P_TOKEN_TYPE)
- AND OSR.OSR_CONSUMER_KEY = P_CONSUMER_KEY
- AND OST.OST_TOKEN = P_TOKEN
- AND OSR.OSR_ENABLED = 1
- AND OST.OST_TOKEN_TTL >= SYSDATE;
-
-END IF;
-
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc
deleted file mode 100644
index af7d275..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc
+++ /dev/null
@@ -1,35 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_GET_SERVER
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_USER_ID IN NUMBER,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Get a server from the consumer registry using the consumer key
-BEGIN
-P_RESULT := 0;
-
-OPEN P_ROWS FOR
- SELECT OCR_ID "id",
- OCR_USA_ID_REF "user_id",
- OCR_CONSUMER_KEY "consumer_key",
- OCR_CONSUMER_SECRET "consumer_secret",
- OCR_SIGNATURE_METHODS "signature_methods",
- OCR_SERVER_URI "server_uri",
- OCR_REQUEST_TOKEN_URI "request_token_uri",
- OCR_AUTHORIZE_URI "authorize_uri",
- OCR_ACCESS_TOKEN_URI "access_token_uri"
- FROM OAUTH_CONSUMER_REGISTRY
- WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY
- AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL);
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc
deleted file mode 100644
index d838b51..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc
+++ /dev/null
@@ -1,41 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_GET_SERVER_FOR_URI
-(
-P_HOST IN VARCHAR2,
-P_PATH IN VARCHAR2,
-P_USER_ID IN NUMBER,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Find the server details that might be used for a request
-BEGIN
-P_RESULT := 0;
-
-OPEN P_ROWS FOR
-SELECT * FROM (
- SELECT OCR_ID "id",
- OCR_USA_ID_REF "user_id",
- OCR_CONSUMER_KEY "consumer_key",
- OCR_CONSUMER_SECRET "consumer_secret",
- OCR_SIGNATURE_METHODS "signature_methods",
- OCR_SERVER_URI "server_uri",
- OCR_REQUEST_TOKEN_URI "request_token_uri",
- OCR_AUTHORIZE_URI "authorize_uri",
- OCR_ACCESS_TOKEN_URI "access_token_uri"
- FROM OAUTH_CONSUMER_REGISTRY
- WHERE OCR_SERVER_URI_HOST = P_HOST
- AND OCR_SERVER_URI_PATH = SUBSTR(P_PATH, 1, LENGTH(OCR_SERVER_URI_PATH))
- AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL)
- ORDER BY ocr_usa_id_ref DESC, OCR_CONSUMER_KEY DESC, LENGTH(ocr_server_uri_path) DESC
-) WHERE ROWNUM<=1;
-
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc
deleted file mode 100644
index fefbe8a..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc
+++ /dev/null
@@ -1,45 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_GET_SERVER_TOKEN
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_USER_ID IN NUMBER,
-P_TOKEN IN VARCHAR2,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Get a specific server token for the given user
-BEGIN
-P_RESULT := 0;
-
-OPEN P_ROWS FOR
- SELECT OCR_CONSUMER_KEY "consumer_key",
- OCR_CONSUMER_SECRET "consumer_secret",
- OCT_TOKEN "token",
- OCT_TOKEN_SECRET "token_secret",
- OCT_USA_ID_REF "usr_id",
- OCR_SIGNATURE_METHODS "signature_methods",
- OCR_SERVER_URI "server_uri",
- OCR_SERVER_URI_HOST "server_uri_host",
- OCR_SERVER_URI_PATH "server_uri_path",
- OCR_REQUEST_TOKEN_URI "request_token_uri",
- OCR_AUTHORIZE_URI "authorize_uri",
- OCR_ACCESS_TOKEN_URI "access_token_uri",
- OCT_TIMESTAMP "timestamp"
- FROM OAUTH_CONSUMER_REGISTRY
- JOIN OAUTH_CONSUMER_TOKEN
- ON OCT_OCR_ID_REF = OCR_ID
- WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY
- AND OCT_USA_ID_REF = P_USER_ID
- AND OCT_TOKEN_TYPE = 'ACCESS'
- AND OCT_TOKEN = P_TOKEN
- AND OCT_TOKEN_TTL >= SYSDATE;
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc
deleted file mode 100644
index 95eec88..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc
+++ /dev/null
@@ -1,47 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_GET_SERVER_TOKEN_SECRETS
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_TOKEN IN VARCHAR2,
-P_TOKEN_TYPE IN VARCHAR2,
-P_USER_ID IN NUMBER,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- Get the token and token secret we obtained from a server.
-
-BEGIN
-P_RESULT := 0;
-
-
- OPEN P_ROWS FOR
- SELECT OCR.OCR_CONSUMER_KEY "consumer_key",
- OCR.OCR_CONSUMER_SECRET "consumer_secret",
- OCT.OCT_TOKEN "token",
- OCT.OCT_TOKEN_SECRET "token_secret",
- OCT.OCT_NAME "token_name",
- OCR.OCR_SIGNATURE_METHODS "signature_methods",
- OCR.OCR_SERVER_URI "server_uri",
- OCR.OCR_REQUEST_TOKEN_URI "request_token_uri",
- OCR.OCR_AUTHORIZE_URI "authorize_uri",
- OCR.OCR_ACCESS_TOKEN_URI "access_token_uri",
- CASE WHEN OCT.OCT_TOKEN_TTL >= TO_DATE('9999.12.31', 'yyyy.mm.dd') THEN NULL
- ELSE OCT.OCT_TOKEN_TTL - SYSDATE
- END "token_ttl"
- FROM OAUTH_CONSUMER_REGISTRY OCR, OAUTH_CONSUMER_TOKEN OCT
- WHERE OCT.OCT_OCR_ID_REF = OCR_ID
- AND OCR.OCR_CONSUMER_KEY = P_CONSUMER_KEY
- AND upper(OCT.OCT_TOKEN_TYPE) = upper(P_TOKEN_TYPE)
- AND OCT.OCT_TOKEN = P_TOKEN
- AND OCT.OCT_USA_ID_REF = P_USER_ID
- AND OCT.OCT_TOKEN_TTL >= SYSDATE;
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc
deleted file mode 100644
index bb42465..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc
+++ /dev/null
@@ -1,41 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_LIST_CONSUMERS
-(
-P_USER_ID IN NUMBER,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Fetch a list of all consumer keys, secrets etc.
- -- Returns the public (user_id is null) and the keys owned by the user
-
-BEGIN
-
- P_RESULT := 0;
-
- OPEN P_ROWS FOR
- SELECT OSR_ID "id",
- OSR_USA_ID_REF "user_id",
- OSR_CONSUMER_KEY "consumer_key",
- OSR_CONSUMER_SECRET "consumer_secret",
- OSR_ENABLED "enabled",
- OSR_STATUS "status",
- OSR_ISSUE_DATE "issue_date",
- OSR_APPLICATION_URI "application_uri",
- OSR_APPLICATION_TITLE "application_title",
- OSR_APPLICATION_DESCR "application_descr",
- OSR_REQUESTER_NAME "requester_name",
- OSR_REQUESTER_EMAIL "requester_email",
- OSR_CALLBACK_URI "callback_uri"
- FROM OAUTH_SERVER_REGISTRY
- WHERE (OSR_USA_ID_REF = P_USER_ID OR OSR_USA_ID_REF IS NULL)
- ORDER BY OSR_APPLICATION_TITLE;
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc
deleted file mode 100644
index dae9c72..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc
+++ /dev/null
@@ -1,43 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_LIST_CONSUMER_TOKENS
-(
-P_USER_ID IN NUMBER,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Fetch a list of all consumer tokens accessing the account of the given user.
-
-BEGIN
-
- P_RESULT := 0;
-
- OPEN P_ROWS FOR
- SELECT OSR_CONSUMER_KEY "consumer_key",
- OSR_CONSUMER_SECRET "consumer_secret",
- OSR_ENABLED "enabled",
- OSR_STATUS "status",
- OSR_APPLICATION_URI "application_uri",
- OSR_APPLICATION_TITLE "application_title",
- OSR_APPLICATION_DESCR "application_descr",
- OST_TIMESTAMP "timestamp",
- OST_TOKEN "token",
- OST_TOKEN_SECRET "token_secret",
- OST_REFERRER_HOST "token_referrer_host",
- OSR_CALLBACK_URI "callback_uri"
- FROM OAUTH_SERVER_REGISTRY
- JOIN OAUTH_SERVER_TOKEN
- ON OST_OSR_ID_REF = OSR_ID
- WHERE OST_USA_ID_REF = P_USER_ID
- AND OST_TOKEN_TYPE = 'ACCESS'
- AND OST_TOKEN_TTL >= SYSDATE
- ORDER BY OSR_APPLICATION_TITLE;
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc
deleted file mode 100644
index 275950e..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc
+++ /dev/null
@@ -1,75 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_LIST_LOG
-(
-P_OPTION_FLAG IN NUMBER, -- 0:NULL; 1:OTHERWISE
-P_USA_ID IN NUMBER,
-P_OSR_CONSUMER_KEY IN VARCHAR2,
-P_OCR_CONSUMER_KEY IN VARCHAR2,
-P_OST_TOKEN IN VARCHAR2,
-P_OCT_TOKEN IN VARCHAR2,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Get a page of entries from the log. Returns the last 100 records
- -- matching the options given.
-
-BEGIN
-
- P_RESULT := 0;
-
- IF P_OPTION_FLAG IS NULL OR P_OPTION_FLAG = 0 THEN
- OPEN P_ROWS FOR
- SELECT * FROM (
- SELECT OLG_ID "olg_id",
- OLG_OSR_CONSUMER_KEY "osr_consumer_key",
- OLG_OST_TOKEN "ost_token",
- OLG_OCR_CONSUMER_KEY "ocr_consumer_key",
- OLG_OCT_TOKEN "oct_token",
- OLG_USA_ID_REF "user_id",
- OLG_RECEIVED "received",
- OLG_SENT "sent",
- OLG_BASE_STRING "base_string",
- OLG_NOTES "notes",
- OLG_TIMESTAMP "timestamp",
- -- INET_NTOA(OLG_REMOTE_IP) "remote_ip"
- OLG_REMOTE_IP "remote_ip"
- FROM OAUTH_LOG
- WHERE OLG_USA_ID_REF = P_USA_ID
- ORDER BY OLG_ID DESC
- ) WHERE ROWNUM<=100;
- ELSE
- OPEN P_ROWS FOR
- SELECT * FROM (
- SELECT OLG_ID "olg_id",
- OLG_OSR_CONSUMER_KEY "osr_consumer_key",
- OLG_OST_TOKEN "ost_token",
- OLG_OCR_CONSUMER_KEY "ocr_consumer_key",
- OLG_OCT_TOKEN "oct_token",
- OLG_USA_ID_REF "user_id",
- OLG_RECEIVED "received",
- OLG_SENT "sent",
- OLG_BASE_STRING "base_string",
- OLG_NOTES "notes",
- OLG_TIMESTAMP "timestamp",
- -- INET_NTOA(OLG_REMOTE_IP) "remote_ip"
- OLG_REMOTE_IP "remote_ip"
- FROM OAUTH_LOG
- WHERE OLG_OSR_CONSUMER_KEY = P_OSR_CONSUMER_KEY
- AND OLG_OCR_CONSUMER_KEY = P_OCR_CONSUMER_KEY
- AND OLG_OST_TOKEN = P_OST_TOKEN
- AND OLG_OCT_TOKEN = P_OCT_TOKEN
- AND (OLG_USA_ID_REF IS NULL OR OLG_USA_ID_REF = P_USA_ID)
- ORDER BY OLG_ID DESC
- ) WHERE ROWNUM<=100;
-
- END IF;
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc
deleted file mode 100644
index 51dd39a..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc
+++ /dev/null
@@ -1,66 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_LIST_SERVERS
-(
-P_Q IN VARCHAR2,
-P_USER_ID IN NUMBER,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Get a list of all consumers from the consumer registry.
-BEGIN
-P_RESULT := 0;
-
-IF P_Q IS NOT NULL THEN
-
- OPEN P_ROWS FOR
- SELECT OCR_ID "id",
- OCR_USA_ID_REF "user_id",
- OCR_CONSUMER_KEY "consumer_key",
- OCR_CONSUMER_SECRET "consumer_secret",
- OCR_SIGNATURE_METHODS "signature_methods",
- OCR_SERVER_URI "server_uri",
- OCR_SERVER_URI_HOST "server_uri_host",
- OCR_SERVER_URI_PATH "server_uri_path",
- OCR_REQUEST_TOKEN_URI "request_token_uri",
- OCR_AUTHORIZE_URI "authorize_uri",
- OCR_ACCESS_TOKEN_URI "access_token_uri"
- FROM OAUTH_CONSUMER_REGISTRY
- WHERE ( OCR_CONSUMER_KEY LIKE '%'|| P_Q ||'%'
- OR OCR_SERVER_URI LIKE '%'|| P_Q ||'%'
- OR OCR_SERVER_URI_HOST LIKE '%'|| P_Q ||'%'
- OR OCR_SERVER_URI_PATH LIKE '%'|| P_Q ||'%')
- AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL)
- ORDER BY OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH;
-
-ELSE
-
- OPEN P_ROWS FOR
- SELECT OCR_ID "id",
- OCR_USA_ID_REF "user_id",
- OCR_CONSUMER_KEY "consumer_key",
- OCR_CONSUMER_SECRET "consumer_secret",
- OCR_SIGNATURE_METHODS "signature_methods",
- OCR_SERVER_URI "server_uri",
- OCR_SERVER_URI_HOST "server_uri_host",
- OCR_SERVER_URI_PATH "server_uri_path",
- OCR_REQUEST_TOKEN_URI "request_token_uri",
- OCR_AUTHORIZE_URI "authorize_uri",
- OCR_ACCESS_TOKEN_URI "access_token_uri"
- FROM OAUTH_CONSUMER_REGISTRY
- WHERE OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL
- ORDER BY OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH;
-
-END IF;
-
-
-
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc
deleted file mode 100644
index baa62c0..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc
+++ /dev/null
@@ -1,45 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_LIST_SERVER_TOKENS
-(
-P_USER_ID IN NUMBER,
-P_ROWS OUT TYPES.REF_CURSOR,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Find the server details that might be used for a request
-BEGIN
-P_RESULT := 0;
-
-OPEN P_ROWS FOR
- SELECT OCR_CONSUMER_KEY "consumer_key",
- OCR_CONSUMER_SECRET "consumer_secret",
- OCT_ID "token_id",
- OCT_TOKEN "token",
- OCT_TOKEN_SECRET "token_secret",
- OCT_USA_ID_REF "user_id",
- OCR_SIGNATURE_METHODS "signature_methods",
- OCR_SERVER_URI "server_uri",
- OCR_SERVER_URI_HOST "server_uri_host",
- OCR_SERVER_URI_PATH "server_uri_path",
- OCR_REQUEST_TOKEN_URI "request_token_uri",
- OCR_AUTHORIZE_URI "authorize_uri",
- OCR_ACCESS_TOKEN_URI "access_token_uri",
- OCT_TIMESTAMP "timestamp"
- FROM OAUTH_CONSUMER_REGISTRY
- JOIN OAUTH_CONSUMER_TOKEN
- ON OCT_OCR_ID_REF = OCR_ID
- WHERE OCT_USA_ID_REF = P_USER_ID
- AND OCT_TOKEN_TYPE = 'ACCESS'
- AND OCT_TOKEN_TTL >= SYSDATE
- ORDER BY OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH;
-
-
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc
deleted file mode 100644
index e5a96c9..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc
+++ /dev/null
@@ -1,28 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_SET_CONSUMER_ACC_TOKEN_TTL
-(
-P_TOKEN IN VARCHAR2,
-P_TOKEN_TTL IN NUMBER,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Set the ttl of a consumer access token. This is done when the
- -- server receives a valid request with a xoauth_token_ttl parameter in it.
-
-BEGIN
-
- P_RESULT := 0;
-
- UPDATE OAUTH_SERVER_TOKEN
- SET OST_TOKEN_TTL = SYSDATE + (P_TOKEN_TTL/(24*60*60))
- WHERE OST_TOKEN = P_TOKEN
- AND OST_TOKEN_TYPE = 'ACCESS';
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc
deleted file mode 100644
index 34a99de..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc
+++ /dev/null
@@ -1,29 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_SET_SERVER_TOKEN_TTL
-(
-P_TOKEN_TTL IN NUMBER, -- IN SECOND
-P_CONSUMER_KEY IN VARCHAR2,
-P_TOKEN IN VARCHAR2,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Set the ttl of a server access token.
-
-BEGIN
-
- P_RESULT := 0;
-
-
-UPDATE OAUTH_CONSUMER_TOKEN
-SET OCT_TOKEN_TTL = SYSDATE + (P_TOKEN_TTL/(24*60*60)) -- DATE_ADD(NOW(), INTERVAL %D SECOND)
-WHERE OCT_TOKEN = P_TOKEN
-AND OCT_OCR_ID_REF IN (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY);
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc
deleted file mode 100644
index a79e64c..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc
+++ /dev/null
@@ -1,40 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_UPDATE_CONSUMER
-(
-P_OSR_USA_ID_REF IN NUMBER,
-P_OSR_CONSUMER_KEY IN VARCHAR2,
-P_OSR_CONSUMER_SECRET IN VARCHAR2,
-P_OSR_REQUESTER_NAME IN VARCHAR2,
-P_OSR_REQUESTER_EMAIL IN VARCHAR2,
-P_OSR_CALLBACK_URI IN VARCHAR2,
-P_OSR_APPLICATION_URI IN VARCHAR2,
-P_OSR_APPLICATION_TITLE IN VARCHAR2,
-P_OSR_APPLICATION_DESCR IN VARCHAR2,
-P_OSR_APPLICATION_NOTES IN VARCHAR2,
-P_OSR_APPLICATION_TYPE IN VARCHAR2,
-P_OSR_APPLICATION_COMMERCIAL IN INTEGER,
-P_RESULT OUT NUMBER
-)
-AS
-
- -- PROCEDURE TO Insert a new consumer with this server (we will be the server)
-BEGIN
-P_RESULT := 0;
-
-
- INSERT INTO OAUTH_SERVER_REGISTRY
- ( OSR_ID, OSR_ENABLED, OSR_STATUS,OSR_USA_ID_REF,OSR_CONSUMER_KEY, OSR_CONSUMER_SECRET,OSR_REQUESTER_NAME,
- OSR_REQUESTER_EMAIL, OSR_CALLBACK_URI, OSR_APPLICATION_URI, OSR_APPLICATION_TITLE, OSR_APPLICATION_DESCR,
- OSR_APPLICATION_NOTES, OSR_APPLICATION_TYPE, OSR_APPLICATION_COMMERCIAL, OSR_TIMESTAMP, OSR_ISSUE_DATE)
- VALUES
- ( SEQ_OSR_ID.NEXTVAL, 1, 'ACTIVE', P_OSR_USA_ID_REF, P_OSR_CONSUMER_KEY, P_OSR_CONSUMER_SECRET,P_OSR_REQUESTER_NAME,
- P_OSR_REQUESTER_EMAIL, P_OSR_CALLBACK_URI, P_OSR_APPLICATION_URI, P_OSR_APPLICATION_TITLE, P_OSR_APPLICATION_DESCR,
- P_OSR_APPLICATION_NOTES, P_OSR_APPLICATION_TYPE, P_OSR_APPLICATION_COMMERCIAL, SYSDATE, SYSDATE);
-
-
-EXCEPTION
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc b/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc
deleted file mode 100644
index 7826eb6..0000000
--- a/vendor/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc
+++ /dev/null
@@ -1,139 +0,0 @@
-CREATE OR REPLACE PROCEDURE SP_UPDATE_SERVER
-(
-P_CONSUMER_KEY IN VARCHAR2,
-P_USER_ID IN NUMBER,
-P_OCR_ID IN NUMBER,
-P_USER_IS_ADMIN IN NUMBER, -- 0:NO; 1:YES;
-P_OCR_CONSUMER_SECRET IN VARCHAR2,
-P_OCR_SERVER_URI IN VARCHAR2,
-P_OCR_SERVER_URI_HOST IN VARCHAR2,
-P_OCR_SERVER_URI_PATH IN VARCHAR2,
-P_OCR_REQUEST_TOKEN_URI IN VARCHAR2,
-P_OCR_AUTHORIZE_URI IN VARCHAR2,
-P_OCR_ACCESS_TOKEN_URI IN VARCHAR2,
-P_OCR_SIGNATURE_METHODS IN VARCHAR2,
-P_OCR_USA_ID_REF IN NUMBER,
-P_UPDATE_P_OCR_USA_ID_REF_FLAG IN NUMBER, -- 1:TRUE; 0:FALSE
-P_RESULT OUT NUMBER
-)
-AS
-
- -- Add a request token we obtained from a server.
-V_OCR_ID_EXIST NUMBER;
-V_OCR_USA_ID_REF NUMBER;
-
-V_EXC_DUPLICATE_CONSUMER_KEY EXCEPTION;
-V_EXC_UNAUTHORISED_USER_ID EXCEPTION;
-BEGIN
-P_RESULT := 0;
-
-V_OCR_USA_ID_REF := P_OCR_USA_ID_REF;
-
- IF P_OCR_ID IS NOT NULL THEN
- BEGIN
- SELECT 1 INTO V_OCR_ID_EXIST FROM DUAL WHERE EXISTS
- (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY
- WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY
- AND OCR_ID != P_OCR_ID
- AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL));
-
- EXCEPTION
- WHEN NO_DATA_FOUND THEN
- V_OCR_ID_EXIST :=0;
- END;
- ELSE
- BEGIN
- SELECT 1 INTO V_OCR_ID_EXIST FROM DUAL WHERE EXISTS
- (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY
- WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY
- AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL));
-
- EXCEPTION
- WHEN NO_DATA_FOUND THEN
- V_OCR_ID_EXIST :=0;
- END;
- END IF;
-
- IF V_OCR_ID_EXIST = 1 THEN
- RAISE V_EXC_DUPLICATE_CONSUMER_KEY;
- END IF;
-
-
- IF P_OCR_ID IS NOT NULL THEN
- IF P_USER_IS_ADMIN != 1 THEN
- BEGIN
- SELECT OCR_USA_ID_REF INTO V_OCR_USA_ID_REF
- FROM OAUTH_CONSUMER_REGISTRY
- WHERE OCR_ID = P_OCR_ID;
-
- EXCEPTION
- WHEN NO_DATA_FOUND THEN
- NULL;
- END;
-
- IF V_OCR_USA_ID_REF != P_USER_ID THEN
- RAISE V_EXC_UNAUTHORISED_USER_ID;
- END IF;
- END IF;
-
- IF P_UPDATE_P_OCR_USA_ID_REF_FLAG = 0 THEN
-
- UPDATE OAUTH_CONSUMER_REGISTRY
- SET OCR_CONSUMER_KEY = P_CONSUMER_KEY,
- OCR_CONSUMER_SECRET = P_OCR_CONSUMER_SECRET,
- OCR_SERVER_URI = P_OCR_SERVER_URI,
- OCR_SERVER_URI_HOST = P_OCR_SERVER_URI_HOST,
- OCR_SERVER_URI_PATH = P_OCR_SERVER_URI_PATH,
- OCR_TIMESTAMP = SYSDATE,
- OCR_REQUEST_TOKEN_URI = P_OCR_REQUEST_TOKEN_URI,
- OCR_AUTHORIZE_URI = P_OCR_AUTHORIZE_URI,
- OCR_ACCESS_TOKEN_URI = P_OCR_ACCESS_TOKEN_URI,
- OCR_SIGNATURE_METHODS = P_OCR_SIGNATURE_METHODS
- WHERE OCR_ID = P_OCR_ID;
-
- ELSIF P_UPDATE_P_OCR_USA_ID_REF_FLAG = 1 THEN
- UPDATE OAUTH_CONSUMER_REGISTRY
- SET OCR_CONSUMER_KEY = P_CONSUMER_KEY,
- OCR_CONSUMER_SECRET = P_OCR_CONSUMER_SECRET,
- OCR_SERVER_URI = P_OCR_SERVER_URI,
- OCR_SERVER_URI_HOST = P_OCR_SERVER_URI_HOST,
- OCR_SERVER_URI_PATH = P_OCR_SERVER_URI_PATH,
- OCR_TIMESTAMP = SYSDATE,
- OCR_REQUEST_TOKEN_URI = P_OCR_REQUEST_TOKEN_URI,
- OCR_AUTHORIZE_URI = P_OCR_AUTHORIZE_URI,
- OCR_ACCESS_TOKEN_URI = P_OCR_ACCESS_TOKEN_URI,
- OCR_SIGNATURE_METHODS = P_OCR_SIGNATURE_METHODS,
- OCR_USA_ID_REF = P_OCR_USA_ID_REF
- WHERE OCR_ID = P_OCR_ID;
-
- END IF;
-
- ELSE
- IF P_UPDATE_P_OCR_USA_ID_REF_FLAG = 0 THEN
- V_OCR_USA_ID_REF := P_USER_ID;
- END IF;
-
- INSERT INTO OAUTH_CONSUMER_REGISTRY
- (OCR_ID, OCR_CONSUMER_KEY ,OCR_CONSUMER_SECRET, OCR_SERVER_URI, OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH,
- OCR_TIMESTAMP, OCR_REQUEST_TOKEN_URI, OCR_AUTHORIZE_URI, OCR_ACCESS_TOKEN_URI, OCR_SIGNATURE_METHODS,
- OCR_USA_ID_REF)
- VALUES
- (SEQ_OCR_ID.NEXTVAL, P_CONSUMER_KEY, P_OCR_CONSUMER_SECRET, P_OCR_SERVER_URI, P_OCR_SERVER_URI_HOST, P_OCR_SERVER_URI_PATH,
- SYSDATE, P_OCR_REQUEST_TOKEN_URI, P_OCR_AUTHORIZE_URI, P_OCR_ACCESS_TOKEN_URI, P_OCR_SIGNATURE_METHODS,
- V_OCR_USA_ID_REF);
-
- END IF;
-
-
-EXCEPTION
-WHEN V_EXC_DUPLICATE_CONSUMER_KEY THEN
-P_RESULT := 2; -- DUPLICATE_CONSUMER_KEY
-WHEN V_EXC_UNAUTHORISED_USER_ID THEN
-P_RESULT := 3; -- UNAUTHORISED_USER_ID
-
-WHEN OTHERS THEN
--- CALL THE FUNCTION TO LOG ERRORS
-ROLLBACK;
-P_RESULT := 1; -- ERROR
-END;
-/
diff --git a/vendor/oauth-php/library/store/oracle/install.php b/vendor/oauth-php/library/store/oracle/install.php
deleted file mode 100644
index 5a80f04..0000000
--- a/vendor/oauth-php/library/store/oracle/install.php
+++ /dev/null
@@ -1,28 +0,0 @@
-<?php
-
-
-/**
- Added by Vinay Kant Sahu.
-vinaykant.sahu@gmail.com
- * Storage container for the oauth credentials, both server and consumer side.
- * Based on Oracle
- *
-
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
-
-
-
- */
-
-echo 'Right now we do not have Oracle DB installer.
-Please find OracleDB folder here with this Table, Sequences and Procedures. You need to manually install/create DB schema and SP with your oracle DB. ';
-?> \ No newline at end of file
diff --git a/vendor/oauth-php/library/store/postgresql/pgsql.sql b/vendor/oauth-php/library/store/postgresql/pgsql.sql
deleted file mode 100644
index 8f0e4d3..0000000
--- a/vendor/oauth-php/library/store/postgresql/pgsql.sql
+++ /dev/null
@@ -1,166 +0,0 @@
-#
-# Log table to hold all OAuth request when you enabled logging
-#
-
-CREATE TABLE oauth_log (
- olg_id serial primary key,
- olg_osr_consumer_key varchar(64),
- olg_ost_token varchar(64),
- olg_ocr_consumer_key varchar(64),
- olg_oct_token varchar(64),
- olg_usa_id_ref text,
- olg_received text not null,
- olg_sent text not null,
- olg_base_string text not null,
- olg_notes text not null,
- olg_timestamp timestamp not null default current_timestamp,
- olg_remote_ip inet not null
-);
-
-COMMENT ON TABLE oauth_log IS 'Log table to hold all OAuth request when you enabled logging';
-
-
-#
-# /////////////////// CONSUMER SIDE ///////////////////
-#
-
-# This is a registry of all consumer codes we got from other servers
-# The consumer_key/secret is obtained from the server
-# We also register the server uri, so that we can find the consumer key and secret
-# for a certain server. From that server we can check if we have a token for a
-# particular user.
-
-CREATE TABLE oauth_consumer_registry (
- ocr_id serial primary key,
- ocr_usa_id_ref text,
- ocr_consumer_key varchar(128) not null,
- ocr_consumer_secret varchar(128) not null,
- ocr_signature_methods varchar(255) not null default 'HMAC-SHA1,PLAINTEXT',
- ocr_server_uri varchar(255) not null,
- ocr_server_uri_host varchar(128) not null,
- ocr_server_uri_path varchar(128) not null,
-
- ocr_request_token_uri varchar(255) not null,
- ocr_authorize_uri varchar(255) not null,
- ocr_access_token_uri varchar(255) not null,
- ocr_timestamp timestamp not null default current_timestamp,
-
- unique (ocr_consumer_key, ocr_usa_id_ref, ocr_server_uri)
-);
-
-COMMENT ON TABLE oauth_consumer_registry IS 'This is a registry of all consumer codes we got from other servers';
-
-# Table used to sign requests for sending to a server by the consumer
-# The key is defined for a particular user. Only one single named
-# key is allowed per user/server combination
-
--- Create enum type token_type
-CREATE TYPE consumer_token_type AS ENUM (
- 'request',
- 'authorized',
- 'access'
-);
-
-CREATE TABLE oauth_consumer_token (
- oct_id serial primary key,
- oct_ocr_id_ref integer not null,
- oct_usa_id_ref text not null,
- oct_name varchar(64) not null default '',
- oct_token varchar(64) not null,
- oct_token_secret varchar(64) not null,
- oct_token_type consumer_token_type,
- oct_token_ttl timestamp not null default timestamp '9999-12-31',
- oct_timestamp timestamp not null default current_timestamp,
-
- unique (oct_ocr_id_ref, oct_token),
- unique (oct_usa_id_ref, oct_ocr_id_ref, oct_token_type, oct_name),
-
- foreign key (oct_ocr_id_ref) references oauth_consumer_registry (ocr_id)
- on update cascade
- on delete cascade
-);
-
-
-COMMENT ON TABLE oauth_consumer_token IS 'Table used to sign requests for sending to a server by the consumer';
-
-#
-# ////////////////// SERVER SIDE /////////////////
-#
-
-# Table holding consumer key/secret combos an user issued to consumers.
-# Used for verification of incoming requests.
-
-CREATE TABLE oauth_server_registry (
- osr_id serial primary key,
- osr_usa_id_ref text,
- osr_consumer_key varchar(64) not null,
- osr_consumer_secret varchar(64) not null,
- osr_enabled boolean not null default true,
- osr_status varchar(16) not null,
- osr_requester_name varchar(64) not null,
- osr_requester_email varchar(64) not null,
- osr_callback_uri varchar(255) not null,
- osr_application_uri varchar(255) not null,
- osr_application_title varchar(80) not null,
- osr_application_descr text not null,
- osr_application_notes text not null,
- osr_application_type varchar(20) not null,
- osr_application_commercial boolean not null default false,
- osr_issue_date timestamp not null,
- osr_timestamp timestamp not null default current_timestamp,
-
- unique (osr_consumer_key)
-);
-
-
-COMMENT ON TABLE oauth_server_registry IS 'Table holding consumer key/secret combos an user issued to consumers';
-
-# Nonce used by a certain consumer, every used nonce should be unique, this prevents
-# replaying attacks. We need to store all timestamp/nonce combinations for the
-# maximum timestamp received.
-
-CREATE TABLE oauth_server_nonce (
- osn_id serial primary key,
- osn_consumer_key varchar(64) not null,
- osn_token varchar(64) not null,
- osn_timestamp bigint not null,
- osn_nonce varchar(80) not null,
-
- unique (osn_consumer_key, osn_token, osn_timestamp, osn_nonce)
-);
-
-
-COMMENT ON TABLE oauth_server_nonce IS 'Nonce used by a certain consumer, every used nonce should be unique, this prevents replaying attacks';
-
-# Table used to verify signed requests sent to a server by the consumer
-# When the verification is succesful then the associated user id is returned.
-
--- Create enum type token_type
-CREATE TYPE server_token_type AS ENUM (
- 'request',
- 'access'
-);
-
-CREATE TABLE oauth_server_token (
- ost_id serial primary key,
- ost_osr_id_ref integer not null,
- ost_usa_id_ref text not null,
- ost_token varchar(64) not null,
- ost_token_secret varchar(64) not null,
- ost_token_type server_token_type,
- ost_authorized boolean not null default false,
- ost_referrer_host varchar(128) not null default '',
- ost_token_ttl timestamp not null default timestamp '9999-12-31',
- ost_timestamp timestamp not null default current_timestamp,
- ost_verifier char(10),
- ost_callback_url varchar(512),
-
- unique (ost_token),
-
- foreign key (ost_osr_id_ref) references oauth_server_registry (osr_id)
- on update cascade
- on delete cascade
-);
-
-
-COMMENT ON TABLE oauth_server_token IS 'Table used to verify signed requests sent to a server by the consumer';
diff --git a/vendor/oauth-php/test/discovery/xrds-fireeagle.xrds b/vendor/oauth-php/test/discovery/xrds-fireeagle.xrds
deleted file mode 100644
index 0f5eba2..0000000
--- a/vendor/oauth-php/test/discovery/xrds-fireeagle.xrds
+++ /dev/null
@@ -1,78 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<XRDS xmlns="xri://$xrds">
-
- <!-- FireEagle User-Centric OAuth Configuration -->
- <XRD xml:id="oauth" xmlns:simple="http://xrds-simple.net/core/1.0" xmlns="xri://$XRD*($v*2.0)" version="2.0">
-
- <Type>xri://$xrds*simple</Type>
- <Expires>2008-04-15T00:25:30-07:00</Expires>
-
- <!-- Request Token -->
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/request</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/parameters/post-body</Type>
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
- <Type>http://oauth.net/core/1.0/signature/HMAC-SHA1</Type>
- <Type>http://oauth.net/core/1.0/signature/PLAINTEXT</Type>
-
- <URI>https://fireeagle.yahooapis.com/oauth/request_token</URI>
- </Service>
-
- <!-- User Authorization -->
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/authorize</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
-
- <URI>https://fireeagle.yahooapis.com/oauth/access_token</URI>
- </Service>
-
- <!-- Access Token -->
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/access</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/parameters/post-body</Type>
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
- <Type>http://oauth.net/core/1.0/signature/HMAC-SHA1</Type>
- <Type>http://oauth.net/core/1.0/signature/PLAINTEXT</Type>
-
- <URI>http://fireeagle.yahoo.net/oauth/authorize</URI>
- </Service>
-
- <!-- Protected Resources -->
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/resource</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/parameters/post-body</Type>
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
- <Type>http://oauth.net/core/1.0/signature/HMAC-SHA1</Type>
- <Type>http://oauth.net/core/1.0/signature/PLAINTEXT</Type>
- </Service>
-
- <!-- Consumer Identity -->
-
- <!-- Manual Consumer Identity Allocation -->
- <Service>
- <Type>http://oauth.net/discovery/1.0/consumer-identity/oob</Type>
- <URI>https://fireeagle.yahoo.net/developer/create</URI>
- </Service>
- </XRD>
-
- <!-- Global Resource Definition -->
-
- <XRD xmlns="xri://$XRD*($v*2.0)" version="2.0">
- <Type>xri://$xrds*simple</Type>
-
- <!-- OAuth Endpoints Definition -->
- <Service>
- <Type>http://oauth.net/discovery/1.0</Type>
- <URI>#oauth</URI>
- </Service>
- </XRD>
-
-</XRDS> \ No newline at end of file
diff --git a/vendor/oauth-php/test/discovery/xrds-getsatisfaction.xrds b/vendor/oauth-php/test/discovery/xrds-getsatisfaction.xrds
deleted file mode 100644
index ab94b5b..0000000
--- a/vendor/oauth-php/test/discovery/xrds-getsatisfaction.xrds
+++ /dev/null
@@ -1,73 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<XRDS xmlns="xri://$xrds">
-
- <XRD xml:id="oauth" xmlns:simple="http://xrds-simple.net/core/1.0" xmlns="xri://$XRD*($v*2.0)" version="2.0">
- <Type>xri://$xrds*simple</Type>
- <Expires>2008-04-30T23:59:59Z</Expires>
-
- <!-- Request Token -->
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/request</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/signature/HMAC-SHA1</Type>
-
- <URI>http://getsatisfaction.com/api/request_token</URI>
- </Service>
-
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/authorize</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
-
- <URI>http://getsatisfaction.com/api/authorize</URI>
- </Service>
-
- <!-- Access Token -->
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/access</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/signature/HMAC-SHA1</Type>
-
- <URI>http://getsatisfaction.com/api/access_token</URI>
- </Service>
-
- <!-- Protected Resources -->
- <!--
-
- To test successful access token grant, make a request against
-
- http://api.getsatisfaction.com/me
-
- The API should respond with hCard of the user who authorized the token
- -->
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/resource</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/signature/HMAC-SHA1</Type>
-
- </Service>
-
- <!-- Consumer Identity -->
-
- <Service>
- <Type>http://oauth.net/discovery/1.0/consumer-identity/oob</Type>
- <URI>http://getsatisfaction.com/me/extensions/new</URI>
- </Service>
- </XRD>
-
- <!-- Global Resource Definition -->
-
- <XRD xmlns="xri://$XRD*($v*2.0)" version="2.0">
- <Type>xri://$xrds*simple</Type>
-
- <!-- OAuth Endpoints Definition -->
- <Service priority="10">
- <Type>http://oauth.net/discovery/1.0</Type>
- <URI>#oauth</URI>
- </Service>
- </XRD>
-
-</XRDS> \ No newline at end of file
diff --git a/vendor/oauth-php/test/discovery/xrds-magnolia.xrds b/vendor/oauth-php/test/discovery/xrds-magnolia.xrds
deleted file mode 100644
index 361b5c9..0000000
--- a/vendor/oauth-php/test/discovery/xrds-magnolia.xrds
+++ /dev/null
@@ -1,81 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<XRDS xmlns="xri://$xrds">
-
- <!-- Ma.gnolia OAuth Configuration -->
- <XRD xml:id="oauth" xmlns="xri://$XRD*($v*2.0)" version="2.0">
-
- <Type>xri://$xrds*simple</Type>
- <Expires>2008-04-13T07:34:58Z</Expires>
-
- <!-- Request Token -->
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/request</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/parameters/post-body</Type>
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
- <Type>http://oauth.net/core/1.0/signature/HMAC-SHA1</Type>
- <Type>http://oauth.net/core/1.0/signature/RSA-SHA1</Type>
- <Type>http://oauth.net/core/1.0/signature/PLAINTEXT</Type>
-
- <URI>https://ma.gnolia.com/oauth/get_request_token</URI>
- </Service>
-
- <!-- User Authorization (HTTPS Prefered) -->
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/authorize</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
-
- <URI priority="10">https://ma.gnolia.com/oauth/authorize</URI>
- <URI priority="20">http://ma.gnolia.com/oauth/authorize</URI>
- </Service>
-
- <!-- Access Token -->
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/access</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/parameters/post-body</Type>
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
- <Type>http://oauth.net/core/1.0/signature/HMAC-SHA1</Type>
- <Type>http://oauth.net/core/1.0/signature/RSA-SHA1</Type>
- <Type>http://oauth.net/core/1.0/signature/PLAINTEXT</Type>
-
- <URI>https://ma.gnolia.com/oauth/get_access_token</URI>
- </Service>
-
- <!-- Protected Resources -->
- <Service>
- <Type>http://oauth.net/core/1.0/endpoint/resource</Type>
-
- <Type>http://oauth.net/core/1.0/parameters/auth-header</Type>
- <Type>http://oauth.net/core/1.0/parameters/post-body</Type>
- <Type>http://oauth.net/core/1.0/parameters/uri-query</Type>
- <Type>http://oauth.net/core/1.0/signature/HMAC-SHA1</Type>
- <Type>http://oauth.net/core/1.0/signature/RSA-SHA1</Type>
- </Service>
-
- <!-- Consumer Identity -->
-
- <!-- Manual Consumer Identity Allocation -->
- <Service>
- <Type>http://oauth.net/discovery/1.0/consumer-identity/oob</Type>
- <URI>http://ma.gnolia.com/applications/new</URI>
- </Service>
- </XRD>
-
- <!-- Global Resource Definition -->
-
- <XRD xmlns="xri://$XRD*($v*2.0)" version="2.0">
- <Type>xri://$xrds*simple</Type>
-
- <!-- OAuth Endpoints Definition -->
- <Service priority="10">
- <Type>http://oauth.net/discovery/1.0</Type>
- <URI>#oauth</URI>
- </Service>
- </XRD>
-
-</XRDS> \ No newline at end of file
diff --git a/vendor/oauth-php/test/oauth_test.php b/vendor/oauth-php/test/oauth_test.php
deleted file mode 100644
index c7d174b..0000000
--- a/vendor/oauth-php/test/oauth_test.php
+++ /dev/null
@@ -1,188 +0,0 @@
-<?php
-
-/**
- * Tests of OAuth implementation.
- *
- * @version $Id$
- * @author Marc Worrell <marcw@pobox.com>
- * @date Nov 29, 2007 3:46:56 PM
- * @see http://wiki.oauth.net/TestCases
- *
- * The MIT License
- *
- * Copyright (c) 2007-2008 Mediamatic Lab
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-require_once dirname(__FILE__) . '/../library/OAuthRequest.php';
-require_once dirname(__FILE__) . '/../library/OAuthRequester.php';
-require_once dirname(__FILE__) . '/../library/OAuthRequestSigner.php';
-require_once dirname(__FILE__) . '/../library/OAuthRequestVerifier.php';
-
-if (!function_exists('getallheaders'))
-{
- function getallheaders()
- {
- return array();
- }
-}
-
-
-oauth_test();
-
-function oauth_test ()
-{
- error_reporting(E_ALL);
-
- header('Content-Type: text/plain; charset=utf-8');
-
- echo "Performing OAuth module tests.\n\n";
- echo "See also: http://wiki.oauth.net/TestCases\n\n";
-
- assert_options(ASSERT_CALLBACK, 'oauth_assert_handler');
- assert_options(ASSERT_WARNING, 0);
-
- $req = new OAuthRequest('http://www.example.com', 'GET');
-
- echo "***** Parameter Encoding *****\n\n";
-
- assert('$req->urlencode(\'abcABC123\') == \'abcABC123\'');
- assert('$req->urlencode(\'-._~\') == \'-._~\'');
- assert('$req->urlencode(\'%\') == \'%25\'');
- assert('$req->urlencode(\'&=*\') == \'%26%3D%2A\'');
- assert('$req->urlencode(\'&=*\') == \'%26%3D%2A\'');
- assert('$req->urlencode("\n") == \'%0A\'');
- assert('$req->urlencode(" ") == \'%20\'');
- assert('$req->urlencode("\x7f") == \'%7F\'');
-
-
- echo "***** Normalize Request Parameters *****\n\n";
-
- $req = new OAuthRequest('http://example.com/?name', 'GET');
- assert('$req->getNormalizedParams() == \'name=\'');
-
- $req = new OAuthRequest('http://example.com/?a=b', 'GET');
- assert('$req->getNormalizedParams() == \'a=b\'');
-
- $req = new OAuthRequest('http://example.com/?a=b&c=d', 'GET');
- assert('$req->getNormalizedParams() == \'a=b&c=d\'');
-
- // At this moment we don't support two parameters with the same name
- // so I changed this test case to "a=" and "b=" and not "a=" and "a="
- $req = new OAuthRequest('http://example.com/?b=x!y&a=x+y', 'GET');
- assert('$req->getNormalizedParams() == \'a=x%2By&b=x%21y\'');
-
- $req = new OAuthRequest('http://example.com/?x!y=a&x=a', 'GET');
- assert('$req->getNormalizedParams() == \'x=a&x%21y=a\'');
-
-
- echo "***** Base String *****\n\n";
-
- $req = new OAuthRequest('http://example.com/?n=v', 'GET');
- assert('$req->signatureBaseString() == \'GET&http%3A%2F%2Fexample.com%2F&n%3Dv\'');
-
- $req = new OAuthRequest(
- 'https://photos.example.net/request_token',
- 'POST',
- 'oauth_version=1.0&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_timestamp=1191242090&oauth_nonce=hsu94j3884jdopsl&oauth_signature_method=PLAINTEXT&oauth_signature=ignored',
- array('X-OAuth-Test' => true));
- assert('$req->signatureBaseString() == \'POST&https%3A%2F%2Fphotos.example.net%2Frequest_token&oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dhsu94j3884jdopsl%26oauth_signature_method%3DPLAINTEXT%26oauth_timestamp%3D1191242090%26oauth_version%3D1.0\'');
-
- $req = new OAuthRequest(
- 'http://photos.example.net/photos?file=vacation.jpg&size=original&oauth_version=1.0&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_token=nnch734d00sl2jdk&oauth_timestamp=1191242096&oauth_nonce=kllo9940pd9333jh&oauth_signature=ignored&oauth_signature_method=HMAC-SHA1',
- 'GET');
- assert('$req->signatureBaseString() == \'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal\'');
-
-
- echo "***** HMAC-SHA1 *****\nRequest signing\n";
-
- OAuthStore::instance('MySQL', array('conn'=>false));
- $req = new OAuthRequestSigner('http://photos.example.net/photos?file=vacation.jpg&size=original', 'GET');
-
- assert('$req->urldecode($req->calculateDataSignature(\'bs\', \'cs\', \'\', \'HMAC-SHA1\')) == \'egQqG5AJep5sJ7anhXju1unge2I=\'');
- assert('$req->urldecode($req->calculateDataSignature(\'bs\', \'cs\', \'ts\', \'HMAC-SHA1\')) == \'VZVjXceV7JgPq/dOTnNmEfO0Fv8=\'');
-
- $secrets = array(
- 'consumer_key' => 'dpf43f3p2l4k3l03',
- 'consumer_secret' => 'kd94hf93k423kf44',
- 'token' => 'nnch734d00sl2jdk',
- 'token_secret' => 'pfkkdhi9sl3r4s00',
- 'signature_methods' => array('HMAC-SHA1'),
- 'nonce' => 'kllo9940pd9333jh',
- 'timestamp' => '1191242096'
- );
- $req->sign(0, $secrets);
- assert('$req->getParam(\'oauth_signature\', true) == \'tR3+Ty81lMeYAr/Fid0kMTYa/WM=\'');
-
- echo "***** HMAC-SHA1 *****\nRequest verification\n";
-
- $req = new OAuthRequestVerifier(
- 'http://photos.example.net/photos?file=vacation.jpg&size=original'
- .'&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_token=nnch734d00sl2jdk'
- .'&oauth_signature_method=HMAC-SHA1&oauth_nonce=kllo9940pd9333jh'
- .'&oauth_timestamp=1191242096&oauth_version=1.0'
- .'&oauth_signature='.rawurlencode('tR3+Ty81lMeYAr/Fid0kMTYa/WM=')
- , 'GET');
-
- $req->verifySignature('kd94hf93k423kf44', 'pfkkdhi9sl3r4s00');
-
- echo "\n";
- echo "***** Yahoo! test case ******\n\n";
-
- OAuthStore::instance('MySQL', array('conn'=>false));
- $req = new OAuthRequestSigner('http://example.com:80/photo', 'GET');
-
- $req->setParam('title', 'taken with a 30% orange filter');
- $req->setParam('file', 'mountain & water view');
- $req->setParam('format', 'jpeg');
- $req->setParam('include', array('date','aperture'));
-
- $secrets = array(
- 'consumer_key' => '1234=asdf=4567',
- 'consumer_secret' => 'erks823*43=asd&123ls%23',
- 'token' => 'asdf-4354=asew-5698',
- 'token_secret' => 'dis9$#$Js009%==',
- 'signature_methods' => array('HMAC-SHA1'),
- 'nonce' => '3jd834jd9',
- 'timestamp' => '12303202302'
- );
- $req->sign(0, $secrets);
-
- // echo "Basestring:\n",$req->signatureBaseString(), "\n\n";
-
- //echo "queryString:\n",$req->getQueryString(), "\n\n";
- assert('$req->getQueryString() == \'title=taken%20with%20a%2030%25%20orange%20filter&file=mountain%20%26%20water%20view&format=jpeg&include=date&include=aperture\'');
-
- //echo "oauth_signature:\n",$req->getParam('oauth_signature', true),"\n\n";
- assert('$req->getParam(\'oauth_signature\', true) == \'jMdUSR1vOr3SzNv3gZ5DDDuGirA=\'');
-
- echo "\n\nFinished.\n";
-}
-
-
-function oauth_assert_handler ( $file, $line, $code )
-{
- echo "\nAssertion failed in $file:$line
- $code\n\n";
-}
-
-/* vi:set ts=4 sts=4 sw=4 binary noeol: */
-
-?> \ No newline at end of file