public function runPreRoutingFilters(ezcMvcRequest $request) { $pos = ezcPersistentSessionInstance::get(); $q = $pos->createFindQuery('aiiSitesClass'); $q->where($q->expr->eq('host', $q->bindValue($request->host))); $sites = $pos->find($q, 'aiiSitesClass'); return current($sites); }
public function testDelayedInit2() { try { $instance2 = ezcPersistentSessionInstance::get('delayed2'); } catch (ezcPersistentSessionNotFoundException $e) { $this->assertEquals("Could not find the persistent session: delayed2.", $e->getMessage()); } }
public function testSetWithIdentifierMixed() { $session = $this->getSession(); $sessionDecorator = $this->getSessionDecorator($session); ezcPersistentSessionInstance::set($session, 'session'); ezcPersistentSessionInstance::set($sessionDecorator, 'decorator'); $this->assertSame($session, ezcPersistentSessionInstance::get('session')); $this->assertSame($sessionDecorator, ezcPersistentSessionInstance::get('decorator')); }
/** * Returns the authorization object for a user & application * @param ezpRestClient $client * @param eZUser $user */ public static function fetchForClientUser(ezpRestClient $client, eZUser $user) { $session = ezcPersistentSessionInstance::get(); $q = $session->createFindQuery(__CLASS__); $q->where($q->expr->eq('rest_client_id', $q->bindValue($client->id)))->where($q->expr->eq('user_id', $q->bindValue($user->attribute('contentobject_id')))); $results = $session->find($q, __CLASS__); if (count($results) != 1) { return false; } else { return array_shift($results); } }
public function doRead() { $pos = ezcPersistentSessionInstance::get(); $q = $pos->createFindQuery('aiiPagesClass'); $where = array($q->expr->eq('slug', $q->bindValue($this->request->variables['slug']))); if (array_key_exists('site', $this->request->variables)) { $where[] = $q->expr->eq('site_id', $q->bindValue($this->request->variables['site']->id)); } call_user_func_array(array($q, 'where'), $where); $pages = $pos->find($q, 'aiiPagesClass'); $page = current($pages); $ret = new aiiPagesResult(); $ret->variables['page'] = $page; if (array_key_exists('site', $this->request->variables)) { $ret->variables['site'] = $this->request->variables['site']; } return $ret; }
public function run($credentials) { // Checking for existance of token $session = ezcPersistentSessionInstance::get(); $q = $session->createFindQuery('ezpRestToken'); $q->where($q->expr->eq('id', $q->bindValue($credentials->id))); $tokenInfo = $session->find($q, 'ezpRestToken'); if (empty($tokenInfo)) { // return self::STATUS_TOKEN_INVALID; throw new ezpOauthInvalidTokenException("Specified token does not exist."); } $tokenInfo = array_shift($tokenInfo); // Check expiry of token if ($tokenInfo->expirytime !== 0) { if ($tokenInfo->expirytime < time()) { $d = date("c", $tokenInfo->expirytime); // return self::STATUS_TOKEN_EXPIRED; throw new ezpOauthExpiredTokenException("Token expired on {$d}"); } } // Extra step to be implemented // Check if user's access grant is still valid or if it has been revoked. // Scope checking to be implemented. // Currently some hooks ought to be added to eZP to maximise the // benefit to this field. return self::STATUS_OK; // Fetch and validate token for validity and optionally scope. // Either let teh request pass, or immediately bail with 401. // Section 5.2.1 for error handling. // // invalid_request missing required params -> 400 // // invalid_token Expired token which cannot be refreshed -> 401 // // expired_token Token has expired -> 401 // // insufficient_scope The requested scope is outside scope associated with token -> 403 // // Do not include error info for requests which did not contain auth details.ref. 5.2.1 }
/** * Fetches an ezpRestToken persistent object from an access token * @param string $accessToken Access token hash string * @param bool $authCheck If true, will also check if token corresponds to a client app authorized by its user * @return ezpRestToken */ public static function fetch( $accessToken, $authCheck = true ) { $tokenInfo = null; $session = ezcPersistentSessionInstance::get(); $q = $session->createFindQuery( __CLASS__ ); $e = $q->expr; $q->innerJoin( 'ezprest_clients', 'ezprest_token.client_id', 'ezprest_clients.client_id' ); if ( $authCheck ) { $q->innerJoin( 'ezprest_authorized_clients', $e->lAnd( $e->eq( 'ezprest_authorized_clients.rest_client_id', 'ezprest_clients.id' ), $e->eq( 'ezprest_authorized_clients.user_id', 'ezprest_token.user_id' ) ) ); } $q->where( $q->expr->eq( 'ezprest_token.id', $q->bindValue( $accessToken ) ) ); $tokenInfo = $session->find( $q, 'ezpRestToken' ); if ( !empty( $tokenInfo ) ) { $tokenInfo = array_shift( $tokenInfo ); } else // Empty array. For consistency in result, cast it to null { $tokenInfo = null; } return $tokenInfo; }
<?php /** * File containing the oauthadmin/action view definition * * @copyright Copyright (C) 1999-2011 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version //autogentag// * @package kernel */ $session = ezcPersistentSessionInstance::get(); $module = $Params['Module']; // new application: create draft, redirect to edit this draft if ( $module->isCurrentAction( 'NewApplication' ) ) { $user = eZUser::currentUser(); $application = new ezpRestClient(); $application->name = ezpI18n::tr( 'extension/oauthadmin', 'New REST application' ); $application->version = ezpRestClient::STATUS_DRAFT; $application->owner_id = $user->attribute( 'contentobject_id' ); $application->created = time(); $application->updated = 0; $application->version = ezpRestClient::STATUS_DRAFT; $session->save( $application ); // The following does not work on PostgreSQL, incorrect id. Probably need refresh from DB. return $module->redirectToView( 'edit', array( $application->id ) ); }
/** * Generates a new token against an authorization_code * Auth code is checked against clientId, clientSecret and redirectUri as registered for client in admin * Auth code is for one-use only and will be removed once the access token generated * @param string $clientId Client identifier * @param string $clientSecret Client secret key * @param string $authCode Authorization code provided by the client * @param string $redirectUri Redirect URI. Must be the same as registered in admin * @return ezpRestToken * @throws ezpOauthInvalidRequestException * @throws ezpOauthInvalidTokenException * @throws ezpOauthExpiredTokenException */ public static function doRefreshTokenWithAuthorizationCode($clientId, $clientSecret, $authCode, $redirectUri) { $client = ezpRestClient::fetchByClientId($clientId); $tokenTTL = (int) eZINI::instance('rest.ini')->variable('OAuthSettings', 'TokenTTL'); if (!$client instanceof ezpRestClient) { throw new ezpOauthInvalidRequestException(ezpOauthTokenEndpointErrorType::INVALID_CLIENT); } if (!$client->validateSecret($clientSecret)) { throw new ezpOauthInvalidRequestException(ezpOauthTokenEndpointErrorType::INVALID_CLIENT); } if (!$client->isEndPointValid($redirectUri)) { throw new ezpOauthInvalidRequestException(ezpOauthTokenEndpointErrorType::INVALID_REQUEST); } $session = ezcPersistentSessionInstance::get(); $q = $session->createFindQuery('ezpRestAuthcode'); $q->where($q->expr->eq('id', $q->bindValue($authCode))); $codeInfo = $session->find($q, 'ezpRestAuthcode'); if (empty($codeInfo)) { throw new ezpOauthInvalidTokenException("Specified authorization code does not exist."); } $codeInfo = array_shift($codeInfo); // Validate client is still authorized, then validate code is not expired $authorized = ezpRestAuthorizedClient::fetchForClientUser($client, eZUser::fetch($codeInfo->user_id)); if (!$authorized instanceof ezpRestAuthorizedClient) { throw new ezpOauthInvalidRequestException(ezpOauthTokenEndpointErrorType::INVALID_CLIENT); } // Check expiry of authorization_code if ($codeInfo->expirytime != 0) { if ($codeInfo->expirytime < time()) { $d = date("c", $codeInfo->expirytime); throw new ezpOauthExpiredTokenException("Authorization code expired on {$d}"); } } // code ok, create access and refresh tokens $accessToken = ezpRestToken::generateToken(''); $refreshToken = ezpRestToken::generateToken(''); $token = new ezpRestToken(); $token->id = $accessToken; $token->refresh_token = $refreshToken; $token->client_id = $clientId; $token->user_id = $codeInfo->user_id; $token->expirytime = time() + $tokenTTL; $session = ezcPersistentSessionInstance::get(); $session->save($token); // After an auth code is used, we'll remove it so it is not abused $session->delete($codeInfo); return $token; }
/** * Shows the merge queue items */ public function doMergeQueue() { $result = new ezcMvcResult(); $result->variables['page_title'] = 'Merge queue status :: MKV Manager'; $result->variables['items'] = $this->items; switch( $this->items ) { case 'active': $statuses = array( mmMergeOperation::STATUS_PENDING, mmMergeOperation::STATUS_RUNNING ); break; case 'archive': $statuses = array( mmMergeOperation::STATUS_ARCHIVED ); break; case 'done': $statuses = array( mmMergeOperation::STATUS_DONE ); break; case 'error': $statuses = array( mmMergeOperation::STATUS_ERROR ); break; default: throw new ezcBaseFileNotFoundException( $this->items ); } $session = ezcPersistentSessionInstance::get(); $q = $session->createFindQuery( 'mmMergeOperation' ); $q->where( $q->expr->in( 'status', $statuses ) ) ->orderBy( 'create_time', 'asc' ); $operations = $session->find( $q, 'mmMergeOperation' ); $result->variables['operations'] = $operations; $htmlTable = ''; $operationStructs = array(); foreach( $operations as $hash => $operation ) { $htmlTable .= "<tr class=\"status\">" . "<td>{$operation->hash}</td>". "<td>".basename( $operation->targetFile )."</td>". "<td>{$operation->createTime}</td>". "<td>{$operation->endTime}</td>". "<td><progress id=\"progressBar\" value=\"".$operation->progress()."\" max=\"100\"></progress><span class=\"percent\">".$operation->progress()."%</span></td>". "</tr>"; $operationStructs[$hash] = $operation->asStruct(); } $result->variables['html_table'] = $htmlTable; $result->variables['operations'] = $operationStructs; return $result; }
/** * Handles the POST request which is sent to obtain token data. * * Currently only authorization code access grant is supported, section 4.1.1 * * @return ezcMvcResult */ public function doHandleRequest() { // Check that the correct params are present // Params for token endpoint per section 4 // REQUIRED: grant_type, client_id, client_secret // OPTIONAL: scope // // Supported grant types are: authorization_code and refresh_token // // Additional params for 'authorization_code', Section 4.1.1 // REQUIRED: code, redirect_uri // // Additional param for 'refresh_token", Section 4.1.4 // REQUIRED: refresh_token // Defining the required params for each stage of operation $initialRequiredParams = array('grant_type', 'client_id', 'client_secret'); // params for grant_type=authorization_code $codeRequiredParams = array('code', 'redirect_uri'); // params for grant_type=refresh_token $refreshRequiredParams = array('refresh_token'); $this->checkParams($initialRequiredParams); // We can get the first set of required params $grant_type = $this->request->post['grant_type']; $client_id = $this->request->post['client_id']; $client_secret = $this->request->post['client_secret']; if (!$this->validateGrantType($grant_type)) { throw new ezpOauthInvalidRequestException(ezpOauthTokenEndpointErrorType::UNSUPPORTED_GRANT_TYPE); } switch ($grant_type) { case 'authorization_code': $this->checkParams($codeRequiredParams); $authCode = $this->request->post['code']; $redirect_uri = $this->request->post['redirect_uri']; $client = ezpRestClient::fetchByClientId($client_id); if (!$client instanceof ezpRestClient) { throw new ezpOauthInvalidRequestException(ezpOauthTokenEndpointErrorType::INVALID_CLIENT); } if (!$client->validateSecret($client_secret)) { throw new ezpOauthInvalidRequestException(ezpOauthTokenEndpointErrorType::INVALID_CLIENT); } if (!$client->isEndPointValid($redirect_uri)) { throw new ezpOauthInvalidRequestException(ezpOauthTokenEndpointErrorType::INVALID_REQUEST); } $session = ezcPersistentSessionInstance::get(); $q = $session->createFindQuery('ezpRestAuthcode'); $q->where($q->expr->eq('id', $q->bindValue($authCode))); $codeInfo = $session->find($q, 'ezpRestAuthcode'); if (empty($codeInfo)) { // return self::STATUS_TOKEN_INVALID; throw new ezpOauthInvalidTokenException("Specified authorization code does not exist."); } $codeInfo = array_shift($codeInfo); // Validate client is still authorized, then validate code is not expired $authorized = ezpRestAuthorizedClient::fetchForClientUser($client, eZUser::fetch($codeInfo->user_id)); if (!$authorized instanceof ezpRestAuthorizedClient) { throw new ezpOauthInvalidRequestException(ezpOauthTokenEndpointErrorType::INVALID_CLIENT); } // Check expiry of token if ($codeInfo->expirytime !== 0) { if ($codeInfo->expirytime < time()) { $d = date("c", $codeInfo->expirytime); // return self::STATUS_TOKEN_EXPIRED; throw new ezpOauthExpiredTokenException("Token expired on {$d}"); } } // code eok, create access token $accessToken = ezpRestToken::generateToken(''); $refreshToken = ezpRestToken::generateToken(''); $token = new ezpRestToken(); $token->id = $accessToken; $token->refresh_token = $refreshToken; $token->client_id = $client_id; $token->user_id = $codeInfo->user_id; $token->expirytime = time() + 3600; $session = ezcPersistentSessionInstance::get(); $session->save($token); //@TODO for later, check for transmission over https $r = new ezcMvcResult(); $r->status = new ezcMvcExternalRedirect($redirect_uri . '?access_token=' . $token->id); return $r; break; case 'refresh_token': $this->checkParams($refreshRequiredParams); $refreshToken = $this->request->post['refresh_token']; break; } }
public function doSourcefileArchive() { $result = new ezcMvcResult(); $nonExistingFiles = array(); $hash = $this->hash; if ( $queueItem = mmMergeOperation::fetchByHash( $hash ) ) { $status = 'ok'; $message = ''; $removed = array(); $command = $queueItem->commandObject; if ( $command->conversionType == 'tvshow' ) { $files = array_merge( $command->VideoFiles, $command->SubtitleFiles ); foreach( $files as $file ) { $extension = pathinfo( $file['pathname'], PATHINFO_EXTENSION ); if ( ( $extension == 'mkv' or $extension == 'avi' ) && file_exists( $file['pathname']) && filesize( $file['pathname'] ) == 0 ) { $result->variables['status'] = 'ko'; $result->variables['message'] = 'already_archived'; return $result; } if ( !file_exists( $file['pathname'] ) ) { $nonExistingFiles[] = $file; } else { if ( !isset( $dummyFile ) ) $dummyFile = $file['pathname']; $removed[] = $file['pathname']; unlink( $file['pathname'] ); } } touch( $dummyFile ); } else { $mainFile = $command->VideoFiles[0]['pathname']; if ( file_exists( $mainFile ) ) { $directory = dirname( $mainFile ); $files[] = glob( "$directory/*" ); try { ezcBaseFile::removeRecursive( $directory ); $removed = $files; } catch( ezcBaseFilePermissionException $e ) { $status = 'ko'; $message = $e->getMessage(); } } } if ( !empty( $nonExistingFiles ) ) $result->variables['messages'] = 'Some files were not found, see [not_found_files]'; if ( $status === 'ok' ) { $queueItem->status = mmMergeOperation::STATUS_ARCHIVED; ezcPersistentSessionInstance::get()->update( $queueItem ); } $result->variables['status'] = $status; $result->variables['removed_files'] = $removed; $result->variables['not_found_files'] = $nonExistingFiles; $result->variables['message'] = $message; } else { // @todo Handle with exception $result->variables['status'] = 'ko'; $result->variables['message'] = "No operation with hash $hash"; } return $result; }
/** * Updates the stored version of the process */ public function update() { ezcPersistentSessionInstance::get()->update( $this ); }
public function testResetWithIdentifiers() { $manager = new ezcPersistentCodeManager(dirname(__FILE__) . "/PersistentObject/tests/data/"); $session1 = new ezcPersistentSession(ezcDbInstance::get(), $manager); $session2 = new ezcPersistentSession(ezcDbInstance::get(), $manager); ezcPersistentSessionInstance::set($session1, 'first'); ezcPersistentSessionInstance::set($session2, 'secondary'); $this->assertSame($session1, ezcPersistentSessionInstance::get('first')); $this->assertSame($session2, ezcPersistentSessionInstance::get('secondary')); ezcPersistentSessionInstance::reset(); try { ezcPersistentSessionInstance::get('first'); $this->fail("Getting a non existent instance did not fail."); } catch (ezcPersistentSessionNotFoundException $e) { } try { ezcPersistentSessionInstance::get('secondary'); $this->fail("Getting a non existent instance did not fail."); } catch (ezcPersistentSessionNotFoundException $e) { } }
public function getForm() { $form = new Zend_Form(); $form->setName($this->poClass . "_form"); $schema = $this->schema->getSchema(); foreach ($this->getEditableProperties() as $propertyName => $property) { $methodName = 'get' . ucfirst($propertyName) . 'Element'; if (method_exists($this, $methodName)) { $form->addElement($this->{$methodName}()); continue; } $dbField = $schema[$this->poDef->table]->fields[$property->columnName]; $dbType = $dbField->type; switch ($dbType) { case 'integer': case 'timestamp': case 'boolean': $element = new Zend_Form_Element_Text($propertyName); $element->addValidator('allnum'); $element->addFilter('int'); break; case 'float': case 'decimal': $element = new Zend_Form_Element_Text($propertyName); break; case 'blob': case 'clob': $element = new Zend_Form_Element_Textarea($propertyName); break; case 'text': case 'time': case 'date': default: $element = new Zend_Form_Element_Text($propertyName); break; } if (list($relatedClassName, $relationDef) = $this->isFK($property->columnName)) { $element = new Zend_Form_Element_Select($propertyName); $pos = ezcPersistentSessionInstance::get(); $q = $pos->createFindQuery($relatedClassName); $this->queryHook($q); $list = $pos->find($q, $relatedClassName); $element->options = $list; $element->addFilter('int'); } if (!$this->isNullProperty($property->columnName, $this->poDef->table)) { $element->setRequired(true)->addValidator('NotEmpty'); } $element->setLabel($propertyName); $form->addElement($element); } $submit = new Zend_Form_Element_Submit('submit'); $submit->setLabel('Submit'); $form->addElement($submit); $form->clearDecorators(); $form->addDecorator('FormElements')->addDecorator('HtmlTag', array('tag' => '<ul>'))->addDecorator('Form'); $form->setElementDecorators(array(array('ViewHelper'), array('Errors'), array('Description'), array('Label', array('separator' => ' ')), array('HtmlTag', array('tag' => 'li', 'class' => 'element-group')))); // buttons do not need labels $submit->setDecorators(array(array('ViewHelper'), array('Description'), array('HtmlTag', array('tag' => 'li', 'class' => 'submit-group')))); $form->setView(new Zend_View()); return $form; }
protected function getRelatedObjects($relation) { $dbsession = ezcPersistentSessionInstance::get(); if ($relation['orderBy']) { $objects = $dbsession->getRelatedObjects($this, $relation['class'], $relation['name']); } else { if ($relation['name']) { $q = $dbsession->createRelationFindQuery($this, $relation['class'], $relation['name']); } else { $q = $dbsession->createRelationFindQuery($this, $relation['class']); } $q->orderBy($relation['orderBy']); try { if ($relation['name']) { $objects = $dbsession->find($q, $relation['class'], $relation['name']); } else { $objects = $dbsession->getRelatedObjects($this, $relation['class']); } } catch (ezcPersistentRelatedObjectNotFoundException $e) { return null; } } if ($relation['type'] == 'single') { return array_shift($objects); } else { return $objects; } }
/** * Authorizes this application for a user * @param eZUser $user * @return void */ public function authorizeFor($user = null) { $authorization = new ezpRestAuthorizedClient(); $authorization->rest_client_id = $this->id; $authorization->user_id = $user->attribute('contentobject_id'); $session = ezcPersistentSessionInstance::get(); $session->save($authorization); }
<?php require_once 'tutorial_autoload.php'; class customLazyPersistentSessionConfiguration implements ezcBaseConfigurationInitializer { public static function configureObject($instance) { switch ($instance) { case null: // Default instance $session = new ezcPersistentSession(ezcDbInstance::get(), new ezcPersistentCodeManager('../persistent')); return $session; case 'second': $session = new ezcPersistentSession(ezcDbInstance::get(), new ezcPersistentCodeManager('../additionalPersistent')); return $session; } } } ezcBaseInit::setCallback('ezcInitPersistentSessionInstance', 'customLazyPersistentSessionConfiguration'); // Create and configure default persistent session $db = ezcPersistentSessionInstance::get(); // Create and configure additional persistent session $sb = ezcPersistentSessionInstance::get('second');