/** * Test with project path set */ public function testWithProjectPathSet() { $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_working_path_mandatory')); $this->parameters->set('workingPath', '/path/to/project/'); $task = new ProjectPathMandatory(); $result = $task($this->route, $this->console, $this->parameters); $this->assertEquals(0, $result); }
/** * @param Parameters $params * * @return Parameters */ protected function initDefaults(Parameters $params) { if (is_null($params->get('quality')) || !strlen(trim($params->get('quality')))) { $params->set('quality', QualityInterface::QUALITY_THUMBNAIL); } if (is_null($params->get('source')) || !strlen(trim($params->get('source')))) { $params->set('source', SourceNameInterface::SOURCE_USER); } return $params; }
/** * @param $request * @return array|mixed|User * @throws \Exception */ public function login($request) { $adapter = $this->getAuthPlugin()->getAuthAdapter(); $pin = $request->get('pin'); $accountId = $request->get('accountId'); if (!empty($pin)) { $user = $this->getUserByPin($pin, $accountId); $credentials = array('username' => $user->getUsername(), 'password' => $user->getPassword()); } else { $credentials = array('username' => $request->get('username'), 'password' => $request->get('password')); } $params = new Parameters(); $params->set('identity', $credentials['username']); $params->set('credential', $credentials['password']); $emulatedRequest = new Request(); $emulatedRequest->setPost($params); $result = $adapter->prepareForAuthentication($emulatedRequest); if ($result instanceof Response) { return $result; } $auth = $this->getAuthPlugin()->getAuthService()->authenticate($adapter); if (!$auth->isValid()) { $isRegistered = $this->isRegistered($credentials); $accountUser = $this->getAccountUsersByParams($params); if ($accountUser != null && !$isRegistered) { if ($this->getAgencyIsDeleted($accountUser->getAccountId())) { throw new \Exception(self::AGENCY_DELETED_MESSAGE); } return $this->createUserFromAccountUsers($accountUser); } $account = $this->getAccountByParams($params); if ($account != null && !$isRegistered) { return $this->createUserFromAccount($account); } if ($accountUser != null && $isRegistered) { return $this->updateUser($accountUser); } $result = $auth->getMessages(); $message = "Bad request."; if (isset($result[0])) { $message = $result[0]; } throw new \Exception($message); } $accountUser = $this->getAccountUsersByParams($params); if ($this->getAgencyIsDeleted($accountUser->getAccountId())) { throw new \Exception(self::AGENCY_DELETED_MESSAGE); } if ($this->getUserIsDeleted($credentials['username'])) { throw new \Exception(self::USER_DELETED_MESSAGE); } $user = $this->getAuthPlugin()->getIdentity(); return $user; }
/** * Test with controller existing */ public function testWithKnownHydrators() { $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_base_hydrator_param_unknown')); $this->console->expects($this->never())->method('colorize'); $knownHydrators = ['ArraySerializable', 'ClassMethods', 'ObjectProperty', 'Reflection']; foreach ($knownHydrators as $hydrator) { $this->parameters->set('paramBaseHydrator', $hydrator); $task = new BaseHydratorParam(); $result = $task($this->route, $this->console, $this->parameters); $this->assertEquals(0, $result); } }
public function testRunActionWithParams() { $params = array('strict' => true, 'verbose' => true, 'debug' => true); $runner = $this->getMockForAbstractClass('HumusPHPUnitModule\\RunnerInterface'); $runner->expects($this->once())->method('setParams')->with($params); $runner->expects($this->once())->method('run'); $params = new Parameters(); $params->set('strict', true); $params->set('verbose', true); $params->set('debug', true); $this->request->setParams($params); $this->controller->setRunner($runner); $response = new Response(); $this->controller->dispatch($this->request, $response); }
/** * Test with module path existing */ public function testWithModulePathExisting() { $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_working_path_not_exists')); $this->console->expects($this->never())->method('colorize'); $this->parameters->set('projectModuleDir', $this->zf2rapidModuleDir); $task = new ModulePathExists(); $result = $task($this->route, $this->console, $this->parameters); $this->assertEquals(0, $result); }
/** * Test with controller plugin existing */ public function testWithControllerPluginExisting() { $this->console->expects($this->once())->method('writeTaskLine')->with($this->equalTo('task_check_checking_file'), ['controller plugin']); $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_file_exists_not_found')); $this->console->expects($this->never())->method('colorize'); $this->parameters->set('controllerPluginDir', $this->zf2rapidControllerPluginDir); $this->parameters->set('paramControllerPlugin', $this->zf2rapidControllerPluginName); file_put_contents($this->zf2rapidControllerPluginDir . $this->zf2rapidControllerPluginFile, 'class TestPlugin {}'); $task = new ControllerPluginExists(); $result = $task($this->route, $this->console, $this->parameters); $this->assertEquals(0, $result); }
/** * Test with form existing */ public function testWithFormExisting() { $this->console->expects($this->once())->method('writeTaskLine')->with($this->equalTo('task_check_checking_file'), ['form']); $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_file_exists_not_found')); $this->console->expects($this->never())->method('colorize'); $this->parameters->set('formDir', $this->zf2rapidFormDir); $this->parameters->set('paramForm', $this->zf2rapidFormName); file_put_contents($this->zf2rapidFormDir . $this->zf2rapidFormFile, 'class TestForm {}'); $task = new FormExists(); $result = $task($this->route, $this->console, $this->parameters); $this->assertEquals(0, $result); }
/** * Test with validator existing */ public function testWithValidatorExisting() { $this->console->expects($this->once())->method('writeTaskLine')->with($this->equalTo('task_check_checking_file'), array('validator')); $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_file_exists_not_found')); $this->console->expects($this->never())->method('colorize'); $this->parameters->set('validatorDir', $this->zf2rapidValidatorDir); $this->parameters->set('paramValidator', $this->zf2rapidValidatorName); file_put_contents($this->zf2rapidValidatorDir . $this->zf2rapidValidatorFile, 'class TestValidator {}'); $task = new ValidatorExists(); $result = $task($this->route, $this->console, $this->parameters); $this->assertEquals(0, $result); }
/** * Test with existing file */ public function testWithExistingFile() { $this->parameters->set('workingPath', $this->zf2rapidFileDir); $expectedConfig = array('foo' => 'bar', 'one' => 'two'); file_put_contents($this->zf2rapidFileDir . $this->zf2rapidFileName, json_encode($expectedConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); $task = new ConfigFile(); $result = $task($this->route, $this->console, $this->parameters); $this->assertEquals(0, $result); $this->assertEquals($expectedConfig, $this->parameters->config); $this->assertFileExists($this->zf2rapidFileDir . $this->zf2rapidFileName); $this->assertEquals($expectedConfig, json_decode(file_get_contents($this->zf2rapidFileDir . $this->zf2rapidFileName), true)); }
public function testPagesActionCanBeAccessedByPost() { $this->routeMatch->setParam('action', 'pages'); $this->request->setMethod('POST'); $p = new Parameters(); $p->set('role_id', '1'); $this->request->setPost($p); $result = $this->controller->dispatch($this->request); $response = $this->controller->getResponse(); $this->assertInstanceOf('Zend\\Http\\Response', $result); $this->assertEquals(302, $response->getStatusCode()); }
/** * Test hydrator param */ public function testHydratorParam() { $this->parameters->set('moduleSrcDir', '/path/to/module/dir/testModule/src'); $this->parameters->set('config', ['namespaceHydrator' => 'Model\\Hydrator']); $paramValueMap = [['hydrator', null, 'HydratorName'], ['baseHydrator', null, 'BaseHydrator']]; $this->route->method('getMatchedParam')->will($this->returnValueMap($paramValueMap)); $task = new Params(); $result = $task($this->route, $this->console, $this->parameters); $this->assertEquals(0, $result); $this->assertEquals('HydratorName', $this->parameters->paramHydrator); $this->assertEquals('BaseHydrator', $this->parameters->paramBaseHydrator); $this->assertEquals('/path/to/module/dir/testModule/src/Model/Hydrator', $this->parameters->hydratorDir); }
/** * Test with existing file */ public function testWithExistingFile() { $this->parameters->set('workingPath', $this->zf2rapidFileDir); $setupConfig = ['foo' => 'bar', 'one' => 'two']; file_put_contents($this->zf2rapidFileDir . $this->zf2rapidFileName, json_encode($setupConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); $expectedConfig = array_merge($setupConfig, ['configFileFormat' => 'php', 'flagAddDocBlocks' => 'true', 'fileDocBlockText' => 'ZF2 Application built by ZF2rapid', 'fileDocBlockCopyright' => '(c) 2015 John Doe', 'fileDocBlockLicense' => 'http://opensource.org/licenses/MIT The MIT License (MIT)', 'namespaceController' => 'Controller', 'namespaceControllerPlugin' => 'Controller\\Plugin', 'namespaceViewHelper' => 'View\\Helper', 'namespaceFilter' => 'Filter', 'namespaceValidator' => 'Validator', 'namespaceInputFilter' => 'InputFilter', 'namespaceForm' => 'Form', 'namespaceHydrator' => 'Hydrator', 'namespaceEntity' => 'Entity', 'namespaceTableGateway' => 'TableGateway', 'namespaceStorage' => 'Storage', 'namespaceRepository' => 'Repository']); $task = new ConfigFile(); $result = $task($this->route, $this->console, $this->parameters); $this->assertEquals(0, $result); $this->assertEquals($expectedConfig, $this->parameters->config); $this->assertFileExists($this->zf2rapidFileDir . $this->zf2rapidFileName); $this->assertEquals($expectedConfig, json_decode(file_get_contents($this->zf2rapidFileDir . $this->zf2rapidFileName), true)); }
/** * Test with module dir creating succeed */ public function testWithModuleDirCreatingSucceed() { $this->console->expects($this->once())->method('writeTaskLine')->with($this->equalTo('task_create_structure_module_root_created')); $this->console->expects($this->once())->method('colorize'); $this->parameters->set('moduleDir', $this->zf2rapidModuleDir); $this->parameters->set('moduleConfigDir', $this->zf2rapidModuleDir . 'config/'); $this->parameters->set('moduleSrcDir', $this->zf2rapidModuleDir . 'src/'); $this->parameters->set('moduleViewDir', $this->zf2rapidModuleDir . 'view/'); $task = new CreateModuleStructure(); $result = $task($this->route, $this->console, $this->parameters); $this->assertEquals(0, $result); $this->assertFileExists($this->zf2rapidModuleDir); $this->assertFileExists($this->zf2rapidModuleDir . 'config/'); $this->assertFileExists($this->zf2rapidModuleDir . 'src/'); $this->assertFileExists($this->zf2rapidModuleDir . 'view/'); }
/** * Test with project path not allowed file */ public function testWithProjectPathNotAllowedFile() { if (!file_exists($this->zf2rapidProjectPath)) { mkdir($this->zf2rapidProjectPath); } if (!file_exists($this->zf2rapidProjectPath . $this->zf2rapidNotAllowedFile)) { file_put_contents($this->zf2rapidProjectPath . $this->zf2rapidNotAllowedFile, 'test'); } $this->console->expects($this->once())->method('writeFailLine')->with($this->equalTo('task_check_working_path_not_empty')); $this->console->expects($this->once())->method('colorize'); $this->parameters->set('workingPath', $this->zf2rapidProjectPath); $this->assertFileExists($this->zf2rapidProjectPath); $task = new ProjectPathEmpty(); $result = $task($this->route, $this->console, $this->parameters); $this->assertEquals(1, $result); $this->assertFileExists($this->zf2rapidProjectPath); }
public function testParametersPersistNameAndValues() { $parameters = new Parameters(array('foo' => 'bar')); $this->assertEquals('bar', $parameters['foo']); $this->assertEquals('bar', $parameters->foo); $parameters->offsetSet('baz', 5); $this->assertEquals(5, $parameters->baz); $parameters->fromArray(array('bar' => 'foo')); $this->assertEquals('foo', $parameters->bar); $parameters->fromString('bar=foo&five=5'); $this->assertEquals('foo', $parameters->bar); $this->assertEquals('5', $parameters->five); $this->assertEquals(array('bar' => 'foo', 'five' => '5'), $parameters->toArray()); $this->assertEquals('bar=foo&five=5', $parameters->toString()); $parameters->fromArray(array()); $parameters->set('foof', 'barf'); $this->assertEquals('barf', $parameters->get('foof')); $this->assertEquals('barf', $parameters->foof); }
/** * Loop through configuration to discover and set controller options. * * @param array $config * @param RestController $controller */ protected function setControllerOptions(array $config, RestController $controller) { foreach ($config as $option => $value) { switch ($option) { case 'collection_http_methods': $controller->setCollectionHttpMethods($value); break; case 'collection_name': $controller->setCollectionName($value); break; case 'collection_query_whitelist': if (is_string($value)) { $value = (array) $value; } if (!is_array($value)) { break; } // Create a listener that checks the query string against // the whitelisted query parameters in order to seed the // collection route options. $whitelist = $value; $controller->getEventManager()->attach('getList.pre', function (Event $e) use($whitelist) { $controller = $e->getTarget(); $resource = $controller->getResource(); if (!$resource instanceof Resource) { // ResourceInterface does not define setQueryParams, so we need // specifically a Resource instance return; } $request = $controller->getRequest(); if (!method_exists($request, 'getQuery')) { return; } $query = $request->getQuery(); $params = new Parameters(array()); foreach ($query as $key => $value) { if (!in_array($key, $whitelist)) { continue; } $params->set($key, $value); } $resource->setQueryParams($params); }); $controller->getEventManager()->attach('getList.post', function (Event $e) use($whitelist) { $controller = $e->getTarget(); $resource = $controller->getResource(); if (!$resource instanceof Resource) { // ResourceInterface does not define setQueryParams, so we need // specifically a Resource instance return; } $collection = $e->getParam('collection'); if (!$collection instanceof Collection) { return; } $params = $resource->getQueryParams()->getArrayCopy(); // Set collection route options with the captured query whitelist, to // ensure paginated links are generated correctly $collection->setCollectionRouteOptions(array('query' => $params)); // If no self link defined, set the options in the collection and return $links = $collection->getLinks(); if (!$links->has('self')) { return; } // If self link is defined, but is not route-based, return $self = $links->get('self'); if (!$self->hasRoute()) { return; } // Otherwise, merge the query string parameters with // the self link's route options $self = $links->get('self'); $options = $self->getRouteOptions(); $self->setRouteOptions(array_merge($options, array('query' => $params))); }); break; case 'entity_http_methods': $controller->setEntityHttpMethods($value); break; /** * The identifierName is a property of the ancestor * and is described by Apigility as route_identifier_name */ /** * The identifierName is a property of the ancestor * and is described by Apigility as route_identifier_name */ case 'route_identifier_name': $controller->setIdentifierName($value); break; case 'page_size': $controller->setPageSize($value); break; case 'page_size_param': $controller->setPageSizeParam($value); break; /** * @todo Remove this by 1.0; BC only, starting in 0.9.0 */ /** * @todo Remove this by 1.0; BC only, starting in 0.9.0 */ case 'resource_http_methods': $controller->setEntityHttpMethods($value); break; case 'route_name': $controller->setRoute($value); break; } } }
/** * Pull the search parameters * * @param \Zend\StdLib\Parameters $request Parameter object representing user * request. * * @return void */ public function initFromRequest($request) { // Check for advanced search from VuFind1 missing join and/or bool parameter: if (null === $request->get('lookfor')) { if (null === $request->get('join')) { $request->set('join', 'AND'); } $bool0 = $request->get('bool0'); if (!is_array($bool0) || empty(array_filter($bool0))) { $request->set('bool0', ['AND']); } } // Check for VuFind1 orfilters and convert them: if ($orFilters = $request->get('orfilter')) { $filters = $request->get('filter', []); foreach ($orFilters as $filter) { $filters[] = "~{$filter}"; } $request->set('filter', $filters); $request->set('orfilter', null); } parent::initFromRequest($request); $this->setDebugQuery($request->get('debugSolrQuery', false)); }
/** * * @dataProvider providerTestRegisterAction * @depend testActionControllHasIdentity * @depend testRegisterActionIsNotAllowed */ public function testRegisterAction($wantRedirect, $postRedirectGetReturn, $registerSuccess, $loginAfterSuccessWith) { $controller = $this->controller; $redirectUrl = 'http://localhost/redirect1'; $route_url = '/user/register'; $expectedResult = null; $this->setUpZfcUserAuthenticationPlugin(array('hasIdentity' => false)); $this->options->expects($this->any())->method('getEnableRegistration')->will($this->returnValue(true)); $request = $this->getMock('Zend\\Http\\Request'); $this->helperMakePropertyAccessable($controller, 'request', $request); $userService = $this->getMock('\\ZfcUser\\Service\\User'); $controller->setUserService($userService); $form = $this->getMockBuilder('\\Zend\\Form\\Form')->disableOriginalConstructor()->getMock(); $controller->setRegisterForm($form); $this->options->expects($this->any())->method('getUseRedirectParameterIfPresent')->will($this->returnValue((bool) $wantRedirect)); if ($wantRedirect) { $params = new Parameters(); $params->set('redirect', $redirectUrl); $request->expects($this->any())->method('getQuery')->will($this->returnValue($params)); } $url = $this->getMock('Zend\\Mvc\\Controller\\Plugin\\Url'); $url->expects($this->at(0))->method('fromRoute')->with($controller::ROUTE_REGISTER)->will($this->returnValue($route_url)); $this->pluginManagerPlugins['url'] = $url; $prg = $this->getMock('\\Zend\\Mvc\\Controller\\Plugin\\PostRedirectGet'); $this->pluginManagerPlugins['prg'] = $prg; $redirectQuery = $wantRedirect ? '?redirect=' . rawurlencode($redirectUrl) : ''; $prg->expects($this->once())->method('__invoke')->with($route_url . $redirectQuery)->will($this->returnValue($postRedirectGetReturn)); if ($registerSuccess) { $user = new UserIdentity(); $user->setEmail('*****@*****.**'); $user->setUsername('zfc-user'); $userService->expects($this->once())->method('register')->with($postRedirectGetReturn)->will($this->returnValue($user)); $userService->expects($this->any())->method('getOptions')->will($this->returnValue($this->options)); $this->options->expects($this->once())->method('getLoginAfterRegistration')->will($this->returnValue(!empty($loginAfterSuccessWith))); if ($loginAfterSuccessWith) { $this->options->expects($this->once())->method('getAuthIdentityFields')->will($this->returnValue(array($loginAfterSuccessWith))); $expectedResult = new \stdClass(); $forwardPlugin = $this->getMockBuilder('Zend\\Mvc\\Controller\\Plugin\\Forward')->disableOriginalConstructor()->getMock(); $forwardPlugin->expects($this->once())->method('dispatch')->with($controller::CONTROLLER_NAME, array('action' => 'authenticate'))->will($this->returnValue($expectedResult)); $this->pluginManagerPlugins['forward'] = $forwardPlugin; } else { $response = new Response(); $route_url = '/user/login'; $redirectUrl = isset($postRedirectGetReturn['redirect']) ? $postRedirectGetReturn['redirect'] : null; $redirectQuery = $redirectUrl ? '?redirect=' . rawurlencode($redirectUrl) : ''; $redirect = $this->getMock('Zend\\Mvc\\Controller\\Plugin\\Redirect'); $redirect->expects($this->once())->method('toUrl')->with($route_url . $redirectQuery)->will($this->returnValue($response)); $this->pluginManagerPlugins['redirect'] = $redirect; $url->expects($this->at(1))->method('fromRoute')->with($controller::ROUTE_LOGIN)->will($this->returnValue($route_url)); } } /*********************************************** * run */ $result = $controller->registerAction(); /*********************************************** * assert */ if ($postRedirectGetReturn instanceof Response) { $expectedResult = $postRedirectGetReturn; } if ($expectedResult) { $this->assertSame($expectedResult, $result); return; } if ($postRedirectGetReturn === false) { $expectedResult = array('registerForm' => $form, 'enableRegistration' => true, 'redirect' => $wantRedirect ? $redirectUrl : false); } elseif ($registerSuccess === false) { $expectedResult = array('registerForm' => $form, 'enableRegistration' => true, 'redirect' => isset($postRedirectGetReturn['redirect']) ? $postRedirectGetReturn['redirect'] : null); } if ($expectedResult) { $this->assertInternalType('array', $result); $this->assertArrayHasKey('registerForm', $result); $this->assertArrayHasKey('enableRegistration', $result); $this->assertArrayHasKey('redirect', $result); $this->assertEquals($expectedResult, $result); } else { $this->assertInstanceOf('\\Zend\\Http\\Response', $result); $this->assertSame($response, $result); } }
/** * This method returns an array of strings matching the user's query for * display in the autocomplete box. * * @param string $query The user query * * @return array The suggestions for the provided query */ public function getSuggestions($query) { $params = $this->searchObject->getParams(); $this->request->set('filter', $this->request->get('hiddenFilters')); $params->initSpatialDateRangeFilter($this->request); $this->searchObject->getOptions()->disableHighlighting(); if (!$this->facetingDisabled) { foreach ($this->facetSettings as $field => $facets) { foreach ($facets as $key => $facet) { if (!empty($facet['tabs']) && (!$this->searchTab || !in_array($this->searchTab, $facet['tabs']))) { unset($this->facetSettings[$field][$key]); } } } $facetLimit = 20; $params->setFacetLimit($facetLimit); $allFacets = array_keys($this->facetSettings); $facets = array_diff($allFacets, $this->hierarchicalFacets); foreach ($facets as $facet) { $params->addFacet($facet, null, $this->useOrFacet($facet)); } } $suggestionsLimit = isset($this->searchConfig->Autocomplete->suggestions) ? $this->searchConfig->Autocomplete->suggestions : 5; $suggestions = parent::getSuggestions($query); if (!empty($suggestions)) { $suggestions = array_splice($suggestions, 0, $suggestionsLimit); } $facets = []; if (!$this->facetingDisabled) { $getFacetValues = function ($facet) { return [$facet['value'], $facet['count']]; }; $facetResults = []; // Facets foreach ($this->searchObject->getFacetList() as $field => $data) { $filtered = $this->filterFacetValues($field, $data['list']); foreach ($filtered as $data) { $values = $this->extractFacetData($field, $data['values']); $facetResults[$data['pos']] = $values; } } // Hierarchical facets $this->initSearchObject(); $this->searchObject->getOptions()->disableHighlighting(); $this->searchObject->getParams()->setBasicSearch($this->mungeQuery($query), $this->handler); $this->searchObject->getParams()->setSort($this->sortField); foreach ($this->filters as $current) { $this->searchObject->getParams()->addFilter($current); } foreach ($this->hierarchicalFacets as $facet) { $this->searchObject->getParams()->addFacet($facet, null, $this->useOrFacet($facet)); } $this->searchObject->getParams()->initSpatialDateRangeFilter($this->request); $hierachicalFacets = $this->searchObject->getFullFieldFacets(array_intersect($this->hierarchicalFacets, $allFacets), false, -1, 'count'); foreach ($hierachicalFacets as $field => $data) { $filtered = $this->filterFacetValues($field, $data['data']['list']); foreach ($filtered as $data) { $values = $this->extractFacetData($field, $data['values'], true); $facetResults[$data['pos']] = $values; } } $facets = $facetResults; } ksort($facets); $facets = array_values($facets); $result = compact('suggestions', 'facets'); return $result; }
/** * Parse upload content from a content stream * * @param resource $stream * @return array * @throws Exception\InvalidMultipartContentException */ protected function parseFromStream($stream) { $data = new Parameters(); $files = new Parameters(); $partInProgress = false; $inHeader = false; $headers = []; $header = false; $name = false; $content = ''; $file = []; $filename = false; $mimeType = false; $tmpFile = false; $partBoundaryPatternStart = '/^--' . $this->boundary . '(--)?/'; $partBoundaryPatternEnd = '/^--' . $this->boundary . '--$/'; while (false !== ($line = fgets($stream))) { $trimmedLine = rtrim($line); if (preg_match($partBoundaryPatternStart, $trimmedLine)) { if ($partInProgress) { // Time to handle the data we've already parsed! // Data if (!$filename) { $data->set($name, rtrim($content, "\r\n")); } // File (successful upload so far) if ($filename && $tmpFile) { // Write the last line, stripping the EOL characters if (false === fwrite($tmpFile, rtrim($lastline, "\r\n"))) { // Ooops! error writing the very last line! $file['error'] = UPLOAD_ERR_CANT_WRITE; fclose($tmpFile); } else { // Success! Let's try and guess the MIME type based on the file written fclose($tmpFile); if ($mimeType === 'application/octet-stream' && function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $type = finfo_file($finfo, $file['tmp_name']); if (false !== $type) { $file['type'] = $type; } } // Finally, set the filesize $file['size'] = filesize($file['tmp_name']); } } if ($filename) { // At this point, we can add the file entry, regardless of error condition $files->set($name, $file); } } // Is this a boundary end? If so, we're done if (preg_match($partBoundaryPatternEnd, $trimmedLine)) { // Met the "end" boundary; time to stop! break; } // New part to parse! $partInProgress = true; $inHeader = true; $headers = []; $header = ''; continue; } if (!$partInProgress) { // We're not inside a part, so do nothing. continue; } if ($inHeader) { if (preg_match('/^\\s*$/s', $line)) { // Headers are done; cleanup $inHeader = false; $content = ''; $file = ['error' => UPLOAD_ERR_OK]; $tmpFile = false; $lastline = null; // Parse headers $name = $this->getNameFromHeaders($headers); if (!$name) { throw new Exception\InvalidMultipartContentException('Missing Content-Disposition header, or Content-Disposition header does not ' . 'contain a "name" field'); } $filename = $this->getFilenameFromHeaders($headers); $mimeType = $this->getMimeTypeFromHeaders($headers); continue; } if (preg_match('/^(?P<header>[a-z]+[a-z0-9_-]+):\\s*(?P<value>.*)$/i', $trimmedLine, $matches)) { $header = strtoupper($matches['header']); $headers[$header] = $matches['value']; continue; } if (!$header) { throw new Exception\InvalidMultipartContentException('Malformed or missing MIME part header for multipart content'); } $headers[$header] .= $trimmedLine; continue; } // In the body content... // Data only; aggregate. if (!$filename) { $content .= $line; continue; } // If we've had an error already with the upload, continue parsing // to the end of the MIME part if ($file['error'] !== UPLOAD_ERR_OK) { continue; } // Create a temporary file handle if we haven't already if (!$tmpFile) { // Sets the file entry $file['name'] = $filename; $file['type'] = $mimeType; $tmpDir = $this->getUploadTempDir(); if (empty($tmpDir)) { // Cannot ascertain temporary directory; this is an error $file['error'] = UPLOAD_ERR_NO_TMP_DIR; continue; } $file['tmp_name'] = tempnam($tmpDir, 'zfc'); $tmpFile = fopen($file['tmp_name'], 'wb'); if (false === $tmpFile) { // Cannot open the temporary file for writing; this is an error $file['error'] = UPLOAD_ERR_CANT_WRITE; continue; } } // Off-by-one operation. Last line must be trimmed, so we'll write // the lines one iteration behind. if (null === $lastline) { $lastline = $line; continue; } if (false === fwrite($tmpFile, $lastline)) { $file['error'] = UPLOAD_ERR_CANT_WRITE; fclose($tmpFile); continue; } $lastline = $line; } fclose($stream); if ($files->count()) { $this->request->setFiles($files); } return $data->toArray(); }
/** * Send scheduled alerts for a view. * * @return void */ protected function processViewAlerts() { $this->msg(" Sending scheduled alerts for view: {$this->localDir} " . "(base: {$this->scheduleBaseUrl})"); $iso8601 = 'Y-m-d\\TH:i:s\\Z'; $configLoader = $this->getServiceLocator()->get('VuFind\\Config'); $this->iniReader = new IniReader(); $this->iniReader->setNestSeparator(chr(0)); $hmac = $this->getServiceLocator()->get('VuFind\\HMAC'); $userTable = $this->getTable('User'); $backend = $this->getServiceLocator()->get('VuFind\\Search\\BackendManager')->get('Solr'); $viewManager = $this->getServiceLocator()->get('viewmanager'); $viewModel = $viewManager->getViewModel(); $renderer = $viewManager->getRenderer(); $emailer = $this->getServiceLocator()->get('VuFind\\Mailer'); $translator = $renderer->plugin('translate'); $urlHelper = $renderer->plugin('url'); $todayTime = new \DateTime(); $user = false; $institution = false; $institutionConfigs = false; $scheduled = $this->searchTable->getScheduledSearches($this->scheduleBaseUrl); $this->msg(sprintf(' Processing %d searches', count($scheduled))); foreach ($scheduled as $s) { $lastTime = new \DateTime($s->finna_last_executed); $schedule = $s->finna_schedule; if ($schedule == 1) { // Daily if ($todayTime->format('Y-m-d') == $lastTime->format('Y-m-d')) { $this->msg(' Bypassing search ' . $s->id . ': previous execution too recent (daily, ' . $lastTime->format($iso8601) . ')'); continue; } } else { if ($schedule == 2) { $diff = $todayTime->diff($lastTime); if ($diff->days < 6) { $this->msg(' Bypassing search ' . $s->id . ': previous execution too recent (weekly, ' . $lastTime->format($iso8601) . ')'); continue; } } else { $this->err('Search ' . $s->id . ': unknown schedule: ' . $s->schedule); continue; } } if ($user === false || $s->user_id != $user->id) { if (!($user = $userTable->getById($s->user_id))) { $this->err('Search ' . $s->id . ': user ' . $s->user_id . ' does not exist '); continue; } } if (!$user->email || trim($user->email) == '') { $this->err('User ' . $user->username . ' does not have an email address, bypassing alert ' . $s->id); continue; } $scheduleUrl = parse_url($s->finna_schedule_base_url); if (!isset($scheduleUrl['host'])) { $this->err('Could not resolve institution for search ' . $s->id . ' with schedule_base_url: ' . var_export($scheduleUrl, true)); continue; } // Set email language $language = $this->mainConfig->Site->language; if ($user->finna_language != '' && in_array($user->finna_language, array_keys($this->mainConfig->Languages->toArray()))) { $language = $user->finna_language; } $this->getServiceLocator()->get('VuFind\\Translator')->addTranslationFile('ExtendedIni', null, $this->defaultPath, $language)->setLocale($language); $limit = 50; // Prepare query $searchService = $this->getServiceLocator()->get('VuFind\\Search'); $searchObject = $s->getSearchObject(); $finnaSearchObject = null; if ($searchObject instanceof \Finna\Search\Minified) { $finnaSearchObject = $searchObject; $searchObject = $finnaSearchObject->getParentSO(); } if ($searchObject->cl != 'Solr') { $this->err('Unsupported search class ' . $s->cl . ' for search ' . $s->id); continue; } $options = new Options($configLoader); $dateConverter = new DateConverter(); $params = new Params($options, $configLoader, $dateConverter); $params->deminify($searchObject); if ($finnaSearchObject) { $params->deminifyFinnaSearch($finnaSearchObject); } // Add daterange filter $daterangeField = $params::SPATIAL_DATERANGE_FIELD; $filters = $searchObject->f; if (isset($filters[$daterangeField])) { $req = new Parameters(); if ($finnaSearchObject && isset($finnaSearchObject->f_dty)) { $req->set("{$daterangeField}_type", $finnaSearchObject->f_dty); } $req->set('filter', ["{$daterangeField}:" . $filters[$daterangeField][0]]); $params->initSpatialDateRangeFilter($req); } $params->setLimit($limit); $params->setSort('first_indexed+desc'); $query = $params->getQuery(); $searchParams = $params->getBackendParameters(); $searchTime = gmdate($iso8601, time()); try { $collection = $searchService->search('Solr', $query, 0, $limit, $searchParams); $resultsTotal = $collection->getTotal(); if ($resultsTotal < 1) { $this->msg('No results found for search ' . $s->id); continue; } $records = $collection->getRecords(); } catch (\VuFindSearch\Backend\Exception\BackendException $e) { $this->err('Error processing search ' . $s->id . ': ' . $e->getMessage()); } $newestRecordDate = date($iso8601, strtotime($records[0]->getFirstIndexed())); $lastExecutionDate = $lastTime->format($iso8601); if ($newestRecordDate < $lastExecutionDate) { $this->msg('No new results for search ' . $s->id . ": {$newestRecordDate} < {$lastExecutionDate}"); continue; } // Collect records that have been indexed (for the first time) // after previous scheduled alert run $newRecords = []; foreach ($collection->getRecords() as $rec) { $recDate = date($iso8601, strtotime($rec->getFirstIndexed())); if ($recDate < $lastExecutionDate) { break; } $newRecords[] = $rec; } // Prepare email content $viewBaseUrl = $searchUrl = $s->finna_schedule_base_url; $searchUrl .= $urlHelper->__invoke($options->getSearchAction()); $urlQueryHelper = new UrlQueryHelper($params); $searchUrl .= str_replace('&', '&', $urlQueryHelper->getParams()); $secret = $s->getUnsubscribeSecret($hmac, $user); $unsubscribeUrl = $s->finna_schedule_base_url; $unsubscribeUrl .= $urlHelper->__invoke('myresearch-unsubscribe') . "?id={$s->id}&key={$secret}"; $params->setServiceLocator($this->getServiceLocator()); $filters = $this->processFilters($params->getFilterList()); $params = ['records' => $newRecords, 'info' => ['baseUrl' => $viewBaseUrl, 'description' => $params->getDisplayQuery(), 'recordCount' => count($records), 'url' => $searchUrl, 'unsubscribeUrl' => $unsubscribeUrl, 'filters' => $filters]]; $message = $renderer->render('Email/scheduled-alert.phtml', $params); $subject = $this->mainConfig->Site->title . ': ' . $translator->__invoke('Scheduled Alert Results'); $from = $this->mainConfig->Site->email; $to = $user->email; try { $this->getServiceLocator()->get('VuFind\\Mailer')->send($to, $from, $subject, $message); } catch (\Exception $e) { $this->err("Failed to send message to {$user->email}: " . $e->getMessage()); continue; } if ($s->setLastExecuted($searchTime) === 0) { $this->msg('Error updating last_executed date for search ' . $s->id); } } }
/** * Login form */ public function loginAction() { if ($this->UserAuthentication()->getAuthService()->hasIdentity()) { } $request = $this->getRequest(); $form = $this->getLoginForm(); $values = $this->fromJson(); $parameters = new Parameters(); $parameters->set('identity', $values->identity); $parameters->set('credential', $values->credential); $request->setPost($parameters); $post = $request->getPost(); $post->set('credential', trim($post->get('credential'))); $form->setData($post); if (!$form->isValid()) { } // clear adapters $this->UserAuthentication()->getAuthAdapter()->resetAdapters(); $this->UserAuthentication()->getAuthService()->clearIdentity(); $adapter = $this->UserAuthentication()->getAuthAdapter(); $adapter->prepareForAuthentication($this->getRequest()); $auth = $this->UserAuthentication()->getAuthService()->authenticate($adapter); if (!$auth->isValid()) { } if ($this->isUserLogin()) { $user = $this->em('User\\Document\\User')->find($this->getUserId()); $user->setAccessToken(hash('sha256', $this->getUserId())); $this->em()->persist($user); $this->em()->flush(); } return new JsonModel(['data' => 'ok']); /*$request = $this->getRequest(); $form = $this->getLoginForm(); if ($this->getOptions()->getUseRedirectParameterIfPresent() && $request->getQuery()->get('redirect')) { $redirect = $request->getQuery()->get('redirect'); } else { $redirect = false; } if (!$request->isPost()) { return array( 'loginForm' => $form, 'redirect' => $redirect, 'enableRegistration' => $this->getOptions()->getEnableRegistration(), ); } $post = $request->getPost(); $post->set('credential', trim($post->get('credential'))); $form->setData($post); if (!$form->isValid()) { $this->flashMessenger()->addErrorMessage($this->failedLoginMessage); return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN) . ($redirect ? '?redirect=' . $redirect : '')); } // clear adapters $this->UserAuthentication()->getAuthAdapter()->resetAdapters(); $this->UserAuthentication()->getAuthService()->clearIdentity(); return $this->forward()->dispatch(static::CONTROLLER_NAME, array('action' => 'authenticate'));*/ }